90 Commits

Author SHA1 Message Date
swanadiva 38c2c6e671 fix: handle null hostOptions when no active hosts exist 2026-07-09 19:41:59 +07:00
swanadiva d5406eab6c fix: terminal WebSocket connection — manage xterm containers in JS
- Remove Alpine x-for template for xterm containers (async rendering bug)
- Add static #xterm-wrapper div, JS creates/removes container elements directly
- addTab() uses document.createElement + appendChild for instant DOM
- switchTab() toggles display:block/none, closeTab() removes from DOM
- Add console.log for WebSocket open/close/error debugging
- Terminal now connects on page load
2026-07-09 19:28:15 +07:00
swanadiva 71864336f6 fix: terminal WebSocket connection timing + better mock fallback
- Fix xterm.js container not found: use requestAnimationFrame retry loop
  instead of single $nextTick (Alpine x-for renders asynchronously)
- Better mock fallback: use host name+IP instead of raw UUID
- Add logging for WebSocket connection path (found/not-found/hostname)
2026-07-09 18:40:35 +07:00
swanadiva ef4e44984b feat: upgrade terminal to xterm.js + WebSocket
- Rewrite terminal.js: xterm.js Terminal per tab, WebSocket per connection
- Light theme terminal (Lumina: white bg, blue cursor, proper ANSI colors)
- Alpine.js keeps tab management, xterm.js handles rendering
- Each tab gets its own WebSocket to /terminal/ws/:hostID
- Mock handler iterates chars (fixes multi-char xterm.js messages)
- Sync mock commands with React template (help, ls, docker ps, etc.)
- Add xterm.css custom scrollbar styles
- terminal_content.html: xterm containers with Alpine show/hide per tab
2026-07-09 18:32:33 +07:00
swanadiva 7accb86203 feat: add transfer panel to dashboard + remove PERBAIKANUI.md
- Add Background Transfers section with mock download/upload rows
- Progress bars with green glow shadow, source/destination layout
- Empty state when no transfers active
- Delete PERBAIKANUI.md (all UI tasks complete)
2026-07-09 18:27:47 +07:00
swanadiva 56eaf57649 fix: modal scroll, SSH key textarea, nav full-page, remove OS/Provider
- Fix modal scroll: restructure overlay with scroll/centering wrapper
- Add SSH key textarea + file upload to host modal (authType='key')
- Fix textarea reset on new host (clear via DOM)
- SSH username placeholder instead of default 'root'
- Nav uses plain <a href> instead of HTMX for full-page navigation
- /hosts route returns full page; /hosts/list for HTMX partials
- Remove OS and Provider from host modal, grid card, and list card
- Fix key modal x-data scope for Alpine $dispatch
- Update key_grid to display multi-line key content properly
- Simplify SSH key placeholder format
2026-07-09 18:21:45 +07:00
swanadiva 5445d15aca fix: include host_modal inside host_list.html so modal works after HTMX nav 2026-07-07 15:59:41 +07:00
swanadiva a2412b7cd2 fix: host modal — single POST endpoint for create+edit, remove hx-put conflict
- hx-put="" (empty) was causing HTMX to send wrong requests
- Now use single hx-post="/hosts" with hidden hostId field
- Server checks hostId: empty → create, present → update
- UpdateHost reads ID from both URL param and form data
2026-07-07 15:56:54 +07:00
swanadiva 301115b74d feat: Host CRUD complete — edit, full form fields, connect, toast
- Add UpdateHost handler + PUT /hosts/:id route
- CreateHost now accepts all fields (port, username, auth, notes)
- host_modal.html: full form with port, username, auth type toggle, edit mode
- host_list.html: edit button dispatches edit-host event with host data
- Connect button links to /terminal?host={id} for pre-selection
- Terminal page reads selected host from query param
- Toast notification system via Alpine.js events
- Add default template function for fallback values
2026-07-07 15:51:57 +07:00
swanadiva 3df8416d9b fix: nav Alpine event name — use htmx:after-settle, not after-settle 2026-07-07 15:39:10 +07:00
swanadiva cdc8b3afd0 fix: nav highlight follows current page via Alpine.js client-side state
- Server-side {{if eq $.View .ID}} only works on initial page load
- HTMX swaps #main-content only, nav never re-renders → stale highlight
- Add x-data page state + @after-settle.window listener to track current route
- Nav items use :class binding to apply active style based on Alpine state
2026-07-07 15:37:16 +07:00
swanadiva e70b133073 fix: add missing _content partial templates for HTMX nav (terminal, sftp, settings, brief)
- Create terminal_content.html, sftp_content.html, settings_content.html, brief_content.html
- Update full page templates to use partial templates via {{template}}
- Handlers already rendered these templates on HX-Request, but files were missing → 500
- All pages now return 200 for both full page and HTMX nav requests
2026-07-07 15:36:12 +07:00
swanadiva 8357d9d76e fix: UI overhaul — align all HTMX views with Lumina Design System (46 fixes)
- All 7 pages rewritten: Dashboard, Terminal, Snippets, Keychain, SFTP, Settings, Brief
- Apply consistent Lumina glassmorphic theme (rounded-2xl, shadows, borders, tracking)
- Fix SVG icons not rendering — return template.HTML instead of string
- Fix Alpine x-data scoping: terminal tabs, SFTP modals, snippet tag buttons
- Fix dashboard search sending literal ?q=...
- Rebuild CSS with all new Tailwind classes (62KB)
- Add .air.toml with hot-reload config, docs/PERBAIKANUI.md checklist
- Remove unused backup partials
2026-07-07 14:55:42 +07:00
swanadiva fd7361aa14 Sprint 6: JSON file persistence + real SSH terminal + V1 crypto/knownhosts integration
- go.mod replace directive for git.tukangketik.id/swanadiva/hostkeeper → ../../v1
- store/ package: JSON file persistence for hosts, snippets, keys, settings
  (~/Library/Application Support/hostkeeper/v2/)
- model SSH fields: Hostname, Port, Username, AuthType, Password, KeyID
- sshconn/ package: real SSH client via golang.org/x/crypto/ssh
- Terminal WS: real SSH connection with fallback to mock shell
- Dynamic host list in terminal (server-rendered JSON script tag)
- All mock data defaults removed from model packages
- Settings persist via store/settings.go
2026-07-07 13:53:50 +07:00
swanadiva 04d9cfb096 feat: Sprint 5 — xterm.js terminal with WebSocket mock shell, Alpine tab management 2026-07-07 13:39:35 +07:00
swanadiva 941a67b6ea feat: Sprint 4 — SFTP dual-pane with per-type icons, breadcrumb, drop-zone, create/delete, toast 2026-07-07 13:35:01 +07:00
swanadiva c5ac07e27f feat: Sprint 3 — settings page with tabs/toggles/devices/danger-zone, brief page 2026-07-07 13:31:13 +07:00
swanadiva c4b0d7d8c0 feat: Sprint 2 — snippets + keychain CRUD, standalone templates, clipboard/utils JS 2026-07-07 13:26:56 +07:00
swanadiva 8cfdec3980 docs: update PROGRESS.md + AGENTS.md to reflect Sprint 1 completion, Sprint 2 in progress 2026-07-07 13:19:33 +07:00
swanadiva 86620b034f feat: Sprint 1 final — delete host, Alpine modal events, grid/list toggle, transfers panel 2026-07-07 13:17:31 +07:00
swanadiva d771925727 feat: Sprint 1 — host model, mock store, dashboard CRUD, HTMX partials 2026-07-07 13:15:56 +07:00
swanadiva 43a19b723a feat: Sprint 0 — GoFiber + HTMX + TailwindCSS v4 scaffolding
- Go module: git.tukangketik.id/swanadiva/hostkeeper/v2
- GoFiber v2 server with static, template engine, middleware
- HTMX + Alpine.js (downloaded from CDN)
- TailwindCSS v4 with custom theme (Lumina System colors)
- Custom CSS: dot-grid, glassmorphism, animations, toggle, modal
- Layout template (sidebar nav + header + main)
- Dashboard page with host list, search, filter, view toggle
- Health endpoint: GET /api/health
2026-07-07 12:18:39 +07:00
swanadiva a0c8483c0e docs: migrate all planning docs from React to GoFiber + HTMX
- New ARCHITECTURE_HTMX.md — comprehensive HTMX architecture doc
- ARCHITECTURE.md — updated to point to HTMX version
- UI_COMPONENTS.md — replaced React tree with HTMX partials
- SPRINT_PLAN.md — all sprint tasks updated for HTMX
- BUILD_SYSTEM.md — simplified (no Vite, no npm)
- TIMELINE.md — 3.5 week HTMX timeline
- PROGRESS.md — updated status + HTMX
- AGENTS.md — updated checkpoint with HTMX decision
2026-07-07 12:15:19 +07:00
swanadiva c215d68c81 refactor: flatten docs/ — move V2 docs from docs/v2/ to docs/
- git mv docs/v2/*.md docs/ (11 planning documents)
- Remove empty docs/v2/ directory
- Update all references: AGENTS.md, CHANGELOG.md, README.md, ARCHITECTURE.md
- Fix outdated repo tree in ARCHITECTURE.md to match actual structure
2026-07-07 12:04:59 +07:00
swanadiva 7794ca554b chore: move V1 plans to v1/docs/plans/ + create root AGENTS.md
- git mv docs/plans/ (V1 planning docs) into v1/docs/plans/
- Create AGENTS.md as AI session checkpoint for seamless continuation
- Root now clean: only V2-related files remain
2026-07-07 12:01:52 +07:00
swanadiva 847989df75 refactor: move V1 code into v1/ subdirectory
- git mv cmd/ internal/ pkg/ test/ go.mod go.sum Makefile build.sh docs/ v1/
- Create v1/README.md with V1 documentation
- Update root README for V1 + V2 structure
- V1 still builds (cd v1 && go build ./cmd/hostkeeper) and 105 tests pass
- Root is now clean for V2 development
2026-07-07 11:56:27 +07:00
swanadiva 8ebdebedc8 chore: V2 planning docs + template discovery 2026-07-07 11:53:16 +07:00
swanadiva 4a8b4a2bc4 test: Phase 3 comprehensive test coverage — 105 tests, zero race conditions
- Add test/crypto/ (19 tests): AES-256-GCM encrypt/decrypt, PBKDF2, IsEncrypted, HashPassword
- Add test/knownhosts/ (14 tests): TOFU verify, MITM detection, CRUD, persistence
- Add test/storage/ (20 tests): KeyPair/Snippet CRUD, encryption, MergeStrategy
- Add test/config/ (9 tests): config lifecycle, path getters
- Add test/tui/ (10 tests): WrapFooter, ClampWidth, TruncateStr
- Fix knownhosts deadlock: Add/Remove use saveInternal()
- Export responsive.go functions for testing
- Add docs/TEST_PLAN.md with full scenario documentation

Coverage: crypto 0%→100%, knownhosts 0%→100%, storage 40%→90%, config 22%→80%, tui 40%→70%
2026-06-29 12:05:02 +07:00
swanadiva 408681c8e4 feat: Phase 2 UX Polish — theme system, config profiles, error banner, tests
- Add Theme struct with 3 predefined themes (dark/light/druntime)
- Add Profile struct for named configuration profiles
- Add ErrorBanner with severity levels and auto-dismiss
- Add unit tests for theme, error banner, and models
- Update CHANGELOG.md and PROJECT_STATE.md
2026-06-29 11:50:46 +07:00
swanadiva 93957e3989 feat: auto-detect encrypted files + CLI --password flag
- Storage.IsDataEncrypted() checks if hosts.json is encrypted
- TUI auto-detects encrypted files, prompts password automatically
- Root command: --password flag for all CLI commands
- newStorage() helper applies password flag to storage
- add/list/edit/delete commands now support encrypted storage
- passwordSetMsg loads hosts after password is set
2026-06-25 14:34:41 +07:00
swanadiva 94f2142d3d feat: encryption password prompt + --encrypt flag
- PasswordPromptTab: setup/unlock modes, password + confirm fields
- --encrypt flag: shows password prompt on TUI startup
- Model.ShowEncryptPrompt() triggers prompt on first render
- passwordSetMsg stores password in Model.storagePassword
- Tab interface: added Close() method to PasswordPromptTab
2026-06-25 13:38:59 +07:00
swanadiva 1d2e29d20a feat: integrate security features into TUI
- SFTPBrowserTab: added storagePassword, passphraseCallback fields
- Model: added storagePassword, knownHosts fields
- cmd/hostkeeper/tui.go: initialize known_hosts on startup
- SFTP connect: wire passphrase callback to SSH client
- SetStoragePassword/SetKnownHosts/SetPassphraseCallback methods
2026-06-25 13:32:59 +07:00
swanadiva 611b794fc7 feat: Phase 2 Security Enhancement
- pkg/crypto: AES-256-GCM encryption with PBKDF2 key derivation
  - 100k iterations, 16-byte salt, SHA-256
  - Encrypt/Decrypt/IsEncrypted/HashPassword
- Storage layer encryption:
  - JSONStorage.SetPassword() enables transparent encrypt/decrypt
  - readJSON auto-decrypts, replace* auto-encrypts
- pkg/knownhosts: TOFU host key verification
  - Verify/Add/Remove host keys
  - HostKeyCallback for SSH config
- SSH client security:
  - SetHostKeyCallback() replaces InsecureIgnoreHostKey()
  - SetPassphraseCallback() for encrypted private keys
  - getKeySigner() tries passphrase on encrypted keys
- Models: AppConfig gains EncryptionEnabled, PasswordHash, KnownHostsFile
2026-06-25 13:28:46 +07:00
swanadiva a1cd3d5dc0 feat: SFTP rename files and directories
- M key enters rename mode with current name pre-filled
- Type new name, Enter to confirm, Esc to cancel
- renameItem: client.Rename() for remote, os.Rename() for local
- Clear cache + refresh after rename
- Footer updated: M:rename
- Filter mode allows M to pass through
2026-06-24 16:27:39 +07:00
swanadiva eb663c2634 fix: SFTP auto-refresh + filter mode + delete refresh
- Clear dirCache before refresh after transfer/delete/mkdir
- Cache was stale: old entries returned instead of fresh data
- Filter mode: allow commands (c,d,n,r) and nav (↑↓,Tab) to pass through
- Filter mode no longer blocks transfer/delete/mkdir/pane-switch
- Delete: clear cache + program.Send() for re-render
- Mkdir: clear cache + program.Send() for re-render
2026-06-24 16:19:56 +07:00
swanadiva 55b5c7b5a0 fix: SFTP auto-refresh after file transfer
- Added program *tea.Program to SFTPBrowserTab and Model
- SetProgram() allows goroutines to send messages to Bubble Tea
- After transfer: program.Send(sftpRefreshMsg{}) triggers re-render
- Model stores program reference, passes to SFTP tab on creation
2026-06-24 14:32:30 +07:00
swanadiva 6b95385094 feat: SFTP file transfer progress bar + auto-refresh
- Progress bar: [████████░░░░] 67% 12.3MB/18.5MB
- progressWriter wraps io.Writer, reports bytes via callback
- Footer shows live progress during upload/download
- Auto-refresh destination pane after transfer completes
- Success message shown for 1 second before clearing
2026-06-24 14:25:11 +07:00
swanadiva a597ea5291 fix: rename SFTP footer C:copy → C:transfer for clarity 2026-06-24 14:11:17 +07:00
swanadiva 8f1f2226f3 perf: SFTP directory listing cache
- Added dirCache map to sftpPane for caching directory listings
- Cache hit: instant navigation (no disk/network I/O)
- Cache miss: read from disk/SFTP, store in cache per path
- R key clears current directory cache and forces fresh read
- Significant speedup when navigating back to previously visited folders
2026-06-24 11:46:17 +07:00
swanadiva 2a8940211c docs: update project status — SFTP polish done, next sprint planned
- Updated project phase to Phase 2
- Next sprint: SFTP performance + file transfer
- Final sprint: security + UX polish
2026-06-24 11:43:36 +07:00
swanadiva 25a53d990b fix: SFTP default to Local pane + fixed border height
- Default active pane changed from Remote to Local on SFTP init
- renderPane now takes maxH parameter for fixed border height
- paneStyle.Height(maxH) prevents border from shrinking/growing on scroll
- Stacked mode: maxH = t.height - 6; Side-by-side: t.height - 5
2026-06-24 11:30:54 +07:00
swanadiva 2e10308c75 fix: SFTP stacked mode — render only active pane + indicator bar
Stacked mode (<50 cols) now shows only the active pane (Local/Remote)
with a visual indicator bar. Tab switches between panes. Side-by-side
mode (>=50 cols) unchanged.
2026-06-24 11:22:21 +07:00
swanadiva c114b2435c docs: document SFTP stacked mode fix plan for next agent 2026-06-23 19:34:55 +07:00
swanadiva 0ab4b5211d docs: update CHANGELOG with SFTP pane width fix details 2026-06-23 19:24:36 +07:00
swanadiva ebd72cf16c fix: SFTP pane width — account for border in halfW calculation, fix innerW to maxW-2 (padding only), truncate filter line
Root cause: lipgloss Width(maxW) = content area inside border, border adds 2 chars extra.
- halfW was t.width/2, should be t.width/2-2 (reserve border per pane)
- innerW was maxW-4, should be maxW-2 (padding only, not border)
- Each pane total = maxW + 2 (content + border)
2026-06-23 19:22:58 +07:00
swanadiva 2cc9392e2b fix: SFTP pane truncation — use lipgloss.Width instead of len(), account for border+padding overhead, compact file listing on narrow panes 2026-06-23 19:15:21 +07:00
swanadiva d75621e9b4 feat: responsive TUI layout — mobile/tablet/desktop support
- NEW responsive.go: wrapFooter, adaptiveSidePad, clampWidth, truncateStr
- Footer auto-wraps to multi-line on narrow terminals (full labels preserved)
- Box width clamped to terminal width across all tabs
- Host/key/snippet rows truncated with ellipsis; compact format <35 cols
- SFTP panes stack vertically when terminal < 50 cols
- Tab bar truncates names on overflow
- Form contentW minimum lowered 50->30 for mobile
- Fixed: key_list_tab & snippet_list_tab dropped last data row (off-by-one bug)
2026-06-23 19:08:44 +07:00
swanadiva d359688b75 docs: add responsive layout plan to PROJECT_STATE.md and CHANGELOG.md 2026-06-23 19:01:31 +07:00
swanadiva a6850b577c docs: update CHANGELOG.md and PROJECT_STATE.md with all fixes 2026-06-23 18:49:07 +07:00
swanadiva 7d41391e13 fix: Space/Left/Right passthrough in host form, key/snippet refresh on save/delete, WindowSize to all tabs, footer improvements 2026-06-23 18:48:50 +07:00
swanadiva 9d0338595d docs: update PROJECT_STATE.md and CHANGELOG.md with recent fixes 2026-06-23 18:21:57 +07:00
swanadiva 07899c154b fix: auto-generate ID+timestamps in storage layer on save 2026-06-23 18:18:10 +07:00
swanadiva 512cf5ce1f fix: add E:edit to footer, generate UUID+timestamps in TUI forms 2026-06-23 18:15:36 +07:00
swanadiva 9b27388455 fix(tui): center rows per-line, fix footers per-context 2026-06-23 18:04:11 +07:00
swanadiva e5d32bd22e fix(tui): unify keybinding footer, remove duplicate status bar 2026-06-23 17:45:06 +07:00
swanadiva 4af555c135 chore: remove committed binary, add to gitignore 2026-06-23 17:15:46 +07:00
swanadiva f9b2337612 fix(tui): restore muted status bar, remove duplicate global keys from tab footers 2026-06-23 17:15:39 +07:00
swanadiva 7f197b9e3a fix(tui): center all tabs, full-screen SFTP, muted inline keybindings 2026-06-23 17:12:12 +07:00
swanadiva c7568e0bf4 feat: clear screen on SSH enter/exit, host list scrolling, 'e' edit key
- tea.Batch(tea.ClearScreen, sshConnectCmd) before SSH starts so TUI
  output doesn't bleed into SSH terminal
- tea.ClearScreen after SSH exits so SSH output doesn't ghost in TUI
- Host list now paginates: only (term_height - 8) / 5 cards shown,
  viewport follows selectedIndex with centered scrolling
- Shows 'N of M hosts' indicator when content is clipped
- Added 'e' key alias for editing host (Ctrl+E or E)
2026-06-23 16:04:38 +07:00
swanadiva 2442920616 feat: centered footer + auth type toggle pills
- Status bar footer centered within terminal width using lipgloss.Width
- Auth Type field replaced with toggle pills (password/key)
  Space/Enter/←/→ cycle between options on the focused field
  Selected type shown with SelectedStyle/TagStyle (green),
  inactive type shown in muted SubtitleStyle
  Help hint 'Space/←/→ to toggle' shown when focused
- Added toggleAuthType() and cycleAuthType() helpers
2026-06-23 15:59:54 +07:00
swanadiva 5b456104e8 fix: form tab input not responding to typing
Bug: t.inputs[t.focus].Update(msg) discarded the returned textinput.Model,
so typed characters were never stored in the input state.

Fix: capture both updated model and cmd from textinput.Update():
  t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
  return t, cmd

Same fix applied to all 3 forms (host, key, snippet).
Also moved ctrl+s out of default to its own case for clarity.
2026-06-23 15:53:32 +07:00
swanadiva daa20ac72b fix: sshCmd closure bug + error display
CRITICAL BUG: sshConnectCmd wrapped tea.ExecProcess inside an extra
closure, so Bubble Tea never executed the SSH process — Enter appeared
to do nothing.

Fix:
- sshConnectCmd now returns tea.ExecProcess directly (no extra closure)
- tea.ExecProcess handles all process lifecycle (start, PTY, exit)
- sshExitMsg errors are shown in host list view (ErrorStyle)
- Error routed via Model.Error → HostListTab.err → View()
2026-06-23 15:50:20 +07:00
swanadiva 79f3917a66 fix: cap vertical padding + horizontal centering per line
- 2 lines top padding instead of aggressive vertical centering
- centerText() uses lipgloss.Width for accurate ANSI-aware centering
- Each card line centered individually within terminal width
- Card width capped at 74 chars
2026-06-23 15:45:13 +07:00
swanadiva 53db03814e feat: centered card-style host list layout
- Each host rendered as a bordered card (HostCardStyle / HostCardActiveStyle)
- Title centered horizontally
- Content constrained to 80 columns max
- Vertical centering padding
- Selected host card gets green border (gbGreen #a9b665)
- Empty state message centered
- Removed old plain-text renderHost/renderSelectedHost functions
2026-06-23 15:42:03 +07:00
swanadiva c957a97cdb feat: dual-pane SFTP browser (local ↔ remote)
Phase B — Tamagosh-inspired dual-pane file browser:
- Left pane: local filesystem (starts at /Users/swanadiva)
- Right pane: remote filesystem via SFTP
- Tab key switches active pane (green border = active)
- Local CWD indicator per pane
- File listing with dir/ file size display
- Filter mode with / key
- Copy files: C key copies from active pane to opposite pane
- Delete (D), mkdir (N on remote), Refresh (R)
- Esc to close
- File size formatting (B/KiB/MiB/GiB)
- Progress message during transfers
- StylePaneActive (green border) / StylePaneInactive (muted border)
2026-06-23 15:38:48 +07:00
swanadiva 7b06793002 feat: native SSH delegation via tea.ExecProcess + Gruvbox palette
Phase A — Tamagosh-inspired redesign:
- Replace goroutine-based SSH (crypto/ssh) with tea.ExecProcess + native ssh binary
- Zero-lag SSH: native binary pegang TTY langsung, ga ada Go buffering
- Password auth via sshpass -e (SSHPASS env)
- Key auth via ssh -i <tmpfile> + SSH_ASKPASS for passphrase
- ControlMaster sockets for fast reconnect
- Add askpass subcommand for SSH_ASKPASS support
- Gruvbox Material Dark Hard palette for comfortable viewing
- Clean up old session messages (openSessionMsg, sessionOutputMsg, sessionDoneMsg)
- Remove 354-line session.go, replace with 150-line ssh.go
2026-06-23 15:36:40 +07:00
swanadiva b319f44c3e docs: update design + impl plan — native SSH delegation, Gruvbox theme, dual-pane SFTP 2026-06-23 15:34:04 +07:00
swanadiva 43858dda87 feat: TUI Key & Snippet Management - Task 19
- KeyListTab: view/add/edit/delete SSH keys (Ctrl+K from host list)
- KeyFormTab: add/edit key form with name, type, private key, passphrase
- SnippetListTab: view/add/edit/delete snippets (Ctrl+P from host list)
- SnippetFormTab: add/edit snippet form with name, command, description, tags
- Updated status bar with new hints
- Save/delete commands for both key pairs and snippets
2026-06-23 15:10:20 +07:00
swanadiva 94ec00c303 feat: TUI SFTP Browser Tab - Task 18
- SFTPBrowserTab with remote directory browsing
- Open via Ctrl+F from host list
- Navigate dirs, filter with /, refresh with r
- Dir/icon display with file sizes
- Sort dirs first, then by name
2026-06-23 15:08:22 +07:00
swanadiva 3dc482e353 feat: TUI Host Forms (add/edit) - Task 17
- HostFormTab with textinput fields for all host fields
- Add (Ctrl+N) and Edit (Ctrl+E) from host list
- Save to JSON storage, auto-reload on save
- Esc to cancel, navigable form with keyboard
2026-06-23 15:05:08 +07:00
swanadiva 809ac1d2e8 fix: session tab I/O — stdin direct write, pollSession triggers re-render 2026-06-23 14:59:48 +07:00
swanadiva 98dfc1c79c feat: Task 16 — SSH Session Tab (multi-session)
- pkg/tui/session.go — SessionTab with live SSH terminal in a tab
- pkg/tui/messages.go — quitMsg, openSessionMsg, sessionOutputMsg
- pkg/tui/tabs.go — Tab.Close() interface, Add() returns tea.Cmd
- pkg/tui/host_list_tab.go — Enter opens session tab, q quits
- pkg/tui/tui.go — handle openSessionMsg/quitMsg, SetDataDir
- cmd/hostkeeper/tui.go — pass dataDir to model
2026-06-23 14:54:44 +07:00
swanadiva 5d9e38f8db feat: Task 15 — TUI Tab Framework + Orange Theme
- pkg/tui/styles.go — orange theme palette and component styles
- pkg/tui/tabs.go — Tab interface + TabManager with add/close/next/prev
- pkg/tui/host_list_tab.go — HostListTab implementing Tab interface
- pkg/tui/tui.go — refactored to use TabManager (backward compatible)
- pkg/tui/host_list.go — removed (logic moved to host_list_tab.go)
- pkg/tui/tui_test.go — adapted + added TabManager tests
2026-06-23 14:51:13 +07:00
swanadiva c5cc3bd711 docs: add Phase 2 tasks 15-19 (TUI Overhaul) to implementation plan 2026-06-23 14:48:32 +07:00
swanadiva e8c451ed56 docs: restructure Phase 2 (TUI priority) + update Phase 3 2026-06-23 14:47:47 +07:00
swanadiva e99a6ac347 docs: rewrite TUI Layer — tab system, orange theme, multi-session SSH 2026-06-23 14:47:30 +07:00
swanadiva 9c1bbd4eac docs: update Key Design Principles — TUI-First + Orange Theme 2026-06-23 14:47:12 +07:00
swanadiva 933ee48f3f docs: update Key Design Decisions — TUI-first architecture 2026-06-23 14:46:55 +07:00
swanadiva b3878de9af feat: Go SSH interactive shell default, --native flag for system SSH 2026-06-23 14:26:58 +07:00
swanadiva 513492e6ee feat: add short ID column to list, improve connect error with hint 2026-06-23 14:23:11 +07:00
swanadiva 1869cff590 fix: host lookup by hostname, interactive input with spaces 2026-06-23 14:16:49 +07:00
swanadiva 48c858df0f feat: complete MVP — all 14 tasks done
- Task 13: Full documentation (README, INSTALLATION, USAGE, ARCHITECTURE)
- Task 14: Release prep (CHANGELOG, RELEASE_CHECKLIST)
- Update PROJECT_STATE.md to reflect 100% completion
2026-06-23 14:06:31 +07:00
swanadiva c2d6aabea0 feat: add build system and integration tests
- Update Makefile with test-coverage and verify targets
- Add build.sh script for cross-platform builds with SHA256 checksums
- Implement integration tests for full workflow (add/list/get/update/export/delete)
- Add config integration test
- Update project state documentation
2026-06-23 14:03:08 +07:00
swanadiva 30b57f6084 feat: implement export and import commands
- Add export command with JSON file output and size summary
- Add import command with replace/merge strategies and dry-run preview
- Add integration test for export/import round-trip via storage layer
- Update project state documentation
2026-06-23 13:58:51 +07:00
swanadiva fbe444c3ab feat: implement basic TUI framework with host list
- Add Bubble Tea TUI model with Init/Update/View
- Implement host list screen with keyboard navigation (up/down/enter/q)
- Add styled rendering for hosts, selection, tags
- Create hostkeeper tui CLI command
- Add tests for TUI initialization and host loading
- Update project state documentation
2026-06-23 13:54:49 +07:00
swanadiva d6b810de47 feat: implement edit and delete host commands
- Add edit command with flag-based and interactive update modes
- Add delete command with confirmation prompt and --force flag
- Include delete alias 'rm' for convenience
- Add comprehensive tests for both commands
- Update project state documentation
2026-06-23 13:52:10 +07:00
swanadiva 368b7cdadb feat: implement connect host command with native SSH
- Add connect command with native SSH (default) and direct Go SSH (--direct) modes
- Support host lookup by name or ID
- Build SSH arguments for system SSH client
- Include timeout configuration flag
- Add comprehensive tests for command and SSH arg building
- Update project state documentation
2026-06-23 13:48:05 +07:00
Swana Diva Borneos 4087c5fdc7 feat: add & list commands with deadlock fix
- Add 'add' command: register hosts via flags or interactive prompts
  Supports password/key/both auth, groups, tags, notes, port override
- Add 'list' command: display hosts with filtering and formatting
  Supports --group, --tag filters, --sort, table/json/wide output
- Fix deadlock bug in JSON storage (RLock within Lock)
  Introduced internal list functions that don't lock
  Affects: ListHosts/GetHost/SaveHost/DeleteHost + KeyPair + Snippet
- Add comprehensive tests for add and list commands
- Update PROJECT_STATE.md (Tasks 1-8 complete, ~55% done)
2026-06-23 10:56:04 +07:00
swanadiva 7dfe181b97 docs: update PROJECT_STATE.md - Task 6 complete (CLI Framework Setup)
- Mark Task 6 (CLI Framework Setup) as complete
- Update completion matrix: CLI Framework 100%, Testing ~30%
- Update overall progress to ~45%
- Mark Milestone 1 (Foundation) as COMPLETE
- Update sprint tracking and roadmap
2026-06-22 16:23:27 +07:00
swanadiva 2bb9d18f57 feat: Implement CLI framework with Cobra
- Add root command with Cobra framework
- Implement shell completion support for bash/zsh/fish/powershell
- Add version command
- Add configuration initialization on startup via PersistentPreRunE
- Include verbose (-v/-vv) and debug flags
- Set up proper error handling and exit codes

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-22 16:21:43 +07:00
161 changed files with 24896 additions and 329 deletions
+6 -1
View File
@@ -39,4 +39,9 @@ Thumbs.db
*.local.json *.local.json
# Build output # Build output
dist/ dist/hostkeeper
v1/hostkeeper
# Node dependencies (for TailwindCSS build)
node_modules/
package-lock.json
+221
View File
@@ -0,0 +1,221 @@
# Hostkeeper V2 — AI Session Checkpoint
> **Purpose**: Memungkinkan AI agent berikutnya melanjutkan development tanpa mengulang atau merusak.
> **Last Updated**: 2026-07-07
> **Current Phase**: UI Fix — memperbaiki 107 visual issue dari `docs/PERBAIKANUI.md`
---
## 1. Repository Structure
```
hostkeeper/ (root — bersih untuk V2)
├── v1/ ← FROZEN — V1 CLI/TUI, jangan disentuh
│ ├── cmd/hostkeeper/ V1 cobra CLI commands
│ ├── internal/errors/ V1 error handling
│ ├── internal/models/ V1 data models
│ ├── pkg/ Shared packages (ssh, crypto, storage, config, knownhosts, tui)
│ ├── test/ V1 integration & unit tests (105 passing)
│ ├── docs/plans/ V1 design & implementation docs
│ ├── go.mod module git.tukangketik.id/swanadiva/hostkeeper
│ ├── Makefile
│ └── PROJECT_STATE.md V1 full project state
├── app/ ← V2 backend GoFiber + views + static
├── mobile/ ← (BELUM DIBUAT) V2 mobile wrapper
├── template/ ← Referensi UI React (Lumina System) — hanya untuk desain
│ └── src/components/ 7 React screens
├── docs/ ← Dokumentasi perencanaan V2 (HTMX)
│ ├── ARCHITECTURE_HTMX.md Arsitektur HTMX (dokumen utama)
│ ├── ARCHITECTURE.md Ringkasan + pointer ke HTMX
│ ├── API.md REST + WebSocket spec
│ ├── DATA_MODELS.md Data models (Host, Snippet, Key, dll)
│ ├── UI_COMPONENTS.md HTMX component tree (bukan React)
│ ├── SPRINT_PLAN.md Sprint 0-6 untuk HTMX
│ ├── BUILD_SYSTEM.md Build pipeline (Go + CSS, tanpa Vite)
│ ├── TIMELINE.md Timeline 3.5 minggu
│ ├── PERFROMANCE.md Performance & stability
│ ├── UI_TERMIUS_REFERENCE.md Termius visual reference
│ ├── PROGRESS.md Status tracker
│ └── PERBAIKANUI.md UI fix checklist (107 task)
├── AGENTS.md ← file ini (checkpoint AI)
└── README.md
Git branches:
- main → V2 development (current)
- v1-snapshot → V1 snapshot before move (safety backup)
```
---
## 2. V1 Status — FROZEN 🧊
| Aspek | Detail |
|-------|--------|
| Kode | Semua di `v1/` — cmd/, internal/, pkg/, test/ |
| Build | `cd v1 && go build ./cmd/hostkeeper` |
| Test | `cd v1 && go test ./...` — 105 tests passing |
| Branch backup | `v1-snapshot` — snapshot sebelum dipindah ke subdirektori |
| Aturan | **JANGAN** mengubah file di `v1/` |
---
## 3. V2 Architecture — HTMX (Keputusan Penting)
**Hostkeeper V2 menggunakan GoFiber + HTMX, BUKAN React.**
Alasan:
- Developer lebih nyaman dengan Go daripada JavaScript
- ~90% kode adalah Go + HTML template
- Hanya ~410 baris JS yang diperlukan (xterm.js, clipboard, toggle)
- Build lebih sederhana — tanpa Vite, npm, TypeScript, Webpack
- Bisa berjalan di browser biasa tanpa Electron
```
┌───────────────────────────────────────────────────┐
│ Browser / Electron WebView │
│ ┌─────────────────────────────────────────────┐ │
│ │ HTMX (14kb) + Alpine.js (15kb) + xterm.js │ │
│ │ ● HTMX: search, filter, modal, form, nav │ │
│ │ ● Alpine: client state (toast, toggle) │ │
│ │ ● xterm.js: terminal (halaman terminal) │ │
│ │ ● Vanilla JS: clipboard, toggle, utils │ │
│ └────────────────┬────────────────────────────┘ │
│ │ hx-get/hx-post/hx-ws │
│ ┌────────────────▼────────────────────────────┐ │
│ │ GoFiber v2 (localhost:1947) │ │
│ │ ┌──────────────┐ ┌────────────────────┐ │ │
│ │ │ HTML handler │ │ WebSocket/SSH │ │ │
│ │ │ (html/templ.) │ │ (xterm.js I/O) │ │ │
│ │ └──────┬───────┘ └────────────────────┘ │ │
│ │ ┌────▼────┐ │ │
│ │ │ v1/pkg/ │ (via replace directive) │ │
│ │ └─────────┘ │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
```
| Library | Ukuran | Fungsi |
|---------|--------|--------|
| HTMX | 14kb | HTML-over-HTTP interaktivitas |
| Alpine.js | 15kb | Client state (modal, toast, tab) |
| xterm.js | ~100kb | Terminal emulator (WAJIB) |
| TailwindCSS v4 | ~27kb | Utility-first CSS |
---
## 4. V2 Status — Sprint 0—6 Complete
### ✅ Sudah Selesai
- Semua dokumentasi diupdate ke HTMX (10 file di `docs/`)
- Template UI dianalisis (Lumina System — bright-tech glassmorphic, TailwindCSS v4)
- Root dibersihkan — V1 di `v1/`, V2 siap dimulai di `app/`
- `template/` tetap sebagai referensi desain (warna, layout, spacing)
- Bug template sudah diidentifikasi (animasi CSS, w-4.5, error boundary, dll)
- **Sprint 0**: GoFiber v2 server + HTMX + Alpine.js + TailwindCSS v4 + custom CSS + layout + nav + health endpoint
- **Sprint 1**: Host model (8 mock hosts), dashboard CRUD, search/filter HTMX, grid/list Alpine toggle, add host modal (Alpine events), delete host (hx-delete), transfers panel
- **Sprint 2**: Snippets + Keychain CRUD, clipboard.js, utils.js
- **Sprint 3**: Settings + Brief, tabs, toggles, danger zone
- **Sprint 4**: SFTP Dual-Pane, breadcrumb, file icons by type, create/delete
- **Sprint 5**: Terminal + xterm.js + WebSocket mock shell, tab management
- **Sprint 6**: JSON file persistence (store package), `go.mod replace` directive for V1 crypto+knownhosts, model SSH fields, real SSH client for terminal (falls back to mock), dynamic host list from server
### 🐛 UI Fix Checklist — Lihat `docs/PERBAIKANUI.md`
- **107 task** teridentifikasi dari audit visual vs template React
- Acuan utama: 7 file di `template/src/components/`
- Setiap task dihapus dari checklist setelah selesai
- Urutan: Dashboard (P0) → Terminal (P0) → Snippets (P0) → Keychain/SFTP/Settings/Brief (P1)
---
## 5. Struktur Folder V2 (Aktual)
```
app/backend/
├── main.go ← Fiber app entry
├── go.mod ← module git.tukangketik.id/swanadiva/hostkeeper/v2
├── internal/
│ ├── handler/ ← HTTP handlers (render HTML)
│ │ ├── dashboard.go
│ │ ├── snippets.go
│ │ ├── keychain.go
│ │ ├── terminal.go
│ │ ├── sftp.go
│ │ ├── settings.go
│ │ ├── brief.go
│ │ └── health.go
│ ├── model/ ← Go structs (Host, Snippet, Key, dll)
│ │ ├── host.go
│ │ ├── snippet.go
│ │ └── keychain.go
│ ├── store/ ← JSON file persistence (store package)
│ │ ├── store.go
│ │ ├── host.go
│ │ ├── snippet.go
│ │ ├── key.go
│ │ ├── settings.go
│ │ └── devices.go
│ ├── sshconn/ ← Real SSH client for terminal
│ │ └── client.go
│ ├── template/ ← Template helper funcs
│ └── middleware/ ← View data injection
├── static/
│ ├── css/ ← output.css + custom.css
│ ├── js/ ← htmx.min.js, alpine.min.js, utils.js, clipboard.js, terminal.js
│ └── xterm/ ← xterm.js lib
└── views/ ← Semua template flat (tidak ada subfolder partials/)
├── nav.html
├── index.html
├── host_list.html
├── host_modal.html
├── snippets.html
├── snippet_grid.html
├── snippet_modal.html
├── keychain.html
├── key_grid.html
├── key_modal.html
├── terminal.html
├── sftp.html
├── settings.html
└── brief.html
```
---
## 6. Yang Harus Dilakukan Selanjutnya (UI Fix)
1. Baca `docs/PERBAIKANUI.md` — 107 task teridentifikasi
2. Urutan: Dashboard (P0) → Terminal (P0) → Snippets (P0) → Keychain (P1) → SFTP (P1) → Settings (P1) → Brief (P1) → Global (P1)
3. Setiap selesai satu task, hapus dari checklist `docs/PERBAIKANUI.md`
4. Verify: `cd app/backend && go build && ./backend` lalu buka http://localhost:1947
---
## 7. Path Penting & Referensi
| Untuk | Lihat di |
|-------|----------|
| Arsitektur HTMX lengkap | `docs/ARCHITECTURE_HTMX.md` |
| API spec | `docs/API.md` |
| Data models (Go struct) | `docs/DATA_MODELS.md` |
| HTMX component tree | `docs/UI_COMPONENTS.md` |
| Sprint plan detail | `docs/SPRINT_PLAN.md` |
| Timeline 3.5 minggu | `docs/TIMELINE.md` |
| Build system | `docs/BUILD_SYSTEM.md` |
| Status tracker | `docs/PROGRESS.md` |
| UI fix checklist | `docs/PERBAIKANUI.md` |
| Template desain (React) | `template/AGENTS.md` (Lumina System) |
| Template komponen (referensi) | `template/src/components/` |
| V1 shared packages | `v1/pkg/ssh/`, `v1/pkg/crypto/`, `v1/pkg/storage/`, `v1/pkg/config/`, `v1/pkg/knownhosts/` |
| V1 build & test | `cd v1 && go build ./cmd/hostkeeper && go test ./...` |
---
## 8. Aturan Penting
- **JANGAN** mengubah file di `v1/` — V1 FROZEN
- **JANGAN** mengubah `template/` — itu referensi desain, bukan source aktif
- Semua kode V2 baru di `app/`
- Saat reuse `v1/pkg/*`, pakai `go.mod replace` — jangan copy
- Template React hanya untuk referensi visual (warna, layout, spacing)
- Gunakan TailwindCSS v4 + custom CSS (Lumina System)
- Pakai bahasa Indonesia untuk komunikasi dengan user (swanadiva)
+230
View File
@@ -0,0 +1,230 @@
# Changelog
## [Unreleased] — V2 Planning Complete (2026-06-29)
### Added (V2 Planning Documents)
- `docs/PROGRESS.md` — Status tracker for V2 development
- `docs/ARCHITECTURE.md` — System architecture (GoFiber + React + Electron)
- `docs/API.md` — REST API + WebSocket specification
- `docs/DATA_MODELS.md` — Extended data models (Groups, PortForward, Workspace)
- `docs/UI_COMPONENTS.md` — React component tree + state management
- `docs/UI_TERMIUS_REFERENCE.md` — Termius visual reference
- `docs/SPRINT_PLAN.md` — Sprint-by-sprint task breakdown
- `docs/BUILD_SYSTEM.md` — Cross-platform build pipeline
- `docs/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 (60100), 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)
### Added
- Initial release of Hostkeeper SSH/SFTP management tool
- **Host management**: CRUD operations for SSH hosts (add, list, edit, delete)
- **SSH connections**: Native SSH (default) and Go SSH direct mode
- **TUI interface**: Interactive host browser using Bubble Tea
- **Export/Import**: JSON export and import with merge/replace strategies
- **Cross-platform builds**: Support for Linux, macOS, Windows, Termux
- **Shell completion**: Bash, Zsh, Fish, and PowerShell support
- **Configuration**: File-based credential storage with `0600` permissions
- **Tag and group**: Host categorization with tags and groups
- **Search and filter**: Filter hosts by group, tag, or text search
### Commands
- `hostkeeper add` — Add SSH hosts (interactive and flag-based)
- `hostkeeper list` — List hosts with table/JSON output
- `hostkeeper connect` — Connect to hosts with custom timeout
- `hostkeeper edit` — Edit host configurations
- `hostkeeper delete` — Delete hosts with confirmation
- `hostkeeper export` — Export data to JSON
- `hostkeeper import` — Import data with merge/replace
- `hostkeeper tui` — Terminal user interface
- `hostkeeper completion` — Shell completion generation
- `hostkeeper version` — Version information
### Technical
- Cobra CLI framework for command structure
- Bubble Tea TUI with keyboard navigation
- Go SSH client for direct connections
- Comprehensive test suite with unit and integration tests
- Build automation via Makefile and build.sh
### Notes
- Initial MVP release, all core features functional
- Encrypted storage planned for future release
- 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
+23 -192
View File
@@ -1,209 +1,40 @@
# Hostkeeper 🔐 # Hostkeeper
> **Cross-platform SSH/SFTP management tool with secure credential storage** **Cross-platform SSH/SFTP management tool with secure credential storage**
**🚨 IMPORTANT**: If you're an AI agent or joining this project mid-development, **[read PROJECT_STATE.md first](PROJECT_STATE.md)** for current status and handoff instructions. ## V1 (Legacy) — CLI/TUI
--- V1 adalah versi CLI/TUI yang sudah selesai dan di-freeze. Semua kode ada di folder [`v1/`](v1/).
## 📋 Project Status
**Current Phase**: Planning Complete → Ready for Implementation
**Progress**: 0% implementation, 100% planning
**Estimated Timeline**: 3-4 weeks to MVP
### Quick Links
- 📊 **[PROJECT_STATE.md](PROJECT_STATE.md)** - **START HERE** - Current status & handoff guide
- 🏗️ **[Design Document](docs/plans/2024-06-22-hostkeeper-design.md)** - Architecture & technical decisions
- 📝 **[Implementation Plan](docs/plans/2024-06-22-hostkeeper-implementation.md)** - Detailed development tasks
- 📚 **Documentation Index** - All project documentation
---
## ✨ What is Hostkeeper?
Hostkeeper is a comprehensive SSH/SFTP management tool inspired by [Termius](https://termius.com/), built with Go for maximum cross-platform compatibility.
### Key Features
- 🔐 **Secure credential management** - Safe SSH key and password storage
- 📁 **SFTP file operations** - Built-in file transfer capabilities
- 🔑 **SSH key management** - Generate, import, organize keys
- 📤 **Cross-device sync** - Export/import credentials between devices
- 🖥️ **Cross-platform** - Linux, macOS, Windows, Termux (Android)
- 🎨 **TUI interface** - Interactive terminal user interface
-**Fast CLI** - Quick commands for power users
---
## 🚀 Quick Start (For Users)
**Note**: This project is currently in early development. Not yet ready for production use.
### Installation (when ready)
```bash ```bash
# From source cd v1
go install github.com/yourusername/hostkeeper/cmd/hostkeeper@latest
# Or build from source
git clone https://github.com/username/hostkeeper.git
cd hostkeeper
make build make build
./hostkeeper tui
``` ```
### Usage (planned) Lihat [`v1/README.md`](v1/README.md) untuk dokumentasi lengkap.
```bash ## V2 (In Development) — GoFiber + React + Electron
# Add your first host
hostkeeper add
# List all hosts V2 adalah rewrite dengan arsitektur baru:
hostkeeper list - **Backend**: GoFiber v2 (fasthttp) — lokal HTTP server di `app/backend/`
- **Frontend**: React + TypeScript + TailwindCSS v4 di `app/frontend/`
- **Desktop**: Electron wrapper di `app/electron/`
- **Mobile**: WebView shell di `mobile/`
# Connect to host Lihat [docs/](docs/) untuk dokumentasi perencanaan.
hostkeeper connect myserver
# Launch TUI interface ## Struktur Repository
hostkeeper tui
```
---
## 🛠️ Development
### For Developers
**👋 If you're joining development:**
1. **[Read PROJECT_STATE.md first](PROJECT_STATE.md)** - This shows current progress
2. Check [Implementation Plan](docs/plans/2024-06-22-hostkeeper-implementation.md) - See what needs doing
3. Pick up next incomplete task and follow TDD approach
### Getting Started
```bash
# Clone repository
git clone https://github.com/username/hostkeeper.git
cd hostkeeper
# Install dependencies
go mod download
# Run tests
make test
# Build project
make build
# Run application
./build/hostkeeper --help
```
### Tech Stack
- **Language**: Go 1.21+
- **CLI Framework**: [Cobra](https://github.com/spf13/cobra)
- **TUI Framework**: [Bubble Tea](https://github.com/charmbracelet/bubbletea)
- **SSH Library**: [golang.org/x/crypto/ssh](https://pkg.go.dev/golang.org/x/crypto/ssh)
---
## 📚 Documentation Structure
``` ```
docs/ hostkeeper/
├── plans/ ├── v1/ ← V1 CLI/TUI (frozen)
│ ├── 2024-06-22-hostkeeper-design.md # Architecture & design decisions ├── app/ ← V2 backend + frontend + electron
│ └── 2024-06-22-hostkeeper-implementation.md # Step-by-step implementation guide ├── mobile/ ← V2 mobile wrapper
├── INSTALLATION.md # Installation guide (to be created) ├── template/ ← Referensi UI React (Lumina System)
── USAGE.md # User documentation (to be created) ── docs/ ← Dokumentasi perencanaan V2
└── ARCHITECTURE.md # Technical architecture (to be created)
``` ```
### Recommended Reading Order ## License
1. **[PROJECT_STATE.md](PROJECT_STATE.md)** ⭐ *Start here for current status* MIT
2. **[Design Document](docs/plans/2024-06-22-hostkeeper-design.md)** - Understanding the system
3. **[Implementation Plan](docs/plans/2024-06-22-hostkeeper-implementation.md)** - How to build it
---
## 🎯 Development Roadmap
### MVP (Current Focus)
- ✅ Complete planning and design
- 🔲 Core SSH connection management
- 🔲 Host CRUD operations
- 🔲 Basic TUI interface
- 🔲 Export/import functionality
- 🔲 Cross-platform builds
### Phase 2 (Enhanced Features)
- 🔳 Encrypted credential storage
- 🔳 SFTP TUI browser
- 🔳 SSH key generation
- 🔳 Connection snippets
### Phase 3 (Advanced Features)
- 🔳 Cloud sync
- 🔳 Custom terminal emulator
- 🔳 Web interface
- 🔳 Plugin system
---
## 🤝 Contributing
**For new contributors and AI agents:**
1. **[Read PROJECT_STATE.md](PROJECT_STATE.md)** first to understand current progress
2. Check [implementation plan](docs/plans/2024-06-22-hostkeeper-implementation.md) for next tasks
3. Follow TDD approach (test → code → refactor)
4. Update PROJECT_STATE.md after completing work
### Development Setup
See [PROJECT_STATE.md](PROJECT_STATE.md) for detailed development workflow and handoff procedures.
---
## 📊 Current Status
| Component | Status |
|-----------|--------|
| Planning & Design | ✅ Complete |
| Implementation | 🔲 Not Started |
| Testing | 🔲 Not Started |
| Documentation | ✅ Complete (technical docs) |
**Next Steps**: Start implementation following the [implementation plan](docs/plans/2024-06-22-hostkeeper-implementation.md)
---
## 📞 Support
- 📖 **[Documentation](docs/)**
- 🐛 [Issue Tracker](https://github.com/username/hostkeeper/issues)
- 💬 [Discussions](https://github.com/username/hostkeeper/discussions)
---
## 📄 License
MIT License - see [LICENSE](LICENSE) file for details
---
## 🙏 Acknowledgments
- Inspired by [Termius](https://termius.com/)
- Reference implementation: [tamagosh](https://github.com/Candratama/tamagosh)
- Built with excellent open-source tools:
- [Cobra](https://github.com/spf13/cobra) - CLI framework
- [Bubble Tea](https://github.com/charmbracelet/bubbletea) - TUI framework
- [golang.org/x/crypto/ssh](https://pkg.go.dev/golang.org/x/crypto/ssh) - SSH library
---
**📌 Remember**: If you're continuing development work, always check [PROJECT_STATE.md](PROJECT_STATE.md) first to see what's been done and what needs to happen next!
+35
View File
@@ -0,0 +1,35 @@
root = "."
tmp_dir = "tmp"
[build]
cmd = "go build -o ./tmp/backend main.go"
full_bin = "./tmp/backend"
delay = 200
exclude_dir = ["assets", "tmp", "vendor", "node_modules"]
exclude_file = []
exclude_regex = []
exclude_unchanged = false
follow_symlink = false
include_dir = ["internal", "views", "static", "."]
include_ext = ["go", "html", "css", "js"]
include_file = ["main.go"]
kill_delay = "0s"
log = "build-errors.log"
send_interrupt = false
stop_on_error = false
[color]
app = ""
build = "yellow"
main = "green"
runner = "cyan"
watcher = "blue"
[log]
time = false
[misc]
clean_on_exit = true
[screen]
clear_on_rebuild = false
+4
View File
@@ -0,0 +1,4 @@
# Air hot-reload build artifacts
tmp/
build-errors.log
+33
View File
@@ -0,0 +1,33 @@
module git.tukangketik.id/swanadiva/hostkeeper/v2
go 1.26.4
require (
git.tukangketik.id/swanadiva/hostkeeper v1.0.0
github.com/gofiber/contrib/websocket v1.3.4
github.com/gofiber/fiber/v2 v2.52.14
github.com/gofiber/template/html/v2 v2.1.3
)
require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.5.0 // indirect
github.com/fasthttp/websocket v1.5.8 // indirect
github.com/gofiber/template v1.8.3 // indirect
github.com/gofiber/utils v1.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.52.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/crypto v0.53.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sys v0.46.0 // indirect
)
replace git.tukangketik.id/swanadiva/hostkeeper => ../../v1
+53
View File
@@ -0,0 +1,53 @@
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
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/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/fasthttp/websocket v1.5.8 h1:k5DpirKkftIF/w1R8ZzjSgARJrs54Je9YJK37DL/Ah8=
github.com/fasthttp/websocket v1.5.8/go.mod h1:d08g8WaT6nnyvg9uMm8K9zMYyDjfKyj3170AtPRuVU0=
github.com/gofiber/contrib/websocket v1.3.4 h1:tWeBdbJ8q0WFQXariLN4dBIbGH9KBU75s0s7YXplOSg=
github.com/gofiber/contrib/websocket v1.3.4/go.mod h1:kTFBPC6YENCnKfKx0BoOFjgXxdz7E85/STdkmZPEmPs=
github.com/gofiber/fiber/v2 v2.52.14 h1:Of3L+9qVFaQNwPlcmEdl5IIodHz8BSE0j37R7rWu4pE=
github.com/gofiber/fiber/v2 v2.52.14/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
github.com/gofiber/template v1.8.3 h1:hzHdvMwMo/T2kouz2pPCA0zGiLCeMnoGsQZBTSYgZxc=
github.com/gofiber/template v1.8.3/go.mod h1:bs/2n0pSNPOkRa5VJ8zTIvedcI/lEYxzV3+YPXdBvq8=
github.com/gofiber/template/html/v2 v2.1.3 h1:n1LYBtmr9C0V/k/3qBblXyMxV5B0o/gpb6dFLp8ea+o=
github.com/gofiber/template/html/v2 v2.1.3/go.mod h1:U5Fxgc5KpyujU9OqKzy6Kn6Qup6Tm7zdsISR+VpnHRE=
github.com/gofiber/utils v1.1.0 h1:vdEBpn7AzIUJRhe+CiTOJdUcTg4Q9RK+pEa0KPbLdrM=
github.com/gofiber/utils v1.1.0/go.mod h1:poZpsnhBykfnY1Mc0KeEa6mSHrS3dV0+oBWyeQmb2e0=
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/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
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/savsgio/gotils v0.0.0-20240303185622-093b76447511 h1:KanIMPX0QdEdB4R3CiimCAbxFrhB3j7h0/OvpYGVQa8=
github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511/go.mod h1:sM7Mt7uEoCeFSCBM+qBrqvEo+/9vdmj19wzp3yzUhmg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.52.0 h1:wqBQpxH71XW0e2g+Og4dzQM8pk34aFYlA1Ga8db7gU0=
github.com/valyala/fasthttp v1.52.0/go.mod h1:hf5C4QnVMkNXMspnsUlfM3WitlgYflyhHYoKol/szxQ=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+15
View File
@@ -0,0 +1,15 @@
package handler
import "github.com/gofiber/fiber/v2"
func Brief(c *fiber.Ctx) error {
data := fiber.Map{
"View": "brief",
"Title": "Quick Brief",
"NavItems": navItems,
}
if c.Get("HX-Request") != "" {
return c.Render("brief_content", data)
}
return c.Render("brief", data)
}
+172
View File
@@ -0,0 +1,172 @@
package handler
import (
"strconv"
"github.com/gofiber/fiber/v2"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/store"
)
var hostStore = store.NewHostStore()
var navItems = []fiber.Map{
{"ID": "hosts", "Label": "Hosts", "Icon": "server"},
{"ID": "terminal", "Label": "Terminal", "Icon": "terminal"},
{"ID": "sftp", "Label": "SFTP", "Icon": "folder-sync"},
{"ID": "snippets", "Label": "Snippets", "Icon": "code2"},
{"ID": "keychain", "Label": "Keychain", "Icon": "key-round"},
{"ID": "settings", "Label": "Settings", "Icon": "settings2"},
}
func Dashboard(c *fiber.Ctx) error {
hosts := hostStore.All()
transfers := []model.Transfer{
{ID: "1", FileName: "backup_v4.tar.gz", Source: "production-api-01", Destination: "Local Machine", Progress: 82, Speed: "12.4 MB/s", Type: "download", Status: "transferring"},
{ID: "2", FileName: "assets_deploy.zip", Source: "Local Storage", Destination: "web-frontend-02", Progress: 35, Speed: "4.8 MB/s", Type: "upload", Status: "transferring"},
}
return c.Render("index", fiber.Map{
"View": "hosts",
"Title": "Hosts",
"Hosts": hosts,
"Active": countByStatus(hosts, "active"),
"Offline": countByStatus(hosts, "offline"),
"NavItems": navItems,
"Transfers": transfers,
})
}
func DashboardList(c *fiber.Ctx) error {
q := c.Query("q")
filter := c.Query("filter", "all")
hosts := hostStore.Search(q, filter)
return c.Render("host_list", fiber.Map{
"Hosts": hosts,
"Active": countByStatus(hosts, "active"),
"Offline": countByStatus(hosts, "offline"),
})
}
func parsePort(s string, def int) int {
i, err := strconv.Atoi(s)
if err != nil || i < 1 || i > 65535 {
return def
}
return i
}
func CreateHost(c *fiber.Ctx) error {
hostID := c.FormValue("hostId")
if hostID != "" {
return UpdateHost(c)
}
name := c.FormValue("name")
ip := c.FormValue("ip")
if name == "" || ip == "" {
return c.Status(400).SendString("name and ip required")
}
h := model.Host{
Name: name,
IP: ip,
OS: c.FormValue("os"),
Provider: c.FormValue("provider"),
Type: c.FormValue("type"),
Port: parsePort(c.FormValue("port"), 22),
Username: c.FormValue("username"),
AuthType: c.FormValue("authType"),
Password: c.FormValue("password"),
Hostname: c.FormValue("hostname"),
Notes: c.FormValue("notes"),
}
if h.Username == "" {
h.Username = "root"
}
if h.AuthType == "" {
h.AuthType = "key"
}
hostStore.AddFull(h)
hosts := hostStore.All()
return c.Render("host_list", fiber.Map{
"Hosts": hosts,
"Active": countByStatus(hosts, "active"),
"Offline": countByStatus(hosts, "offline"),
})
}
func UpdateHost(c *fiber.Ctx) error {
id := c.Params("id")
if id == "" {
id = c.FormValue("hostId")
}
existing, found := hostStore.Get(id)
if !found {
return c.Status(404).SendString("host not found")
}
if v := c.FormValue("name"); v != "" {
existing.Name = v
}
if v := c.FormValue("ip"); v != "" {
existing.IP = v
}
if v := c.FormValue("os"); v != "" {
existing.OS = v
}
if v := c.FormValue("provider"); v != "" {
existing.Provider = v
}
if v := c.FormValue("type"); v != "" {
existing.Type = v
}
if v := c.FormValue("port"); v != "" {
existing.Port = parsePort(v, 22)
}
if v := c.FormValue("username"); v != "" {
existing.Username = v
}
if v := c.FormValue("authType"); v != "" {
existing.AuthType = v
}
if v := c.FormValue("password"); v != "" {
existing.Password = v
}
if v := c.FormValue("hostname"); v != "" {
existing.Hostname = v
}
if v := c.FormValue("notes"); v != "" {
existing.Notes = v
}
hostStore.Update(existing)
hosts := hostStore.All()
return c.Render("host_list", fiber.Map{
"Hosts": hosts,
"Active": countByStatus(hosts, "active"),
"Offline": countByStatus(hosts, "offline"),
})
}
func DeleteHost(c *fiber.Ctx) error {
id := c.Params("id")
hostStore.Delete(id)
hosts := hostStore.All()
return c.Render("host_list", fiber.Map{
"Hosts": hosts,
"Active": countByStatus(hosts, "active"),
"Offline": countByStatus(hosts, "offline"),
})
}
func countByStatus(hosts []model.Host, status string) int {
n := 0
for _, h := range hosts {
if h.Status == status {
n++
}
}
return n
}
+10
View File
@@ -0,0 +1,10 @@
package handler
import "github.com/gofiber/fiber/v2"
func Health(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"status": "ok",
"app": "hostkeeper-v2",
})
}
+44
View File
@@ -0,0 +1,44 @@
package handler
import (
"github.com/gofiber/fiber/v2"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/store"
)
var keyStore = store.NewKeyStore()
func Keychain(c *fiber.Ctx) error {
if c.Get("HX-Request") != "" {
return KeyGrid(c)
}
keys := keyStore.All()
return c.Render("keychain", fiber.Map{
"View": "keychain",
"Title": "Keychain",
"Keys": keys,
"NavItems": navItems,
})
}
func KeyGrid(c *fiber.Ctx) error {
q := c.Query("q", "")
keys := keyStore.Search(q)
return c.Render("credential_grid", fiber.Map{"Keys": keys})
}
func CreateKey(c *fiber.Ctx) error {
name := c.FormValue("name")
username := c.FormValue("username")
url := c.FormValue("url")
passphrase := c.FormValue("passphrase")
keyStore.Add(name, username, url, passphrase)
keys := keyStore.All()
return c.Render("credential_grid", fiber.Map{"Keys": keys})
}
func DeleteKey(c *fiber.Ctx) error {
id := c.Params("id")
keyStore.Delete(id)
keys := keyStore.All()
return c.Render("credential_grid", fiber.Map{"Keys": keys})
}
+49
View File
@@ -0,0 +1,49 @@
package handler
import (
"github.com/gofiber/fiber/v2"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/store"
)
var deviceStore = model.NewDeviceStore()
var settingsStore = store.NewSettingsStore()
func Settings(c *fiber.Ctx) error {
data := fiber.Map{
"View": "settings",
"Title": "Settings",
"Config": settingsStore.Get(),
"Devices": deviceStore.All(),
"NavItems": navItems,
}
if c.Get("HX-Request") != "" {
return c.Render("settings_content", data)
}
return c.Render("settings", data)
}
func UpdateConfig(c *fiber.Ctx) error {
cfg := settingsStore.Get()
if v := c.FormValue("theme"); v != "" { cfg.Theme = v }
if v := c.FormValue("fontSize"); v != "" { cfg.FontSize = parseInt(v, 14) }
if v := c.FormValue("scrollback"); v != "" { cfg.Scrollback = parseInt(v, 5000) }
if v := c.FormValue("autoLock"); v != "" { cfg.AutoLock = parseInt(v, 5) }
cfg.Keepalive = c.FormValue("keepalive") == "on"
cfg.CopyOnSelect = c.FormValue("copyOnSelect") == "on"
cfg.BellEnabled = c.FormValue("bellEnabled") == "on"
cfg.AutoReconnect = c.FormValue("autoReconnect") == "on"
cfg.BlinkCursor = c.FormValue("blinkCursor") == "on"
settingsStore.Update(cfg)
return c.Redirect("/settings", 303)
}
func parseInt(s string, def int) int {
i := 0
for _, c := range s {
if c < '0' || c > '9' { return def }
i = i*10 + int(c-'0')
}
if i == 0 { return def }
return i
}
+82
View File
@@ -0,0 +1,82 @@
package handler
import (
"github.com/gofiber/fiber/v2"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
)
var fileStore = model.NewFileStore()
func SFTP(c *fiber.Ctx) error {
local, remote := fileStore.All()
data := fiber.Map{
"View": "sftp",
"Title": "SFTP",
"LocalFiles": local,
"RemoteFiles": remote,
"LocalBreadcrumb": fileStore.LocalBreadcrumb,
"RemoteBreadcrumb": fileStore.RemoteBreadcrumb,
"NavItems": navItems,
}
if c.Get("HX-Request") != "" {
return c.Render("sftp_content", data)
}
return c.Render("sftp", data)
}
func SFTPPane(c *fiber.Ctx) error {
pane := c.Query("pane", "local")
dir := c.Query("dir", "/")
local, remote := fileStore.All()
files := local
breadcrumb := fileStore.LocalBreadcrumb
if pane == "remote" {
files = remote
breadcrumb = fileStore.RemoteBreadcrumb
}
return c.Render("sftp_pane", fiber.Map{
"Pane": pane,
"Files": files,
"Breadcrumb": breadcrumb,
"CurrentDir": dir,
})
}
func CreateFolder(c *fiber.Ctx) error {
pane := c.FormValue("pane", "local")
name := c.FormValue("name")
if name != "" {
item := model.FileItem{
Name: name, Size: "—", Modified: "Just now",
Type: "folder", Permissions: "drwxr-xr-x",
}
if pane == "remote" {
fileStore.Remote = append([]model.FileItem{item}, fileStore.Remote...)
} else {
fileStore.Local = append([]model.FileItem{item}, fileStore.Local...)
}
}
files := fileStore.Local
if pane == "remote" { files = fileStore.Remote }
return c.Render("sftp_pane", fiber.Map{
"Pane": pane, "Files": files,
"Breadcrumb": fileStore.LocalBreadcrumb,
})
}
func DeleteFile(c *fiber.Ctx) error {
pane := c.Query("pane", "local")
name := c.Query("name")
files := &fileStore.Local
if pane == "remote" { files = &fileStore.Remote }
for i, f := range *files {
if f.Name == name {
*files = append((*files)[:i], (*files)[i+1:]...)
break
}
}
return c.Render("sftp_pane", fiber.Map{
"Pane": pane, "Files": *files,
"Breadcrumb": fileStore.LocalBreadcrumb,
})
}
+88
View File
@@ -0,0 +1,88 @@
package handler
import (
"encoding/json"
"github.com/gofiber/fiber/v2"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/store"
)
func jsonOrEmpty(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return "[]"
}
return string(b)
}
func allTags(snippets []model.Snippet) []string {
seen := map[string]bool{}
var out []string
for _, sn := range snippets {
for _, t := range sn.Tags {
if !seen[t] {
seen[t] = true
out = append(out, t)
}
}
}
return out
}
var snippetStore = store.NewSnippetStore()
func Snippets(c *fiber.Ctx) error {
if c.Get("HX-Request") != "" {
return SnippetGrid(c)
}
snippets := snippetStore.All()
return c.Render("snippets", fiber.Map{
"View": "snippets",
"Title": "Snippets",
"Snippets": snippets,
"SnippetsJSON": jsonOrEmpty(snippets),
"AllTags": allTags(snippets),
"NavItems": navItems,
})
}
func SnippetGrid(c *fiber.Ctx) error {
q := c.Query("q", "")
collection := c.Query("collection", "")
tag := c.Query("tag", "")
snippets := snippetStore.Search(q, collection, tag)
return c.Render("snippet_grid", fiber.Map{
"Snippets": snippets,
"SnippetsJSON": jsonOrEmpty(snippets),
})
}
func CreateSnippet(c *fiber.Ctx) error {
name := c.FormValue("name")
content := c.FormValue("content")
language := c.FormValue("language")
description := c.FormValue("description")
collection := c.FormValue("collection")
tagStr := c.FormValue("tags")
var tags []string
if tagStr != "" {
tags = []string{tagStr}
}
snippetStore.Add(name, content, language, tags, description, collection)
snippets := snippetStore.All()
return c.Render("snippet_grid", fiber.Map{
"Snippets": snippets,
"SnippetsJSON": jsonOrEmpty(snippets),
})
}
func DeleteSnippet(c *fiber.Ctx) error {
id := c.Params("id")
snippetStore.Delete(id)
snippets := snippetStore.All()
return c.Render("snippet_grid", fiber.Map{
"Snippets": snippets,
"SnippetsJSON": jsonOrEmpty(snippets),
})
}
+224
View File
@@ -0,0 +1,224 @@
package handler
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"strings"
"time"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/sshconn"
)
func Terminal(c *fiber.Ctx) error {
hosts := hostStore.All()
type hostItem struct {
ID string `json:"id"`
Name string `json:"name"`
IP string `json:"ip"`
}
var available []hostItem
for _, h := range hosts {
if h.Status == "active" {
available = append(available, hostItem{h.ID, h.Name, h.IP})
}
}
hostsJSON, _ := json.Marshal(available)
selectedHost := c.Query("host", "")
data := fiber.Map{
"View": "terminal",
"Title": "Terminal",
"NavItems": navItems,
"Hosts": available,
"HostsJSON": string(hostsJSON),
"SelectedHost": selectedHost,
}
if c.Get("HX-Request") != "" {
return c.Render("terminal_content", data)
}
return c.Render("terminal", data)
}
func TerminalWS(c *websocket.Conn) {
hostID := c.Params("host", "unknown")
log.Printf("WS connected: host=%s", hostID)
host, found := hostStore.Get(hostID)
if !found {
log.Printf("Host %s not found, using mock", hostID)
mockTerminal(c, hostID)
return
}
if host.Hostname == "" {
log.Printf("Host %s has no hostname, using mock (name=%s, ip=%s)", hostID, host.Name, host.IP)
mockTerminal(c, host.Name+" ("+host.IP+")")
return
}
client, err := sshconn.Dial(host)
if err != nil {
log.Printf("SSH failed for %s: %v, falling back to mock", hostID, err)
mockTerminal(c, hostID)
return
}
defer client.Close()
welcome := fmt.Sprintf("\x1b[1;32mConnected to %s (%s)\x1b[0m\r\n", host.Name, host.IP)
c.WriteMessage(websocket.TextMessage, []byte(welcome))
stdinR, stdinW := io.Pipe()
stdoutR, stdoutW := io.Pipe()
go func() {
scanner := bufio.NewScanner(stdoutR)
for scanner.Scan() {
c.WriteMessage(websocket.TextMessage, []byte(scanner.Text()+"\r\n"))
}
}()
go func() {
defer stdinW.Close()
for {
_, msg, err := c.ReadMessage()
if err != nil {
return
}
input := string(msg)
if input == "\x03" {
client.Close()
return
}
stdinW.Write([]byte(input))
}
}()
if err := client.Shell(stdinR, stdoutW, stdoutW, 24, 80); err != nil {
log.Printf("SSH session ended: %v", err)
}
log.Printf("WS disconnected: host=%s", hostID)
}
func mockTerminal(c *websocket.Conn, host string) {
welcome := fmt.Sprintf("\x1b[1;33m%s (mock mode)\x1b[0m\r\n\x1b[2mConnected at %s\x1b[0m\r\n\r\n", host, time.Now().Format(time.RFC822))
c.WriteMessage(websocket.TextMessage, []byte(welcome))
prompt := fmt.Sprintf("\x1b[1;34m%s:~$\x1b[0m ", host)
c.WriteMessage(websocket.TextMessage, []byte(prompt))
cwd := "~"
buf := ""
for {
_, msg, err := c.ReadMessage()
if err != nil {
break
}
for _, ch := range string(msg) {
switch {
case ch == '\r':
output := handleCommand(buf, host, &cwd)
c.WriteMessage(websocket.TextMessage, []byte(output+prompt))
buf = ""
case ch == '\x7f':
if len(buf) > 0 {
buf = buf[:len(buf)-1]
c.WriteMessage(websocket.TextMessage, []byte("\b \b"))
}
case ch == '\x03':
buf = ""
c.WriteMessage(websocket.TextMessage, []byte("^C\r\n"+prompt))
case ch >= ' ' && ch <= '~':
buf += string(ch)
c.WriteMessage(websocket.TextMessage, []byte(string(ch)))
}
}
}
log.Printf("Mock WS disconnected: host=%s", host)
}
func handleCommand(cmd, host string, cwd *string) string {
cmd = strings.TrimSpace(cmd)
if cmd == "" { return "" }
parts := strings.Fields(cmd)
if len(parts) == 0 { return "" }
switch parts[0] {
case "clear":
return "\x1b[2J\x1b[H"
case "exit", "logout":
return "logout\r\n\x1b[2J\x1b[H\x1b[1;31mConnection closed.\x1b[0m\r\n"
case "help":
return "HostKeeper Mock SSH Interactive Command Parser:\r\n" +
" help - Display this support manifest list\r\n" +
" ls - List contents of the current working directory\r\n" +
" docker ps - List simulated running Docker containers on cluster\r\n" +
" uname -a - Show operating system and machine kernel data\r\n" +
" ping 8.8.8.8 - Probe network gateway performance\r\n" +
" cat server.js - Output snippet of remote index server configuration\r\n" +
" keychain - Query keychain credentials loaded for target session\r\n" +
" clear - Wipe the terminal display buffer clean\r\n"
case "ls":
if *cwd == "~" || *cwd == "/home/deploy" {
return "drwxr-xr-x 3 root root 4096 Jul 6 12:00 controllers\r\n" +
"drwxr-xr-x 2 root root 4096 Jul 6 12:00 models\r\n" +
"drwxr-xr-x 2 root root 4096 Jul 6 12:00 routes\r\n" +
"-rw-r--r-- 1 root root 280 Jul 6 11:34 .env\r\n" +
"-rw-r--r-- 1 root root 1432 Jul 6 14:20 package.json\r\n" +
"-rwxr-xr-x 1 root root 8412 Jul 6 15:43 server.js\r\n"
}
return "total 0\r\n"
case "cd":
if len(parts) > 1 { *cwd = parts[1] } else { *cwd = "~" }
return ""
case "docker ps":
return "CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS\r\n" +
"f87a2d12e9b0 node:18-alpine \"docker-entrypoint.s…\" 2 hours ago Up 2 hours 0.0.0.0:3000->3000/tcp\r\n" +
"c23e84bf9211 postgres:15-alpine \"docker-entrypoint.s…\" 5 hours ago Up 5 hours 0.0.0.0:5432->5432/tcp\r\n" +
"78da12b84e0c redis:7-alpine \"docker-entrypoint.s…\" 10 hours ago Up 10 hours 0.0.0.0:6379->6379/tcp\r\n"
case "uname":
if len(parts) > 1 && parts[1] == "-a" {
return fmt.Sprintf("Linux %s 5.15.0-101-generic #111-Ubuntu SMP Wed Jul 6 21:27:00 UTC 2026 x86_64 GNU/Linux\r\n", host)
}
return "Linux\r\n"
case "ping":
return "64 bytes from 8.8.8.8: icmp_seq=1 ttl=116 time=12.4 ms\r\n" +
"64 bytes from 8.8.8.8: icmp_seq=2 ttl=116 time=14.1 ms\r\n" +
"64 bytes from 8.8.8.8: icmp_seq=3 ttl=116 time=11.8 ms\r\n" +
"--- 8.8.8.8 ping statistics ---\r\n" +
"3 packets transmitted, 3 received, 0% packet loss, rtt min/avg/max = 11.8/12.76/14.1 ms\r\n"
case "cat":
if len(parts) > 1 && parts[1] == "server.js" {
return "const express = require(\"express\");\r\n" +
"const app = express();\r\n" +
"const PORT = process.env.PORT || 3000;\r\n" +
"app.get(\"/api/health\", (req, res) => res.send({ status: \"healthy\" }));\r\n" +
"app.listen(PORT, () => console.log(\"Server active on cluster ingress\"));\r\n"
}
if len(parts) > 1 {
return fmt.Sprintf("# Content of %s\r\n(not implemented in mock shell)\r\n", parts[1])
}
return ""
case "keychain":
return "Keychain Credential Mapping Selected:\r\n" +
" Active Key: id_ed25519_alex (ED25519 standard)\r\n" +
" Encryption: AES-256 GCM cryptokey payload\r\n" +
" Fingerprint: SHA256:7mP9K9+fVj5bW0vQ8zD1y2u3t4m5n6p7q8r9s0v1w2x\r\n"
case "whoami":
return "deploy\r\n"
case "hostname":
return host + "\r\n"
case "pwd":
return *cwd + "\r\n"
case "echo":
return strings.Join(parts[1:], " ") + "\r\n"
default:
return fmt.Sprintf("hostkeeper: command not found: \"%s\". Type \"help\" to view custom commands list.\r\n", parts[0])
}
}
@@ -0,0 +1,9 @@
package middleware
import "github.com/gofiber/fiber/v2"
func ViewData() fiber.Handler {
return func(c *fiber.Ctx) error {
return c.Next()
}
}
+39
View File
@@ -0,0 +1,39 @@
package model
type AppConfig struct {
Theme string `json:"theme"` // light | dark
FontSize int `json:"fontSize"` // 12-18
Scrollback int `json:"scrollback"` // 1000-10000
AutoLock int `json:"autoLock"` // minutes
Keepalive bool `json:"keepalive"`
CopyOnSelect bool `json:"copyOnSelect"`
BellEnabled bool `json:"bellEnabled"`
AutoReconnect bool `json:"autoReconnect"`
BlinkCursor bool `json:"blinkCursor"`
}
type ConfigStore struct {
Config AppConfig
}
func NewConfigStore() *ConfigStore {
return &ConfigStore{Config: defaultConfig()}
}
func (s *ConfigStore) Get() AppConfig { return s.Config }
func (s *ConfigStore) Update(cfg AppConfig) { s.Config = cfg }
func defaultConfig() AppConfig {
return AppConfig{
Theme: "light",
FontSize: 14,
Scrollback: 5000,
AutoLock: 5,
Keepalive: true,
CopyOnSelect: true,
BellEnabled: false,
AutoReconnect: true,
BlinkCursor: false,
}
}
+28
View File
@@ -0,0 +1,28 @@
package model
type Device struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"` // desktop | mobile | tablet
OS string `json:"os"`
LastSeen string `json:"lastSeen"`
Current bool `json:"current"`
}
type DeviceStore struct {
Devices []Device
}
func NewDeviceStore() *DeviceStore {
return &DeviceStore{Devices: defaultDevices()}
}
func (s *DeviceStore) All() []Device { return s.Devices }
func defaultDevices() []Device {
return []Device{
{ID: "d1", Name: "MacBook Pro M4", Type: "desktop", OS: "macOS 15 Sequoia", LastSeen: "Just now", Current: true},
{ID: "d2", Name: "iPhone 17 Pro", Type: "mobile", OS: "iOS 20", LastSeen: "2 hours ago", Current: false},
{ID: "d3", Name: "iPad Air M3", Type: "tablet", OS: "iPadOS 20", LastSeen: "Yesterday", Current: false},
}
}
+60
View File
@@ -0,0 +1,60 @@
package model
type FileItem struct {
Name string `json:"name"`
Size string `json:"size"`
Modified string `json:"modified"`
Type string `json:"type"` // folder | file | image | code | lock
Extension string `json:"extension"`
Permissions string `json:"permissions"`
Path string `json:"path"`
}
type FileStore struct {
Local []FileItem
Remote []FileItem
LocalBreadcrumb []Breadcrumb
RemoteBreadcrumb []Breadcrumb
}
type Breadcrumb struct {
Name string
Path string
}
func NewFileStore() *FileStore {
return &FileStore{
Local: defaultLocalFiles(),
Remote: defaultRemoteFiles(),
LocalBreadcrumb: []Breadcrumb{{Name: "~", Path: "/home/user"}, {Name: "projects", Path: "/home/user/projects"}},
RemoteBreadcrumb: []Breadcrumb{{Name: "/", Path: "/"}, {Name: "var", Path: "/var"}, {Name: "www", Path: "/var/www"}},
}
}
func (s *FileStore) All() (local, remote []FileItem) { return s.Local, s.Remote }
func defaultLocalFiles() []FileItem {
return []FileItem{
{Name: "Downloads", Size: "—", Modified: "2 hours ago", Type: "folder", Permissions: "drwxr-xr-x", Path: "/home/user/Downloads"},
{Name: "Documents", Size: "—", Modified: "Yesterday", Type: "folder", Permissions: "drwxr-xr-x", Path: "/home/user/Documents"},
{Name: "projects", Size: "—", Modified: "Just now", Type: "folder", Permissions: "drwxrwxr-x", Path: "/home/user/projects"},
{Name: "config.yml", Size: "1.4 KB", Modified: "Yesterday", Type: "code", Extension: "yml", Permissions: "-rw-r--r--", Path: "/home/user/projects/config.yml"},
{Name: "README.md", Size: "3.2 KB", Modified: "2 days ago", Type: "code", Extension: "md", Permissions: "-rw-r--r--", Path: "/home/user/projects/README.md"},
{Name: "screenshot.png", Size: "240 KB", Modified: "3 days ago", Type: "image", Extension: "png", Permissions: "-rw-r--r--", Path: "/home/user/Downloads/screenshot.png"},
{Name: "archive.zip", Size: "42 MB", Modified: "1 week ago", Type: "file", Extension: "zip", Permissions: "-rw-r--r--", Path: "/home/user/Downloads/archive.zip"},
{Name: "vault.enc", Size: "8 KB", Modified: "2 weeks ago", Type: "lock", Extension: "enc", Permissions: "-rw-------", Path: "/home/user/vault.enc"},
}
}
func defaultRemoteFiles() []FileItem {
return []FileItem{
{Name: "html", Size: "—", Modified: "2 hours ago", Type: "folder", Permissions: "drwxr-xr-x", Path: "/var/www/html"},
{Name: "assets", Size: "—", Modified: "Yesterday", Type: "folder", Permissions: "drwxr-xr-x", Path: "/var/www/assets"},
{Name: "index.html", Size: "4.1 KB", Modified: "Just now", Type: "code", Extension: "html", Permissions: "-rw-r--r--", Path: "/var/www/index.html"},
{Name: "app.py", Size: "12.8 KB", Modified: "2 hours ago", Type: "code", Extension: "py", Permissions: "-rwxr-xr-x", Path: "/var/www/app.py"},
{Name: "Dockerfile", Size: "512 B", Modified: "Yesterday", Type: "code", Extension: "Dockerfile", Permissions: "-rw-r--r--", Path: "/var/www/Dockerfile"},
{Name: "compose.yml", Size: "2.1 KB", Modified: "Yesterday", Type: "code", Extension: "yml", Permissions: "-rw-r--r--", Path: "/var/www/compose.yml"},
{Name: ".env", Size: "156 B", Modified: "3 days ago", Type: "lock", Extension: "env", Permissions: "-rw-------", Path: "/var/www/.env"},
{Name: "logo.svg", Size: "6.7 KB", Modified: "1 week ago", Type: "image", Extension: "svg", Permissions: "-rw-r--r--", Path: "/var/www/assets/logo.svg"},
}
}
+22
View File
@@ -0,0 +1,22 @@
package model
type Host struct {
ID string `json:"id"`
Name string `json:"name"`
IP string `json:"ip"`
OS string `json:"os"`
Provider string `json:"provider"`
Status string `json:"status"`
LastSeen string `json:"lastSeen"`
Type string `json:"type"`
Hostname string `json:"hostname"`
Port int `json:"port"`
Username string `json:"username"`
AuthType string `json:"authType"` // password | key | both
Password string `json:"password,omitempty"`
KeyID string `json:"keyId,omitempty"`
Group string `json:"group,omitempty"`
Tags string `json:"tags,omitempty"`
Notes string `json:"notes,omitempty"`
}
+15
View File
@@ -0,0 +1,15 @@
package model
type Key struct {
ID string `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Passphrase string `json:"passphrase"`
Strength string `json:"strength"`
Type string `json:"type"`
URL string `json:"url"`
Fingerprint string `json:"fingerprint"`
ConnectedHosts []string `json:"connectedHosts"`
KeyFile string `json:"keyFile"`
CreatedAt string `json:"createdAt"`
}
+13
View File
@@ -0,0 +1,13 @@
package model
type Snippet struct {
ID string `json:"id"`
Name string `json:"name"`
Content string `json:"content"`
Language string `json:"language"`
Description string `json:"description"`
Collection string `json:"collection"`
Icon string `json:"icon"`
Tags []string `json:"tags"`
CreatedAt string `json:"createdAt"`
}
+22
View File
@@ -0,0 +1,22 @@
package model
type Transfer struct {
ID string `json:"id"`
FileName string `json:"fileName"`
Source string `json:"source"`
Destination string `json:"destination"`
Progress int `json:"progress"`
Speed string `json:"speed"`
Type string `json:"type"` // upload | download
Status string `json:"status"` // queued | transferring | completed | error
}
type TransferStore struct {
Transfers []Transfer
}
func NewTransferStore() *TransferStore {
return &TransferStore{}
}
func (s *TransferStore) All() []Transfer { return s.Transfers }
+138
View File
@@ -0,0 +1,138 @@
package sshconn
import (
"fmt"
"io"
"net"
"os"
"time"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
gossh "golang.org/x/crypto/ssh"
)
type Client struct {
Host model.Host
client *gossh.Client
session *gossh.Session
stdin io.WriteCloser
stdout io.Reader
stderr io.Reader
}
func Dial(host model.Host) (*Client, error) {
addr := net.JoinHostPort(host.Hostname, fmt.Sprintf("%d", host.Port))
if host.Hostname == "" {
addr = net.JoinHostPort(host.IP, "22")
}
config := &gossh.ClientConfig{
User: host.Username,
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
Timeout: 10 * time.Second,
}
switch host.AuthType {
case "password", "":
config.Auth = []gossh.AuthMethod{
gossh.Password(host.Password),
}
case "key":
key, err := loadPrivateKey(host.Password)
if err != nil {
return nil, fmt.Errorf("load key: %w", err)
}
config.Auth = []gossh.AuthMethod{
gossh.PublicKeys(key),
}
case "both":
key, err := loadPrivateKey(host.Password)
if err != nil {
return nil, fmt.Errorf("load key: %w", err)
}
config.Auth = []gossh.AuthMethod{
gossh.Password(host.Password),
gossh.PublicKeys(key),
}
default:
return nil, fmt.Errorf("unknown auth type: %s", host.AuthType)
}
client, err := gossh.Dial("tcp", addr, config)
if err != nil {
return nil, fmt.Errorf("dial: %w", err)
}
return &Client{
Host: host,
client: client,
}, nil
}
func (c *Client) Shell(stdin io.Reader, stdout io.Writer, stderr io.Writer, rows, cols int) error {
session, err := c.client.NewSession()
if err != nil {
return fmt.Errorf("session: %w", err)
}
c.session = session
modes := gossh.TerminalModes{
gossh.ECHO: 1,
gossh.TTY_OP_ISPEED: 14400,
gossh.TTY_OP_OSPEED: 14400,
}
if err := session.RequestPty("xterm-256color", rows, cols, modes); err != nil {
return fmt.Errorf("pty: %w", err)
}
c.stdin, _ = session.StdinPipe()
c.stdout, _ = session.StdoutPipe()
c.stderr, _ = session.StderrPipe()
go io.Copy(stdout, c.stdout)
go io.Copy(stderr, c.stderr)
go io.Copy(c.stdin, stdin)
if err := session.Shell(); err != nil {
return fmt.Errorf("shell: %w", err)
}
return session.Wait()
}
func (c *Client) Resize(rows, cols int) error {
if c.session == nil {
return nil
}
return c.session.WindowChange(rows, cols)
}
func (c *Client) Close() error {
if c.session != nil {
c.session.Close()
}
return c.client.Close()
}
func (c *Client) IsConnected() bool {
return c.client != nil
}
func loadPrivateKey(keyContent string) (gossh.Signer, error) {
if keyContent == "" {
paths := []string{
os.ExpandEnv("$HOME/.ssh/id_ed25519"),
os.ExpandEnv("$HOME/.ssh/id_rsa"),
os.ExpandEnv("$HOME/.ssh/id_ecdsa"),
}
for _, p := range paths {
data, err := os.ReadFile(p)
if err == nil {
return gossh.ParsePrivateKey(data)
}
}
return nil, fmt.Errorf("no SSH key found")
}
return gossh.ParsePrivateKey([]byte(keyContent))
}
+32
View File
@@ -0,0 +1,32 @@
package store
import "git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
type DeviceStore struct {
devices []model.Device
}
func NewDeviceStore() *DeviceStore {
s := &DeviceStore{devices: defaultDevices()}
mu.RLock()
readFile("devices.json", &s.devices)
mu.RUnlock()
if s.devices == nil {
s.devices = defaultDevices()
}
return s
}
func (s *DeviceStore) All() []model.Device {
mu.RLock()
defer mu.RUnlock()
return s.devices
}
func defaultDevices() []model.Device {
return []model.Device{
{ID: "d1", Name: "MacBook Pro M4", Type: "desktop", OS: "macOS 15 Sequoia", LastSeen: "Just now", Current: true},
{ID: "d2", Name: "iPhone 17 Pro", Type: "mobile", OS: "iOS 20", LastSeen: "2 hours ago", Current: false},
{ID: "d3", Name: "iPad Air M3", Type: "tablet", OS: "iPadOS 20", LastSeen: "Yesterday", Current: false},
}
}
+129
View File
@@ -0,0 +1,129 @@
package store
import "git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
type HostStore struct {
hosts []model.Host
}
func NewHostStore() *HostStore {
s := &HostStore{}
mu.RLock()
readFile("hosts.json", &s.hosts)
mu.RUnlock()
if s.hosts == nil {
s.hosts = []model.Host{}
}
return s
}
func (s *HostStore) All() []model.Host {
mu.RLock()
defer mu.RUnlock()
return s.hosts
}
func (s *HostStore) Search(q, filter string) []model.Host {
mu.RLock()
defer mu.RUnlock()
var result []model.Host
for _, h := range s.hosts {
if filter != "" && filter != "all" && h.Status != filter {
continue
}
if q == "" || contains(h.Name, q) || contains(h.IP, q) || contains(h.OS, q) ||
contains(h.Hostname, q) || contains(h.Username, q) {
result = append(result, h)
}
}
if result == nil {
return []model.Host{}
}
return result
}
func (s *HostStore) Get(id string) (model.Host, bool) {
mu.RLock()
defer mu.RUnlock()
for _, h := range s.hosts {
if h.ID == id {
return h, true
}
}
return model.Host{}, false
}
func (s *HostStore) Add(name, ip, os, provider, hostType string) model.Host {
return s.AddFull(model.Host{
Name: name,
IP: ip,
OS: os,
Provider: provider,
Type: hostType,
})
}
func (s *HostStore) AddFull(h model.Host) model.Host {
mu.Lock()
defer mu.Unlock()
if h.ID == "" {
h.ID = randID()
}
if h.Status == "" {
h.Status = "active"
}
s.hosts = append(s.hosts, h)
writeFile("hosts.json", &s.hosts)
return h
}
func (s *HostStore) Update(h model.Host) bool {
mu.Lock()
defer mu.Unlock()
for i, existing := range s.hosts {
if existing.ID == h.ID {
s.hosts[i] = h
writeFile("hosts.json", &s.hosts)
return true
}
}
return false
}
func (s *HostStore) Delete(id string) {
mu.Lock()
defer mu.Unlock()
for i, h := range s.hosts {
if h.ID == id {
s.hosts = append(s.hosts[:i], s.hosts[i+1:]...)
writeFile("hosts.json", &s.hosts)
return
}
}
}
func contains(s, q string) bool {
if len(s) < len(q) {
return false
}
for i := 0; i <= len(s)-len(q); i++ {
match := true
for j := 0; j < len(q); j++ {
sc, qc := s[i+j], q[j]
if sc >= 'A' && sc <= 'Z' {
sc += 32
}
if qc >= 'A' && qc <= 'Z' {
qc += 32
}
if sc != qc {
match = false
break
}
}
if match {
return true
}
}
return false
}
+112
View File
@@ -0,0 +1,112 @@
package store
import (
"time"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
)
type KeyStore struct {
keys []model.Key
}
func NewKeyStore() *KeyStore {
s := &KeyStore{}
mu.RLock()
readFile("keys.json", &s.keys)
mu.RUnlock()
if s.keys == nil {
s.keys = []model.Key{}
}
return s
}
func (s *KeyStore) All() []model.Key {
mu.RLock()
defer mu.RUnlock()
return s.keys
}
func (s *KeyStore) Search(q string) []model.Key {
mu.RLock()
defer mu.RUnlock()
if q == "" {
return s.keys
}
var res []model.Key
for _, k := range s.keys {
if contains(k.Name, q) || contains(k.Username, q) || contains(k.URL, q) {
res = append(res, k)
}
}
return res
}
func (s *KeyStore) Add(name, username, url, passphrase string) model.Key {
mu.Lock()
defer mu.Unlock()
keyType := guessKeyType(name, passphrase)
k := model.Key{
ID: randID(),
Name: name,
Username: username,
Passphrase: passphrase,
Strength: calcStrength(passphrase),
Type: keyType,
URL: url,
KeyFile: "— " + keyType + " credential —",
CreatedAt: time.Now().Format("Jan 2, 2006"),
}
s.keys = append(s.keys, k)
writeFile("keys.json", &s.keys)
return k
}
func guessKeyType(name, passphrase string) string {
switch {
case len(passphrase) >= 25:
return "ED25519"
case contains(name, "aws") || contains(name, "AWS"):
return "AWS Key"
case contains(name, "token") || contains(name, "bearer") || contains(name, "TOKEN"):
return "Bearer Token"
case len(passphrase) <= 3:
return "PASSWORD"
default:
return "SSH RSA"
}
}
func (s *KeyStore) Delete(id string) {
mu.Lock()
defer mu.Unlock()
for i, k := range s.keys {
if k.ID == id {
s.keys = append(s.keys[:i], s.keys[i+1:]...)
writeFile("keys.json", &s.keys)
return
}
}
}
func calcStrength(p string) string {
l, d, u, s := 0, 0, 0, 0
for _, c := range p {
switch {
case c >= 'a' && c <= 'z':
l++
case c >= 'A' && c <= 'Z':
u++
case c >= '0' && c <= '9':
d++
default:
s++
}
}
if len(p) >= 12 && u >= 1 && d >= 1 && s >= 1 {
return "secure"
}
if len(p) >= 8 && u+d+s >= 2 {
return "moderate"
}
return "weak"
}
+42
View File
@@ -0,0 +1,42 @@
package store
import "git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
type SettingsStore struct {
cfg model.AppConfig
}
func NewSettingsStore() *SettingsStore {
s := &SettingsStore{cfg: defaultConfig()}
mu.RLock()
readFile("settings.json", &s.cfg)
mu.RUnlock()
return s
}
func (s *SettingsStore) Get() model.AppConfig {
mu.RLock()
defer mu.RUnlock()
return s.cfg
}
func (s *SettingsStore) Update(cfg model.AppConfig) {
mu.Lock()
defer mu.Unlock()
s.cfg = cfg
writeFile("settings.json", &s.cfg)
}
func defaultConfig() model.AppConfig {
return model.AppConfig{
Theme: "light",
FontSize: 14,
Scrollback: 5000,
AutoLock: 5,
Keepalive: true,
CopyOnSelect: true,
BellEnabled: false,
AutoReconnect: true,
BlinkCursor: false,
}
}
+86
View File
@@ -0,0 +1,86 @@
package store
import (
"time"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/model"
)
type SnippetStore struct {
snippets []model.Snippet
}
func NewSnippetStore() *SnippetStore {
s := &SnippetStore{}
mu.RLock()
readFile("snippets.json", &s.snippets)
mu.RUnlock()
if s.snippets == nil {
s.snippets = []model.Snippet{}
}
return s
}
func (s *SnippetStore) All() []model.Snippet {
mu.RLock()
defer mu.RUnlock()
return s.snippets
}
func (s *SnippetStore) Search(q, collection, tag string) []model.Snippet {
mu.RLock()
defer mu.RUnlock()
var res []model.Snippet
for _, sn := range s.snippets {
if q != "" && !contains(sn.Name, q) && !contains(sn.Content, q) && !contains(sn.Language, q) {
continue
}
if collection != "" && sn.Collection != collection {
continue
}
if tag != "" {
found := false
for _, t := range sn.Tags {
if t == tag {
found = true
break
}
}
if !found {
continue
}
}
res = append(res, sn)
}
return res
}
func (s *SnippetStore) Add(name, content, language string, tags []string, description, collection string) model.Snippet {
mu.Lock()
defer mu.Unlock()
sn := model.Snippet{
ID: randID(),
Name: name,
Content: content,
Language: language,
Description: description,
Collection: collection,
Icon: "FileText",
Tags: tags,
CreatedAt: time.Now().Format("Jan 2, 2006"),
}
s.snippets = append(s.snippets, sn)
writeFile("snippets.json", &s.snippets)
return sn
}
func (s *SnippetStore) Delete(id string) {
mu.Lock()
defer mu.Unlock()
for i, sn := range s.snippets {
if sn.ID == id {
s.snippets = append(s.snippets[:i], s.snippets[i+1:]...)
writeFile("snippets.json", &s.snippets)
return
}
}
}
+59
View File
@@ -0,0 +1,59 @@
package store
import (
"encoding/json"
"math/rand"
"os"
"path/filepath"
"sync"
"git.tukangketik.id/swanadiva/hostkeeper/pkg/crypto"
)
var dataDir string
var mu sync.RWMutex
func init() {
configDir, err := os.UserConfigDir()
if err != nil {
configDir = os.TempDir()
}
dataDir = filepath.Join(configDir, "hostkeeper", "v2")
os.MkdirAll(dataDir, 0755)
}
func readFile(name string, v any) error {
path := filepath.Join(dataDir, name)
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
if len(data) == 0 {
return nil
}
if crypto.IsEncrypted(string(data)) {
return nil
}
return json.Unmarshal(data, v)
}
func writeFile(name string, v any) error {
path := filepath.Join(dataDir, name)
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0644)
}
func randID() string {
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
b := make([]byte, 8)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
+93
View File
@@ -0,0 +1,93 @@
package main
import (
"html/template"
"log"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/template/html/v2"
"git.tukangketik.id/swanadiva/hostkeeper/v2/internal/handler"
)
func main() {
engine := html.New("./views", ".html")
engine.Reload(true)
engine.AddFunc("svg", func(name string) template.HTML {
switch name {
case "server":
return `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M5 12h14M12 5l7 7-7 7"/></svg>`
case "terminal":
return `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>`
case "folder-sync":
return `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>`
case "code2":
return `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/></svg>`
case "key-round":
return `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z"/></svg>`
case "settings2":
return `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>`
default:
return `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zM3.75 12h.007v.008H3.75V12zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm-.375 5.25h.007v.008H3.75v-.008zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>`
}
})
engine.AddFunc("dict", func(values ...interface{}) map[string]interface{} {
m := make(map[string]interface{})
for i := 0; i < len(values)-1; i += 2 {
if key, ok := values[i].(string); ok {
m[key] = values[i+1]
}
}
return m
})
engine.AddFunc("default", func(def, val interface{}) interface{} {
if val == nil || val == "" {
return def
}
return val
})
app := fiber.New(fiber.Config{
Views: engine,
})
app.Use(logger.New())
app.Use(recover.New())
app.Use(compress.New())
app.Static("/static", "./static")
app.Get("/", handler.Dashboard)
app.Get("/hosts", handler.Dashboard)
app.Get("/hosts/list", handler.DashboardList)
app.Post("/hosts", handler.CreateHost)
app.Put("/hosts/:id", handler.UpdateHost)
app.Delete("/hosts/:id", handler.DeleteHost)
app.Get("/snippets", handler.Snippets)
app.Get("/snippets/grid", handler.SnippetGrid)
app.Post("/snippets", handler.CreateSnippet)
app.Delete("/snippets/:id", handler.DeleteSnippet)
app.Get("/keychain", handler.Keychain)
app.Get("/keys/grid", handler.KeyGrid)
app.Post("/keys", handler.CreateKey)
app.Delete("/keys/:id", handler.DeleteKey)
app.Get("/settings", handler.Settings)
app.Post("/settings", handler.UpdateConfig)
app.Get("/brief", handler.Brief)
app.Get("/terminal", handler.Terminal)
app.Get("/terminal/ws/:host", websocket.New(func(c *websocket.Conn) {
handler.TerminalWS(c)
}, websocket.Config{
Origins: []string{"*"},
}))
app.Get("/sftp", handler.SFTP)
app.Get("/sftp/pane", handler.SFTPPane)
app.Post("/sftp/mkdir", handler.CreateFolder)
app.Delete("/sftp/rm", handler.DeleteFile)
app.Get("/api/health", handler.Health)
log.Fatal(app.Listen(":1947"))
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"devDependencies": {
"@tailwindcss/cli": "^4.3.2"
}
}
+206
View File
@@ -0,0 +1,206 @@
/* Lumina System — Custom CSS */
/* Alpine cloak — hide until initialized */
[x-cloak] { display: none !important; }
/* Dot grid background */
.dot-grid {
background-image: radial-gradient(#e2e8f0 1.5px, transparent 1.5px);
background-size: 16px 16px;
}
/* Glass panels */
.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);
}
/* Animations */
@keyframes fade-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes scale-up {
from { opacity: 0; transform: scale(0.95); }
to { opacity: 1; transform: scale(1); }
}
@keyframes slide-in {
from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes cursor-blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
.animate-fade-in {
animation: fade-in 0.3s ease-out;
}
.animate-scale-up {
animation: scale-up 0.2s ease-out;
}
.animate-slide-in {
animation: slide-in 0.3s ease-out;
}
.terminal-cursor {
display: inline-block;
width: 8px;
height: 18px;
background: currentColor;
animation: cursor-blink 1s infinite;
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: #c2c6d8;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #a0a4b8;
}
.no-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
.no-scrollbar::-webkit-scrollbar {
display: none;
}
/* Modal backdrop */
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.3);
backdrop-filter: blur(4px);
display: flex;
align-items: center;
justify-content: center;
z-index: 50;
}
.modal-content {
background: white;
border-radius: 16px;
padding: 24px;
width: 100%;
max-width: 480px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
animation: scale-up 0.2s ease-out;
}
/* Toast */
.toast {
position: fixed;
bottom: 24px;
right: 24px;
background: #191c1e;
color: white;
padding: 12px 20px;
border-radius: 10px;
font-size: 14px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
z-index: 100;
animation: slide-in 0.3s ease-out;
}
/* Toggle switch */
.toggle-switch {
position: relative;
width: 44px;
height: 24px;
border-radius: 12px;
background: #c2c6d8;
transition: background 0.2s;
cursor: pointer;
border: none;
padding: 0;
}
.toggle-switch.active {
background: #0050cb;
}
.toggle-knob {
position: absolute;
top: 2px;
left: 2px;
width: 20px;
height: 20px;
border-radius: 50%;
background: white;
transition: transform 0.2s;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
.toggle-switch.active .toggle-knob {
transform: translateX(20px);
}
/* File table */
.file-table-row {
display: grid;
grid-template-columns: 1fr 80px 120px;
gap: 8px;
padding: 8px 12px;
border-radius: 8px;
cursor: pointer;
transition: background 0.15s;
}
.file-table-row:hover {
background: #f1f4f9;
}
/* xterm.js container */
.xterm { padding: 8px 0; }
.xterm-viewport::-webkit-scrollbar { width: 6px; }
.xterm-viewport::-webkit-scrollbar-thumb { background: #c2c6d8; border-radius: 3px; }
/* Strength badges */
.strength-badge-secure {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 6px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
background: #006e2f/15;
color: #006e2f;
}
.strength-badge-moderate {
background: #7e23cc/15;
color: #7e23cc;
}
.strength-badge-weak {
background: #b3261e/15;
color: #b3261e;
}
+33
View File
@@ -0,0 +1,33 @@
@import "tailwindcss";
@theme {
--color-primary: #0050cb;
--color-on-primary: #ffffff;
--color-primary-container: #d6e3ff;
--color-on-primary-container: #001638;
--color-secondary: #006e2f;
--color-on-secondary: #ffffff;
--color-secondary-container: #6bff8f;
--color-on-secondary-container: #00210b;
--color-tertiary: #7e23cc;
--color-on-tertiary: #ffffff;
--color-tertiary-container: #f0daff;
--color-on-tertiary-container: #290055;
--color-error: #b3261e;
--color-on-error: #ffffff;
--color-error-container: #f9dedc;
--color-on-error-container: #410e0b;
--color-surface: #f7f9fb;
--color-on-surface: #191c1e;
--color-surface-container-low: #f0f2f5;
--color-surface-container: #eaecf0;
--color-surface-container-high: #e2e5e9;
--color-on-surface-variant: #424656;
--color-outline: #727686;
--color-outline-variant: #c2c6d8;
--color-inverse-surface: #2d3133;
--color-inverse-on-surface: #f0f1f3;
--font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, monospace;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+22
View File
@@ -0,0 +1,22 @@
document.addEventListener('click', function(e) {
const btn = e.target.closest('[data-copy]');
if (!btn) return;
const text = btn.getAttribute('data-copy');
if (!text) return;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).catch(() => fallbackCopy(text));
} else {
fallbackCopy(text);
}
});
function fallbackCopy(text) {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); } catch (e) {}
document.body.removeChild(ta);
}
File diff suppressed because one or more lines are too long
+192
View File
@@ -0,0 +1,192 @@
document.addEventListener('alpine:init', () => {
const el = document.getElementById('hosts-data');
const hostOptions = el ? (JSON.parse(el.textContent) || []) : [];
const selEl = document.getElementById('selected-host');
const selectedHostId = selEl ? JSON.parse(selEl.textContent) : '';
const termTheme = {
background: '#ffffff',
foreground: '#191c1e',
cursor: '#0050cb',
cursorAccent: '#ffffff',
selectionBackground: '#0050cb33',
black: '#191c1e',
red: '#b3261e',
green: '#006e2f',
yellow: '#a86e0a',
blue: '#0050cb',
magenta: '#7e23cc',
cyan: '#006493',
white: '#191c1e',
brightBlack: '#727686',
brightRed: '#dc362e',
brightGreen: '#008a42',
brightYellow: '#c58800',
brightBlue: '#2962d5',
brightMagenta: '#9a40e8',
brightCyan: '#007ab5',
brightWhite: '#424656',
};
Alpine.data('terminalManager', () => ({
tabs: [],
activeTab: 0,
command: '',
_terminals: {},
_sockets: {},
_containers: {},
init() {
this._wrapper = document.getElementById('xterm-wrapper');
this.addTab();
},
_getHostForTab() {
let host;
if (selectedHostId) {
host = hostOptions.find((h) => h.id === selectedHostId) || hostOptions[0];
}
if (!host) {
host = hostOptions.length > 0
? hostOptions[Math.floor(Math.random() * hostOptions.length)]
: { id: 'h1', name: 'localhost', ip: '127.0.0.1' };
}
return host;
},
addTab() {
const host = this._getHostForTab();
const id = 'tab-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6);
this.tabs.push({ id, name: host.name, host: host.ip, hostID: host.id });
// Create xterm container DOM element directly
const container = document.createElement('div');
container.id = 'xterm-' + id;
container.className = 'absolute inset-0';
container.style.display = 'none';
this._wrapper.appendChild(container);
this._containers[id] = container;
// Create xterm.js terminal
const term = new Terminal({
theme: termTheme,
fontFamily: "'JetBrains Mono', monospace",
fontSize: 13,
lineHeight: 1.5,
cursorBlink: true,
cursorStyle: 'bar',
allowProposedApi: true,
scrollback: 5000,
});
this._terminals[id] = term;
term.open(container);
// Connect WebSocket
const wsUrl =
(location.protocol === 'https:' ? 'wss:' : 'ws:') +
'//' + location.host + '/terminal/ws/' + host.id;
console.log('[terminal] connecting to', wsUrl);
const ws = new WebSocket(wsUrl);
this._sockets[id] = ws;
ws.onopen = () => {
console.log('[terminal] ws open for', host.id);
term.focus();
};
ws.onmessage = (ev) => {
term.write(ev.data);
};
ws.onclose = () => {
console.log('[terminal] ws closed for', host.id);
term.write('\r\n\x1b[33m[Connection closed]\x1b[0m\r\n');
};
ws.onerror = (err) => {
console.error('[terminal] ws error for', host.id, err);
term.write('\r\n\x1b[31m[Connection error]\x1b[0m\r\n');
};
term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(data);
}
});
// Switch to new tab
this.activeTab = this.tabs.length - 1;
this._showActiveTerminal();
},
switchTab(i) {
this.activeTab = i;
this._showActiveTerminal();
},
_showActiveTerminal() {
const cur = this.tabs[this.activeTab];
if (!cur) return;
Object.keys(this._containers).forEach((key) => {
this._containers[key].style.display = key === cur.id ? 'block' : 'none';
});
if (this._terminals[cur.id]) {
this._terminals[cur.id].focus();
this._terminals[cur.id].refresh(0, this._terminals[cur.id].rows);
}
},
closeTab(i) {
if (this.tabs.length <= 1) return;
const tab = this.tabs[i];
const id = tab.id;
if (this._sockets[id]) {
this._sockets[id].close();
delete this._sockets[id];
}
if (this._terminals[id]) {
this._terminals[id].dispose();
delete this._terminals[id];
}
if (this._containers[id]) {
this._containers[id].remove();
delete this._containers[id];
}
this.tabs.splice(i, 1);
if (this.activeTab >= this.tabs.length) {
this.activeTab = this.tabs.length - 1;
}
this._showActiveTerminal();
},
submitCommand() {
const cmd = this.command.trim();
if (!cmd) return;
const cur = this.tabs[this.activeTab];
if (!cur) return;
const ws = this._sockets[cur.id];
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(cmd + '\r');
}
this.command = '';
},
insertCommand(cmd) {
this.command = cmd;
this.$nextTick(() => this.submitCommand());
},
clearBuffer() {
const cur = this.tabs[this.activeTab];
if (!cur) return;
const term = this._terminals[cur.id];
if (term) {
term.clear();
term.write('\x1b[2J\x1b[H');
}
},
}));
});
+13
View File
@@ -0,0 +1,13 @@
document.addEventListener('alpine:init', () => {
Alpine.data('switchToggle', (initial) => ({
on: initial,
toggle() {
this.on = !this.on;
this.$el.classList.toggle('active', this.on);
this.$nextTick(() => {
const hidden = this.$el.nextElementSibling;
if (hidden) hidden.value = this.on ? 'on' : '';
});
}
}));
});
+6
View File
@@ -0,0 +1,6 @@
document.addEventListener('alpine:init', () => {
Alpine.data('passphraseToggle', () => ({
show: false,
toggle() { this.show = !this.show; }
}));
});
+209
View File
@@ -0,0 +1,209 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility,
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}
File diff suppressed because one or more lines are too long
+27
View File
@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quick Brief · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 flex items-center px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-lg font-semibold text-on-surface">{{.Title}}</h1>
</header>
<main id="main-content" class="flex-1 overflow-auto p-6">
{{template "brief_content" .}}
</main>
</div>
</div>
</body>
</html>
+78
View File
@@ -0,0 +1,78 @@
{{define "brief_content"}}
<div class="max-w-3xl mx-auto space-y-6">
<!-- Color Palette -->
<div class="bg-white rounded-2xl border border-outline-variant/30 p-6 space-y-4">
<h3 class="font-bold text-on-surface flex items-center gap-2">
<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01"/></svg>
Color Palette — Lumina System
</h3>
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
<div class="rounded-xl p-3" style="background:#0050cb"><span class="text-white text-xs font-mono font-bold">Primary #0050cb</span></div>
<div class="rounded-xl p-3" style="background:#006e2f"><span class="text-white text-xs font-mono font-bold">Secondary #006e2f</span></div>
<div class="rounded-xl p-3" style="background:#7e23cc"><span class="text-white text-xs font-mono font-bold">Tertiary #7e23cc</span></div>
<div class="rounded-xl p-3" style="background:#b3261e"><span class="text-white text-xs font-mono font-bold">Error #b3261e</span></div>
<div class="rounded-xl p-3 border border-outline-variant/30" style="background:#f7f9fb"><span class="text-[#191c1e] text-xs font-mono font-bold">Surface #f7f9fb</span></div>
<div class="rounded-xl p-3" style="background:#191c1e"><span class="text-white text-xs font-mono font-bold">On-Surface #191c1e</span></div>
<div class="rounded-xl p-3" style="background:#424656"><span class="text-white text-xs font-mono font-bold">On-Surface-Var #424656</span></div>
<div class="rounded-xl p-3" style="background:#c2c6d8"><span class="text-[#191c1e] text-xs font-mono font-bold">Outline-Var #c2c6d8</span></div>
</div>
</div>
<!-- Typography -->
<div class="bg-white rounded-2xl border border-outline-variant/30 p-6 space-y-4">
<h3 class="font-bold text-on-surface flex items-center gap-2">
<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"/></svg>
Typography
</h3>
<div class="space-y-3">
<div><p class="text-xl font-bold tracking-tight">Heading XL — Inter 800</p><p class="text-xs text-on-surface-variant font-mono">text-xl font-bold tracking-tight</p></div>
<div><p class="text-base font-bold">Heading Base — Inter 700</p><p class="text-xs text-on-surface-variant font-mono">text-base font-bold</p></div>
<div><p class="text-sm font-medium">Body — Inter 500</p><p class="text-xs text-on-surface-variant font-mono">text-sm font-medium</p></div>
<div><p class="text-xs text-on-surface-variant">Caption — Inter 400/500</p><p class="text-xs text-on-surface-variant font-mono">text-xs text-on-surface-variant</p></div>
<div><p class="text-xs font-mono">Monospace — JetBrains Mono 400/600</p><p class="text-xs text-on-surface-variant font-mono">text-xs font-mono</p></div>
</div>
</div>
<!-- Elevation -->
<div class="bg-white rounded-2xl border border-outline-variant/30 p-6 space-y-4">
<h3 class="font-bold text-on-surface flex items-center gap-2">
<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"/></svg>
Elevation & Layout
</h3>
<div class="space-y-3 text-sm">
<div class="flex items-center gap-4 p-3 rounded-lg bg-surface-container-low">
<span class="w-16 text-xs font-mono text-on-surface-variant">shadow-sm</span>
<div class="flex-1 h-8 rounded-lg bg-white shadow-sm border border-outline-variant/20"></div>
</div>
<div class="flex items-center gap-4 p-3 rounded-lg bg-surface-container-low">
<span class="w-16 text-xs font-mono text-on-surface-variant">shadow-md</span>
<div class="flex-1 h-8 rounded-lg bg-white shadow-md border border-outline-variant/20"></div>
</div>
<div class="flex items-center gap-4 p-3 rounded-lg bg-surface-container-low">
<span class="w-16 text-xs font-mono text-on-surface-variant">shadow-lg</span>
<div class="flex-1 h-8 rounded-lg bg-white shadow-lg border border-outline-variant/20"></div>
</div>
<div class="flex items-center gap-4 p-3 rounded-lg bg-surface-container-low">
<span class="w-16 text-xs font-mono text-on-surface-variant">shadow-2xl</span>
<div class="flex-1 h-8 rounded-lg bg-white shadow-2xl border border-outline-variant/20"></div>
</div>
</div>
</div>
<!-- Keyboard Shortcuts -->
<div class="bg-white rounded-2xl border border-outline-variant/30 p-6 space-y-4">
<h3 class="font-bold text-on-surface flex items-center gap-2">
<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
Keyboard Shortcuts
</h3>
<div class="space-y-2 text-sm">
<div class="flex items-center justify-between py-1.5 border-b border-outline-variant/10"><span class="text-on-surface-variant">New Host</span><kbd class="px-2 py-0.5 rounded bg-surface-container-low text-xs font-mono text-on-surface">Cmd + N</kbd></div>
<div class="flex items-center justify-between py-1.5 border-b border-outline-variant/10"><span class="text-on-surface-variant">New Snippet</span><kbd class="px-2 py-0.5 rounded bg-surface-container-low text-xs font-mono text-on-surface">Cmd + I</kbd></div>
<div class="flex items-center justify-between py-1.5 border-b border-outline-variant/10"><span class="text-on-surface-variant">Toggle View</span><kbd class="px-2 py-0.5 rounded bg-surface-container-low text-xs font-mono text-on-surface">Cmd + T</kbd></div>
<div class="flex items-center justify-between py-1.5 border-b border-outline-variant/10"><span class="text-on-surface-variant">Search</span><kbd class="px-2 py-0.5 rounded bg-surface-container-low text-xs font-mono text-on-surface">Cmd + P</kbd></div>
<div class="flex items-center justify-between py-1.5 border-b border-outline-variant/10"><span class="text-on-surface-variant">Quick Terminal</span><kbd class="px-2 py-0.5 rounded bg-surface-container-low text-xs font-mono text-on-surface">Cmd + K</kbd></div>
<div class="flex items-center justify-between py-1.5 border-b border-outline-variant/10"><span class="text-on-surface-variant">Close Panel</span><kbd class="px-2 py-0.5 rounded bg-surface-container-low text-xs font-mono text-on-surface">Esc</kbd></div>
</div>
</div>
</div>
{{end}}
+107
View File
@@ -0,0 +1,107 @@
{{define "host_list"}}
<div id="host-list" class="flex flex-col gap-4">
<div x-show="view === 'grid'" x-cloak
class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
{{range .Hosts}}
<div class="group bg-white p-5 rounded-2xl border border-outline-variant hover:border-primary hover:shadow-lg transition-all relative overflow-hidden">
<div class="flex justify-between items-start mb-4">
<div class="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">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M5 12h14M12 5l7 7-7 7"/></svg>
</div>
<div class="flex items-center gap-1.5">
<span class="w-2 h-2 rounded-full {{if eq .Status "active"}}bg-secondary animate-pulse{{else}}bg-outline{{end}}"></span>
<span class="text-[10px] font-bold uppercase tracking-wider {{if eq .Status "active"}}text-secondary{{else}}text-outline{{end}}">{{.Status}}</span>
</div>
</div>
<h4 class="font-bold text-on-surface group-hover:text-primary transition-colors text-base truncate">{{.Name}}</h4>
<p class="font-mono text-xs text-outline mb-1">{{.IP}}</p>
<p class="text-[10px] text-on-surface-variant mb-3" x-data="{ show: false }">
<span class="font-medium">{{.Username | default "root"}}@{{if .Hostname}}{{.Hostname}}{{else}}{{.IP}}{{end}}{{if ne .Port 22}}:{{.Port}}{{end}}</span>
</p>
{{if .Type}}<div class="flex flex-wrap gap-1.5 mb-4">
<span class="px-2 py-0.5 bg-primary-container/10 text-primary rounded text-[10px] font-bold uppercase">{{.Type}}</span>
</div>{{end}}
<div class="pt-3 border-t border-outline-variant/30 flex justify-between items-center text-xs">
<span class="text-outline italic">Last seen {{.LastSeen}}</span>
<div class="flex gap-1">
<a href="/terminal?host={{.ID}}" class="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</a>
<button type="button"
@click="$dispatch('edit-host', { ID: '{{.ID}}', Name: '{{.Name}}', IP: '{{.IP}}', Hostname: '{{.Hostname}}', Port: {{.Port}}, Username: '{{.Username}}', Type: '{{.Type}}', AuthType: '{{.AuthType}}', Password: '{{.Password}}', Notes: '{{.Notes}}' })"
class="p-1.5 rounded-lg hover:bg-surface-container text-on-surface-variant hover:text-primary transition-colors" title="Edit">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"/></svg>
</button>
<button class="p-1.5 rounded-lg hover:bg-red-50 text-on-surface-variant hover:text-red-500 transition-colors"
hx-delete="/hosts/{{.ID}}" hx-target="#host-list" hx-confirm="Delete {{.Name}}?" title="Delete"
@click="$dispatch('toast-message', { message: 'Host deleted' })">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
</button>
</div>
</div>
</div>
{{end}}
<div @click="$dispatch('open-modal')"
class="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 min-h-[200px]">
<svg class="w-8 h-8 mb-2 group-active:scale-90 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 4v16m8-8H4"/></svg>
<span class="font-bold text-sm text-on-surface-variant group-hover:text-primary">Add New Host</span>
<p class="text-[10px] uppercase tracking-widest mt-1 opacity-70">Manual Config or Discovery</p>
</div>
</div>
<div x-show="view === 'list'" x-cloak
class="bg-white border border-outline-variant rounded-2xl overflow-hidden shadow-sm divide-y divide-outline-variant/30">
{{range .Hosts}}
<div class="flex items-center justify-between p-4 hover:bg-primary/5 transition-colors group">
<div class="flex items-center gap-4 min-w-0 flex-1">
<div class="w-10 h-10 rounded-lg bg-surface-container-low flex items-center justify-center text-primary shrink-0 border border-outline-variant/20">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M5 12h14M12 5l7 7-7 7"/></svg>
</div>
<div class="min-w-0 flex-1 sm:grid sm:grid-cols-2 sm:gap-4 items-center">
<div>
<h4 class="font-bold text-on-surface group-hover:text-primary transition-colors text-sm truncate">{{.Name}}</h4>
<span class="font-mono text-xs text-outline">{{.IP}}</span>
</div>
<div class="hidden md:block">
<span class="text-xs text-outline italic">Seen {{.LastSeen}}</span>
</div>
</div>
</div>
<div class="flex items-center gap-2 ml-4 shrink-0">
<span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1 {{if eq .Status "active"}}bg-secondary-container/20 text-secondary{{else}}bg-surface-container text-outline{{end}}">
<span class="w-1.5 h-1.5 rounded-full {{if eq .Status "active"}}bg-secondary animate-pulse{{else}}bg-outline{{end}}"></span>
{{.Status}}
</span>
<a href="/terminal?host={{.ID}}" class="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</a>
<button type="button"
@click="$dispatch('edit-host', { ID: '{{.ID}}', Name: '{{.Name}}', IP: '{{.IP}}', Hostname: '{{.Hostname}}', Port: {{.Port}}, Username: '{{.Username}}', Type: '{{.Type}}', AuthType: '{{.AuthType}}', Password: '{{.Password}}', Notes: '{{.Notes}}' })"
class="p-1.5 rounded-lg hover:bg-surface-container text-on-surface-variant hover:text-primary transition-colors" title="Edit">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"/></svg>
</button>
<button class="p-1.5 rounded-lg hover:bg-red-50 text-on-surface-variant hover:text-red-500 transition-colors"
hx-delete="/hosts/{{.ID}}" hx-target="#host-list" hx-confirm="Delete {{.Name}}?" title="Delete"
@click="$dispatch('toast-message', { message: 'Host deleted' })">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
</button>
</div>
</div>
{{end}}
<div @click="$dispatch('open-modal')"
class="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">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 4v16m8-8H4"/></svg>
Add New Host
</div>
</div>
{{if eq (len .Hosts) 0}}
<div class="text-center py-12 text-on-surface-variant">
<svg class="w-12 h-12 mx-auto mb-3 text-outline/40" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M5 12h14M12 5l7 7-7 7"/></svg>
<p class="text-lg font-medium">No hosts found</p>
<p class="text-sm mt-1">Add your first server to get started</p>
</div>
{{end}}
</div>
{{end}}
+181
View File
@@ -0,0 +1,181 @@
{{define "host_modal"}}
<div id="host-modal" class="fixed inset-0 z-50" x-data="hostForm()" x-show="open" x-cloak
@open-modal.window="reset(); open = true"
@edit-host.window="populate($event.detail); open = true"
@keydown.escape.window="open = false">
<div class="absolute inset-0 bg-black/40 backdrop-blur-sm" @click="open = false"></div>
<div class="absolute inset-0 overflow-y-auto p-4" x-show="open" x-transition>
<div class="flex min-h-full items-center justify-center">
<div class="bg-white rounded-2xl max-w-lg w-full border border-outline-variant/30 shadow-2xl max-h-[90vh] overflow-y-auto">
<div class="flex justify-between items-center border-b border-outline-variant/30 p-6 pb-4">
<h3 class="font-bold text-lg text-on-surface" x-text="editing ? 'Edit Host' : 'Add Host'"></h3>
<button @click="open = false"
class="text-outline hover:text-primary cursor-pointer p-1 rounded-lg">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>
<form hx-post="/hosts"
hx-target="#host-list" hx-swap="innerHTML"
@submit="open = false; $dispatch('toast-message', { message: editing ? 'Host updated' : 'Host added' })"
class="p-6 space-y-4 text-sm">
<input type="hidden" name="hostId" :value="editing ? hostId : ''">
<div class="grid grid-cols-2 gap-4">
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Host Identifier</label>
<input type="text" name="name" x-model="form.name" required placeholder="e.g. prod-db-replica"
class="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 class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">IP Address / Domain</label>
<input type="text" name="ip" x-model="form.ip" required placeholder="e.g. 10.0.12.19"
class="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-on-surface">
</div>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Hostname (SSH)</label>
<input type="text" name="hostname" x-model="form.hostname" placeholder="e.g. prod.example.com"
class="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-on-surface text-xs">
</div>
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">SSH Port</label>
<input type="number" name="port" x-model="form.port" min="1" max="65535" placeholder="22"
class="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-on-surface text-xs">
</div>
</div>
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">SSH Username</label>
<input type="text" name="username" x-model="form.username" placeholder="root"
class="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 class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Host Purpose / Type</label>
<div class="grid grid-cols-3 gap-2">
<button type="button" @click="form.type = 'api'"
:class="form.type === 'api' ? 'bg-primary text-white border-primary' : 'bg-surface-container-low border-outline-variant/40 text-on-surface-variant hover:bg-surface-container'"
class="py-2.5 px-3 border rounded-lg font-bold text-xs uppercase tracking-wider transition-all">API Node</button>
<button type="button" @click="form.type = 'db'"
:class="form.type === 'db' ? 'bg-primary text-white border-primary' : 'bg-surface-container-low border-outline-variant/40 text-on-surface-variant hover:bg-surface-container'"
class="py-2.5 px-3 border rounded-lg font-bold text-xs uppercase tracking-wider transition-all">DB Node</button>
<button type="button" @click="form.type = 'web'"
:class="form.type === 'web' ? 'bg-primary text-white border-primary' : 'bg-surface-container-low border-outline-variant/40 text-on-surface-variant hover:bg-surface-container'"
class="py-2.5 px-3 border rounded-lg font-bold text-xs uppercase tracking-wider transition-all">Web Node</button>
</div>
<input type="hidden" name="type" :value="form.type">
</div>
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Authentication</label>
<div class="grid grid-cols-2 gap-2">
<button type="button" @click="form.authType = 'key'"
:class="form.authType === 'key' ? 'bg-primary text-white border-primary' : 'bg-surface-container-low border-outline-variant/40 text-on-surface-variant hover:bg-surface-container'"
class="py-2 px-3 border rounded-lg font-bold text-xs uppercase tracking-wider transition-all flex items-center justify-center gap-1.5">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z"/></svg>
SSH Key
</button>
<button type="button" @click="form.authType = 'password'"
:class="form.authType === 'password' ? 'bg-primary text-white border-primary' : 'bg-surface-container-low border-outline-variant/40 text-on-surface-variant hover:bg-surface-container'"
class="py-2 px-3 border rounded-lg font-bold text-xs uppercase tracking-wider transition-all flex items-center justify-center gap-1.5">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"/></svg>
Password
</button>
</div>
<input type="hidden" name="authType" :value="form.authType">
</div>
<div x-show="form.authType === 'key'" x-cloak class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">SSH Private Key</label>
<textarea name="password" rows="5" placeholder="Paste your SSH private key here...&#10;&#10;-----BEGIN OPENSSH PRIVATE KEY-----&#10;...&#10;-----END OPENSSH PRIVATE KEY-----"
class="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-on-surface text-xs resize-none leading-relaxed"></textarea>
<div class="flex items-center gap-3 mt-1">
<label class="flex items-center gap-1.5 text-xs text-on-surface-variant cursor-pointer hover:text-primary transition-colors">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/></svg>
Or upload a key file
</label>
<input type="file" class="hidden" accept=".pem,.key,.pub,.txt,.ppk" @change="readKeyFile($event)">
<span class="text-[10px] text-outline">.pem .key .ppk</span>
</div>
</div>
<div x-show="form.authType === 'password'" x-cloak class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Password</label>
<input type="password" name="password" x-model="form.password" placeholder="SSH password"
class="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-on-surface text-xs">
</div>
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Notes</label>
<textarea name="notes" x-model="form.notes" rows="2" placeholder="Optional notes about this host"
class="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 text-xs resize-none"></textarea>
</div>
<div class="pt-4 flex justify-end gap-3 border-t border-outline-variant/20">
<button type="button" @click="open = false"
class="px-4 py-2 text-xs font-bold text-outline hover:text-on-surface transition-colors">Cancel</button>
<button type="submit"
class="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"
x-text="editing ? 'Save Changes' : 'Add Host'"></button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function hostForm() {
return {
open: false,
editing: false,
hostId: '',
form: {
name: '', ip: '', hostname: '', port: '22', username: '',
type: 'api', authType: 'key', password: '', notes: ''
},
reset() {
this.editing = false;
this.hostId = '';
this.form = {
name: '', ip: '', hostname: '', port: '22', username: '',
type: 'api', authType: 'key', password: '', notes: ''
};
var ta = document.querySelector('#host-modal textarea[name=password]');
if (ta) ta.value = '';
},
populate(host) {
this.editing = true;
this.hostId = host.ID;
this.form = {
name: host.Name || '',
ip: host.IP || '',
hostname: host.Hostname || '',
port: String(host.Port || 22),
username: host.Username || 'root',
type: host.Type || 'api',
authType: host.AuthType || 'key',
password: host.Password || '',
notes: host.Notes || ''
};
var ta = document.querySelector('#host-modal textarea[name=password]');
if (ta) ta.value = host.Password || '';
},
readKeyFile($event) {
var file = $event.target.files[0];
if (!file) return;
var reader = new FileReader();
var ta = document.querySelector('#host-modal textarea[name=password]');
reader.onload = function(e) {
if (ta) ta.value = e.target.result;
};
reader.readAsText(file);
}
};
}
</script>
{{end}}
+182
View File
@@ -0,0 +1,182 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hosts · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
<script src="/static/js/clipboard.js"></script>
<script src="/static/js/utils.js"></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 flex items-center px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-lg font-semibold text-on-surface">Hosts</h1>
</header>
<main id="main-content" class="flex-1 overflow-auto p-6">
<div id="dashboard-page" class="max-w-7xl mx-auto space-y-8">
<div class="border-b border-outline-variant/30 pb-4">
<h2 class="text-xl font-bold text-on-surface tracking-tight">Hosts</h2>
<p class="text-xs text-on-surface-variant mt-0.5">Manage connections, monitor uptime, and deploy</p>
</div>
<div class="grid grid-cols-1 md:grid-cols-12 gap-6">
<div class="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 class="relative z-10 space-y-2">
<h3 class="text-on-surface-variant font-bold text-xs uppercase tracking-wider">Active Connections</h3>
<div class="flex items-end gap-3">
<span class="text-4xl font-black text-primary">{{.Active}}</span>
<span class="text-secondary font-bold text-sm mb-1 flex items-center bg-secondary-container/20 px-2 py-0.5 rounded-full">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.25 18L9 11.25l4.306 4.307a11.95 11.95 0 015.814-5.519l2.74-1.22m0 0l-5.94-2.28m5.94 2.28l-2.28 5.941"/></svg>
+2 today
</span>
</div>
<p class="text-xs text-on-surface-variant">Global performance metrics sync integrity active.</p>
</div>
<div class="absolute right-0 top-0 w-1/3 h-full bg-gradient-to-l from-primary/5 to-transparent pointer-events-none"></div>
<div class="flex gap-2 items-end h-16 shrink-0">
<div class="w-2.5 h-10 bg-primary/20 rounded-full animate-pulse"></div>
<div class="w-2.5 h-14 bg-primary/40 rounded-full animate-pulse delay-75"></div>
<div class="w-2.5 h-8 bg-primary/10 rounded-full animate-pulse delay-150"></div>
<div class="w-2.5 h-16 bg-primary/60 rounded-full animate-pulse delay-200"></div>
</div>
</div>
<div class="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 class="relative z-10">
<svg class="w-8 h-8 opacity-90 text-white mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"/></svg>
<p class="font-bold text-lg leading-tight">Fastest Access Enabled</p>
</div>
<p class="text-xs opacity-85 mt-2 relative z-10">Smart routing engine successfully reduces terminal latency by <span class="font-bold">24ms</span> across European and Asian clusters.</p>
<div class="absolute -right-6 -bottom-6 opacity-10">
<svg class="w-32 h-32 rotate-12" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"/></svg>
</div>
</div>
</div>
<div x-data="{ view: 'grid' }">
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4 mb-6">
<div class="flex items-center gap-3">
<h3 class="text-lg font-bold text-on-surface">Recent Hosts</h3>
<div class="flex bg-surface-container rounded-lg p-0.5 text-xs font-semibold border border-outline-variant/20"
x-data="{ filter: 'all' }">
<button @click="filter = 'all'"
:class="filter === 'all' ? 'bg-white text-primary shadow-sm' : 'text-on-surface-variant hover:text-on-surface'"
class="px-2.5 py-1 rounded-md transition-all"
hx-get="/hosts/list?filter=all" hx-target="#host-list">All</button>
<button @click="filter = 'active'"
:class="filter === 'active' ? 'bg-white text-primary shadow-sm' : 'text-on-surface-variant hover:text-on-surface'"
class="px-2.5 py-1 rounded-md transition-all"
hx-get="/hosts/list?filter=active" hx-target="#host-list">Active</button>
<button @click="filter = 'offline'"
:class="filter === 'offline' ? 'bg-white text-primary shadow-sm' : 'text-on-surface-variant hover:text-on-surface'"
class="px-2.5 py-1 rounded-md transition-all"
hx-get="/hosts/list?filter=offline" hx-target="#host-list">Offline</button>
</div>
</div>
<div class="flex items-center gap-3">
<div class="relative">
<svg class="absolute left-3 top-1/2 -translate-y-1/2 text-outline w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
<input type="search" name="q" placeholder="Search hosts..."
hx-get="/hosts/list" hx-trigger="keyup delay:200ms"
hx-target="#host-list"
class="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 text-on-surface placeholder-on-surface-variant">
</div>
<div class="flex border border-outline-variant/50 rounded-lg p-0.5 bg-white">
<button @click="view = 'grid'"
:class="view === 'grid' ? 'bg-surface-container text-primary' : 'text-on-surface-variant'"
class="p-1.5 rounded transition-colors" title="Grid View">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 5a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1H5a1 1 0 01-1-1V5zm10 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1V5zM4 15a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1H5a1 1 0 01-1-1v-4zm10 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"/></svg>
</button>
<button @click="view = 'list'"
:class="view === 'list' ? 'bg-surface-container text-primary' : 'text-on-surface-variant'"
class="p-1.5 rounded transition-colors" title="List View">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
</button>
</div>
</div>
</div>
{{template "host_list" .}}
</div>
</div>
<!-- Transfer Activity Panel -->
<div class="space-y-4 mt-8">
<div class="flex items-center gap-4">
<h3 class="text-base font-bold text-on-surface tracking-tight shrink-0">Background Transfers</h3>
<div class="flex-1 h-px bg-outline-variant/30"></div>
</div>
<div class="bg-white/50 backdrop-blur-sm border border-outline-variant rounded-2xl overflow-hidden shadow-sm">
<div class="p-4 border-b border-outline-variant flex items-center justify-between bg-surface-container-low">
<div class="flex gap-12 text-xs font-bold text-on-surface-variant uppercase tracking-tight">
<span>Source &amp; File</span>
<span>Destination</span>
</div>
<span class="text-xs font-bold text-on-surface-variant uppercase tracking-tight">Progress</span>
</div>
<div class="divide-y divide-outline-variant/30 bg-white">
{{range .Transfers}}
<div class="p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4 hover:bg-primary/5 transition-colors">
<div class="flex items-center gap-4 min-w-0 flex-1">
<div class="p-2 rounded-lg {{if eq .Type "download"}}bg-tertiary/10 text-tertiary{{else}}bg-primary/10 text-primary{{end}}">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
</div>
<div class="min-w-0 flex-1 grid grid-cols-1 sm:grid-cols-2 gap-2">
<div>
<p class="text-sm font-bold truncate text-on-surface">{{.FileName}}</p>
<span class="text-[10px] font-mono text-outline block">{{.Source}}</span>
</div>
<div class="flex items-center gap-1 text-on-surface-variant text-xs">
<svg class="w-4 h-4 text-outline shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
<span class="truncate">{{.Destination}}</span>
</div>
</div>
</div>
<div class="w-full sm:w-48 shrink-0">
<div class="flex justify-between items-center mb-1">
<span class="text-[10px] font-bold text-secondary">{{.Progress}}%</span>
<span class="text-[10px] text-outline font-mono">{{.Speed}}</span>
</div>
<div class="h-1.5 w-full bg-surface-container-high rounded-full overflow-hidden">
<div class="h-full bg-secondary rounded-full transition-all duration-500 shadow-[0_0_8px_rgba(0,110,47,0.3)]"
style="width: {{.Progress}}%"></div>
</div>
</div>
</div>
{{end}}
{{if not .Transfers}}
<div class="p-8 text-center text-on-surface-variant">
<svg class="w-10 h-10 mx-auto mb-2 text-outline/30" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"/></svg>
<p class="text-sm font-medium">No active transfers</p>
</div>
{{end}}
</div>
</div>
</div>
{{template "host_modal" .}}
</main>
</div>
</div>
<!-- Toast -->
<div x-data="{ show: false, msg: '' }" x-cloak
@toast-message.window="msg = $event.detail.message; show = true; setTimeout(() => show = false, 3000)"
x-show="show" x-transition
class="fixed bottom-6 right-6 z-[200] bg-inverse-surface text-inverse-on-surface px-5 py-3 rounded-xl shadow-xl flex items-center gap-3 text-sm font-medium">
<svg class="w-4 h-4 text-secondary shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
<span x-text="msg"></span>
</div>
</body>
</html>
+88
View File
@@ -0,0 +1,88 @@
{{define "credential_grid"}}
{{range $i, $key := .Keys}}
<div class="bg-white p-5 rounded-2xl border border-outline-variant/30 hover:border-primary hover:shadow-lg transition-all flex flex-col justify-between space-y-4"
x-data="{ reveal: false }">
<div class="flex justify-between items-start gap-3">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-xl bg-surface-container-low border border-outline-variant/20 flex items-center justify-center text-primary">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
</div>
<div>
<h3 class="font-bold text-on-surface text-base truncate max-w-[180px]">{{.Name}}</h3>
<span class="text-[10px] font-mono text-outline uppercase tracking-wider">{{.Type}}</span>
</div>
</div>
{{if eq .Strength "secure"}}
<span class="shrink-0 px-2.5 py-0.5 bg-secondary/10 text-secondary border border-secondary/20 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1">
<svg class="w-3.5 h-3.5 text-secondary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
SECURE
</span>
{{else if eq .Strength "moderate"}}
<span class="shrink-0 px-2.5 py-0.5 bg-purple-50 text-tertiary border border-tertiary/20 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1">
<svg class="w-3.5 h-3.5 text-tertiary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
MODERATE
</span>
{{else}}
<span class="shrink-0 px-2.5 py-0.5 bg-red-50 text-error border border-error/20 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1">
<svg class="w-3.5 h-3.5 text-error" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"/></svg>
WEAK
</span>
{{end}}
</div>
<div class="space-y-2 text-xs">
<div class="flex justify-between items-center py-1 border-b border-outline-variant/10">
<span class="text-outline font-semibold uppercase tracking-wider text-[10px]">User Login</span>
<span class="font-mono text-on-surface font-semibold">{{.Username}}</span>
</div>
<div class="flex justify-between items-center py-1 border-b border-outline-variant/10">
<span class="text-outline font-semibold uppercase tracking-wider text-[10px]">Credential Secrets</span>
<div class="flex items-center gap-2">
<span x-show="!reveal" class="font-mono text-on-surface-variant">••••••••••••••••</span>
<button @click="reveal = !reveal"
class="p-1 hover:bg-surface-container rounded text-outline transition-colors" title="Toggle visibility">
<svg x-show="reveal" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a10.06 10.06 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88L6.59 6.59m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"/></svg>
<svg x-show="!reveal" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
</button>
<button data-copy="{{.Passphrase}}"
class="p-1 hover:bg-surface-container rounded text-outline transition-colors" title="Copy secret">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
</button>
</div>
</div>
<div x-show="reveal" x-cloak class="py-1">
<code class="text-[10px] text-on-surface-variant font-mono block break-all bg-surface-container-low p-2 rounded border border-outline-variant/20 max-h-32 overflow-y-auto select-all whitespace-pre-wrap">{{.Passphrase}}</code>
</div>
{{if .Fingerprint}}
<div class="py-1">
<span class="text-outline font-semibold uppercase tracking-wider text-[10px] block mb-0.5">SHA256 FINGERPRINT</span>
<code class="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">{{.Fingerprint}}</code>
</div>
{{end}}
</div>
<div class="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 class="shrink-0">Created {{.CreatedAt}}</span>
<div class="flex items-center justify-between sm:justify-end gap-2 flex-1 min-w-0 w-full">
<div class="flex items-center gap-1.5 min-w-0 flex-1 justify-start sm:justify-end">
{{if .URL}}
<span class="bg-primary-container/15 text-primary px-1.5 py-0.5 rounded font-mono text-[9px] shrink-0">{{.URL}}</span>
{{end}}
</div>
<button hx-delete="/keys/{{.ID}}" hx-target="#key-grid" hx-confirm="Delete {{.Name}}?"
class="p-1 hover:bg-red-50 hover:text-error rounded text-outline transition-colors shrink-0 ml-1">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
</button>
</div>
</div>
</div>
{{end}}
{{if eq (len .Keys) 0}}
<div class="col-span-full p-12 border border-dashed border-outline-variant/40 rounded-2xl text-center text-outline">
No credentials found. Add your first credential.
</div>
{{end}}
{{end}}
+143
View File
@@ -0,0 +1,143 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Keychain · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
<script src="/static/js/clipboard.js"></script>
<script src="/static/js/utils.js"></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 flex items-center px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-lg font-semibold text-on-surface">{{.Title}}</h1>
</header>
<main id="main-content" class="flex-1 overflow-auto p-6" x-data>
<div class="max-w-7xl mx-auto space-y-8">
<!-- Header Panel -->
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
<div>
<h2 class="text-xl font-bold text-on-surface tracking-tight">Keychain & Credentials</h2>
<p class="text-xs text-on-surface-variant mt-0.5">Secure sandbox containing cluster credentials, private SSH keys, and tokens</p>
</div>
<div class="flex items-center gap-3">
<div class="relative">
<svg class="absolute left-3 top-1/2 -translate-y-1/2 text-outline w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
<input type="search" name="q" placeholder="Search credentials..."
hx-get="/keys/grid" hx-trigger="keyup delay:200ms" hx-target="#key-grid"
class="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 @click="$dispatch('open-key-modal')"
class="flex items-center gap-1.5 bg-primary text-white hover:bg-primary/90 font-bold text-xs py-2 px-4 rounded-xl shadow-md transition-all">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
Add Key
</button>
</div>
</div>
<!-- Grid List -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6" id="key-grid">
{{template "credential_grid" .}}
</div>
<!-- Security Advisory Bento -->
<div class="p-5 border border-outline-variant/60 rounded-2xl bg-white/40 flex items-start gap-4 text-xs text-on-surface">
<svg class="w-5 h-5 text-primary shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
<div class="space-y-1">
<h4 class="font-bold text-on-surface">HostKeeper Security Policy & Local Sandbox</h4>
<p class="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>
</div>
<!-- Add Credential Modal -->
<div id="key-modal" class="fixed inset-0 z-50" x-show="open" x-cloak
x-data="{ open: false, readFile($event) {
const file = $event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
document.querySelector('textarea[name=passphrase]').value = e.target.result;
document.querySelector('textarea[name=passphrase]').dispatchEvent(new Event('input'));
};
reader.readAsText(file);
}}"
@open-key-modal.window="open = true" @keydown.escape.window="open = false">
<div class="absolute inset-0 bg-black/40 backdrop-blur-sm" @click="open = false"></div>
<div class="absolute inset-0 flex items-center justify-center p-4" x-show="open" x-transition>
<div class="bg-white rounded-2xl max-w-lg w-full border border-outline-variant/30 shadow-2xl max-h-[90vh] overflow-y-auto">
<div class="flex justify-between items-center border-b border-outline-variant/30 p-6 pb-4">
<h3 class="font-bold text-lg text-on-surface">Register Secure Credential</h3>
<button @click="open = false" class="text-outline hover:text-primary cursor-pointer p-1 rounded-lg">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>
<form hx-post="/keys" hx-target="#key-grid" hx-swap="innerHTML"
@submit="open = false" class="p-6 space-y-4 text-sm">
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Credential Name / Label</label>
<input type="text" name="name" required placeholder="e.g. key_aws_alex"
class="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 class="grid grid-cols-2 gap-4">
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Credential Type</label>
<select name="type"
class="bg-surface-container-low border border-outline-variant/40 rounded-lg py-2 px-3 focus:outline-none focus:border-primary text-sm text-on-surface">
<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 class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Login Username</label>
<input type="text" name="username" required placeholder="e.g. root or ubuntu"
class="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-3 focus:outline-none focus:border-primary text-on-surface">
</div>
</div>
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant uppercase">Key / Secret Value</label>
<textarea name="passphrase" required rows="5"
placeholder="Paste your key or secret here...&#10;&#10;Example SSH key:&#10;-----BEGIN OPENSSH PRIVATE KEY-----&#10;b3BlbnNzaC1rZXktdjEAAAAIA...&#10;-----END OPENSSH PRIVATE KEY-----"
class="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-on-surface text-xs resize-none leading-relaxed"></textarea>
<div class="flex items-center gap-3 mt-1">
<label class="flex items-center gap-1.5 text-xs text-on-surface-variant cursor-pointer hover:text-primary transition-colors">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/></svg>
Or upload a key file
</label>
<input type="file" class="hidden" accept=".pem,.key,.pub,.txt,.ppk,.p12,.pfx" @change="readFile($event)">
<span class="text-[10px] text-outline">.pem .key .ppk .pub .txt</span>
</div>
</div>
<div class="pt-4 flex justify-end gap-3 border-t border-outline-variant/20">
<button type="button" @click="open = false"
class="px-4 py-2 text-xs font-bold text-outline hover:text-on-surface transition-colors">Cancel</button>
<button type="submit"
class="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>
</main>
</div>
</div>
</body>
</html>
+37
View File
@@ -0,0 +1,37 @@
{{define "nav"}}
<nav class="w-[260px] min-h-screen bg-white/70 backdrop-blur-md border-r border-outline-variant/30 flex flex-col shrink-0"
x-data="{ page: '{{.View}}' }">
<div class="p-3 border-b border-outline-variant/20">
<div class="flex items-center gap-2">
<div class="w-8 h-8 rounded-lg bg-primary flex items-center justify-center text-white text-sm font-bold">K</div>
<span class="font-bold text-lg text-on-surface">Hostkeeper</span>
</div>
</div>
<div class="flex-1 px-3 py-4 space-y-0.5">
{{range .NavItems}}
<a href="/{{.ID}}"
:class="page === '{{.ID}}' ? 'bg-primary/10 text-primary font-medium' : 'text-on-surface-variant hover:bg-surface-container-low hover:text-on-surface'"
class="flex items-center gap-3 px-3 py-2 rounded-lg transition-colors text-sm">
<span class="w-5 h-5 flex items-center justify-center">{{svg .Icon}}</span>
<span>{{.Label}}</span>
</a>
{{end}}
</div>
<div class="px-3 py-3 border-t border-outline-variant/20">
<p class="text-xs font-medium text-on-surface-variant uppercase tracking-wide mb-2 px-3">Transfers</p>
<div class="px-3 py-2 rounded-lg bg-surface-container-low/50 text-xs text-on-surface-variant flex items-center gap-2">
<span class="w-1.5 h-1.5 rounded-full bg-on-surface-variant/30"></span>
No active transfers
</div>
</div>
<div class="p-4 border-t border-outline-variant/20">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded-full bg-tertiary/20 flex items-center justify-center text-tertiary text-sm font-semibold">U</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium text-on-surface truncate">User</p>
<p class="text-xs text-on-surface-variant truncate">Local</p>
</div>
</div>
</div>
</nav>
{{end}}
+29
View File
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
<script src="/static/js/clipboard.js"></script>
<script src="/static/js/utils.js"></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 flex items-center px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-lg font-semibold text-on-surface">{{.Title}}</h1>
</header>
<main id="main-content" class="flex-1 overflow-auto p-6">
{{template "settings_content" .}}
</main>
</div>
</div>
</body>
</html>
+244
View File
@@ -0,0 +1,244 @@
{{define "settings_content"}}
<div class="max-w-7xl mx-auto space-y-8 text-sm" x-data="{ toast: '', showToast: false, saveSuccess: false }"
x-init="$watch('showToast', v => v && setTimeout(() => showToast = false, 3000))">
<!-- Toast -->
<div x-show="showToast" x-cloak
class="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">
<svg class="w-4 h-4 text-secondary animate-bounce" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
<span x-text="toast"></span>
</div>
<!-- Header -->
<div class="border-b border-outline-variant/30 pb-4">
<h2 class="text-xl font-bold text-on-surface tracking-tight">Workspace Preferences</h2>
<p class="text-xs text-on-surface-variant mt-0.5">Configure authentication sync protocols and cloud billing</p>
</div>
<div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
<!-- Left: profile + toggles -->
<div class="lg:col-span-8 space-y-8">
<!-- Profile Form -->
<div class="bg-white p-6 rounded-2xl border border-outline-variant/30 shadow-sm space-y-6">
<h3 class="font-bold text-on-surface text-base flex items-center gap-2">
<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
Developer Profile
</h3>
<form method="post" action="/settings" class="grid grid-cols-1 sm:grid-cols-2 gap-5">
<div class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant">FULL NAME</label>
<input type="text" name="name" value="User"
class="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 class="flex flex-col gap-1.5">
<label class="text-xs font-bold text-on-surface-variant">EMAIL ADDRESS</label>
<input type="email" name="email" value="user@hostkeeper.io"
class="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 class="flex flex-col gap-1.5 sm:col-span-2">
<label class="text-xs font-bold text-on-surface-variant">WORKPLACE DESIGNATION / ROLE</label>
<input type="text" name="role" value="DevOps Engineer"
class="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 class="sm:col-span-2 pt-2 flex justify-end">
<button type="submit"
class="flex items-center gap-2 bg-primary text-white hover:bg-primary/90 font-bold text-xs py-2.5 px-6 rounded-xl shadow-md transition-all">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"/></svg>
Save Changes
</button>
</div>
</form>
</div>
<!-- Feature Toggles -->
<div class="bg-white p-6 rounded-2xl border border-outline-variant/30 shadow-sm space-y-6">
<h3 class="font-bold text-on-surface text-base flex items-center gap-2">
<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
Security & Transmission Protocols
</h3>
<div class="space-y-4 divide-y divide-outline-variant/20">
<label class="flex items-center justify-between py-3">
<div class="space-y-0.5 pr-4">
<h4 class="font-bold text-on-surface text-xs sm:text-sm">Cryptographic Keychain Backup</h4>
<p class="text-xs text-on-surface-variant">Synchronize securely encrypted keys automatically inside iCloud/Google drive sandboxes.</p>
</div>
<button type="button" role="switch"
x-data="{ on: true }"
@click="on = !on; $el.classList.toggle('active')"
:class="on ? 'active' : ''"
class="toggle-switch" style="width:44px;height:24px">
<span class="toggle-knob"></span>
</button>
</label>
<label class="flex items-center justify-between pt-3">
<div class="space-y-0.5 pr-4">
<h4 class="font-bold text-on-surface text-xs sm:text-sm">Real-time SFTP Connection Polling</h4>
<p class="text-xs text-on-surface-variant">Enable background file watchers to automatically refresh the directory tree upon local file modifications.</p>
</div>
<button type="button" role="switch"
x-data="{ on: true }"
@click="on = !on; $el.classList.toggle('active')"
:class="on ? 'active' : ''"
class="toggle-switch" style="width:44px;height:24px">
<span class="toggle-knob"></span>
</button>
</label>
<label class="flex items-center justify-between pt-3">
<div class="space-y-0.5 pr-4">
<h4 class="font-bold text-on-surface text-xs sm:text-sm">Desktop Push Notifications</h4>
<p class="text-xs text-on-surface-variant">Trigger native system indicators upon complete transmissions of download/upload streams.</p>
</div>
<button type="button" role="switch"
x-data="{ on: false }"
@click="on = !on; $el.classList.toggle('active')"
:class="on ? 'active' : ''"
class="toggle-switch" style="width:44px;height:24px">
<span class="toggle-knob"></span>
</button>
</label>
</div>
</div>
<!-- Terminal Settings -->
<div class="bg-white p-6 rounded-2xl border border-outline-variant/30 shadow-sm space-y-6">
<h3 class="font-bold text-on-surface text-base flex items-center gap-2">
<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
Terminal Preferences
</h3>
<form method="post" action="/settings" class="space-y-5">
<div class="grid grid-cols-2 gap-4">
<div class="flex flex-col gap-1">
<label class="text-xs font-bold text-on-surface-variant">FONT SIZE</label>
<select name="fontSize"
class="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-3 focus:outline-none focus:border-primary">
<option value="12">12px</option>
<option value="13">13px</option>
<option value="14" selected>14px</option>
<option value="15">15px</option>
<option value="16">16px</option>
<option value="18">18px</option>
</select>
</div>
<div class="flex flex-col gap-1">
<label class="text-xs font-bold text-on-surface-variant">SCROLLBACK</label>
<select name="scrollback"
class="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-3 focus:outline-none focus:border-primary">
<option value="1000">1,000</option>
<option value="5000" selected>5,000</option>
<option value="10000">10,000</option>
</select>
</div>
</div>
<label class="flex items-center justify-between py-2">
<span class="text-sm font-medium text-on-surface">Blinking Cursor</span>
<button type="button" role="switch"
x-data="{ on: true }"
@click="on = !on; $el.classList.toggle('active')"
:class="on ? 'active' : ''"
class="toggle-switch" style="width:44px;height:24px">
<span class="toggle-knob"></span>
</button>
</label>
<label class="flex items-center justify-between py-2">
<span class="text-sm font-medium text-on-surface">Terminal Bell</span>
<button type="button" role="switch"
x-data="{ on: false }"
@click="on = !on; $el.classList.toggle('active')"
:class="on ? 'active' : ''"
class="toggle-switch" style="width:44px;height:24px">
<span class="toggle-knob"></span>
</button>
</label>
<label class="flex items-center justify-between py-2">
<span class="text-sm font-medium text-on-surface">Auto-Reconnect</span>
<button type="button" role="switch"
x-data="{ on: true }"
@click="on = !on; $el.classList.toggle('active')"
:class="on ? 'active' : ''"
class="toggle-switch" style="width:44px;height:24px">
<span class="toggle-knob"></span>
</button>
</label>
<div class="pt-2 flex justify-end">
<button type="submit"
class="bg-primary text-white py-2 px-6 rounded-xl font-bold text-xs shadow-md hover:bg-primary/90 transition-all">Save Settings</button>
</div>
</form>
</div>
</div>
<!-- Right: billing + devices + danger -->
<div class="lg:col-span-4 space-y-8">
<!-- Billing Card -->
<div class="bg-primary text-on-primary p-6 rounded-2xl shadow-lg relative overflow-hidden flex flex-col justify-between h-48">
<div class="relative z-10">
<div class="flex justify-between items-start">
<span class="px-2.5 py-1 bg-white/20 rounded-full font-bold text-[9px] uppercase tracking-wider text-white">HostKeeper Pro</span>
<svg class="w-5 h-5 text-white fill-white" viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
</div>
<h3 class="font-black text-2xl tracking-tight mt-3">Active Workspace</h3>
</div>
<div class="relative z-10 flex justify-between items-end">
<div>
<span class="text-xs opacity-80 uppercase font-semibold">RENEWAL CYCLE</span>
<p class="text-xs font-bold text-white">July 2026</p>
</div>
<span class="text-[10px] font-bold bg-white text-primary rounded-lg px-2.5 py-1 flex items-center gap-1">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
PAID ACCOUNT
</span>
</div>
<div class="absolute right-0 bottom-0 opacity-10 pointer-events-none">
<svg class="w-48 h-48 -rotate-45" viewBox="0 0 24 24" fill="currentColor"><path d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
</div>
</div>
<!-- Devices -->
<div class="bg-white p-5 rounded-2xl border border-outline-variant/30 shadow-sm space-y-4">
<h3 class="font-bold text-on-surface text-sm flex items-center gap-2">
<svg class="w-4 h-4 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
Synchronized Devices
</h3>
<div class="space-y-3.5">
{{range .Devices}}
<div class="flex items-center justify-between text-xs">
<div class="flex items-center gap-2.5 min-w-0">
<div class="p-1.5 bg-surface-container-low border border-outline-variant/20 rounded-lg shrink-0">
<svg class="w-4 h-4 {{if eq .Type "desktop"}}text-primary{{else}}text-outline{{end}}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
{{if eq .Type "desktop"}}<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>{{end}}
{{if eq .Type "mobile"}}<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/>{{end}}
{{if eq .Type "tablet"}}<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"/>{{end}}
</svg>
</div>
<span class="font-bold text-on-surface truncate pr-2">{{.Name}}</span>
</div>
<span class="px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider flex items-center gap-1 shrink-0 {{if .Current}}bg-secondary/10 text-secondary{{else}}bg-surface-container text-outline{{end}}">
<span class="w-1 h-1 rounded-full {{if .Current}}bg-secondary animate-pulse{{else}}bg-outline{{end}}"></span>
{{if .Current}}Online{{else}}Offline{{end}}
</span>
</div>
{{end}}
</div>
</div>
<!-- Danger Zone -->
<div class="p-4 border border-error-container/40 rounded-2xl bg-error-container/5 space-y-3 text-xs" x-data="{ confirm: false }">
<h4 class="font-bold text-error flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
Reset Local State
</h4>
<p class="text-on-surface-variant">Resetting will clear all your locally loaded keystores, snippets, and connection cache buffers from the browser storage.</p>
<button @click="if(confirm('Are you sure you want to flush all local storage configurations?')) { localStorage.clear(); alert('Workspace storage cleared successfully.'); window.location.reload(); }"
class="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>
{{end}}
+27
View File
@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SFTP · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 flex items-center px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-lg font-semibold text-on-surface">{{.Title}}</h1>
</header>
<main id="main-content" class="flex-1 overflow-auto p-6">
{{template "sftp_content" .}}
</main>
</div>
</div>
</body>
</html>
+141
View File
@@ -0,0 +1,141 @@
{{define "sftp_content"}}
<div id="sftp-page" class="max-w-7xl mx-auto space-y-6 relative"
x-data="{ toast: '', showToast: false, showFolderModal: false, folderPane: 'local' }"
x-init="$watch('showToast', v => v && setTimeout(() => showToast = false, 3500))"
@toast-message.window="toast = $event.detail.message; showToast = true">
<!-- Toast -->
<div x-show="showToast" x-cloak
class="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">
<svg class="w-4 h-4 text-secondary animate-bounce" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
<span x-text="toast"></span>
</div>
<!-- Header Panel -->
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
<div>
<h2 class="text-xl font-bold text-on-surface tracking-tight">SFTP Secure File Sync</h2>
<p class="text-xs text-on-surface-variant mt-0.5">Dual streams for real-time asset transmission and file editing</p>
</div>
<div class="flex items-center gap-2">
<button hx-get="/sftp" hx-target="#main-content"
class="flex items-center gap-2 px-3 py-1.5 rounded-lg border border-outline-variant/30 hover:border-primary text-xs font-semibold text-on-surface bg-white transition-all hover:bg-surface-container">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
Reset State
</button>
</div>
</div>
<!-- Dual Panel Body -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<!-- Local Pane -->
<div class="bg-white rounded-2xl border border-outline-variant/30 overflow-hidden shadow-sm flex flex-col h-[520px]">
<div class="p-4 border-b border-outline-variant/50 bg-surface-container-low flex items-center justify-between">
<div class="flex items-center gap-2 min-w-0">
<svg class="w-4 h-4 text-outline shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
<span class="font-bold text-xs text-on-surface truncate uppercase tracking-wider">Local Workstation</span>
</div>
<button @click="$dispatch('open-folder-modal', { pane: 'local' })"
class="text-primary hover:text-primary/80 p-1 rounded hover:bg-primary/5 transition-all" title="New Local Folder">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m-5-8H5a2 2 0 00-2 2v8a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2v2"/></svg>
</button>
</div>
<!-- Breadcrumb -->
<div class="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">
{{range .LocalBreadcrumb}}
<a href="#" hx-get="/sftp/pane?pane=local&dir={{.Path}}" hx-target="#local-pane"
class="text-primary hover:underline cursor-pointer">{{.Name}}</a>
<svg class="w-3 h-3 text-outline/40 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
{{end}}
</div>
<!-- Search -->
<div class="p-3 border-b border-outline-variant/10 relative">
<svg class="absolute left-6 top-1/2 -translate-y-1/2 text-outline w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
<input type="search" name="q" placeholder="Filter local files..."
hx-get="/sftp/pane?pane=local" hx-trigger="keyup delay:200ms" hx-target="#local-pane"
class="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>
<div id="local-pane" class="flex-1 overflow-y-auto min-h-0">
{{template "sftp_pane" dict "Pane" "local" "Files" .LocalFiles "Breadcrumb" .LocalBreadcrumb}}
</div>
</div>
<!-- Remote Pane -->
<div class="bg-white rounded-2xl border border-outline-variant/30 overflow-hidden shadow-sm flex flex-col h-[520px]">
<div class="p-4 border-b border-outline-variant/50 bg-surface-container-low flex items-center justify-between">
<div class="flex items-center gap-2 min-w-0">
<svg class="w-4 h-4 text-primary shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"/></svg>
<span class="font-bold text-xs text-on-surface truncate uppercase tracking-wider">Remote Cluster Node</span>
</div>
<button @click="$dispatch('open-folder-modal', { pane: 'remote' })"
class="text-primary hover:text-primary/80 p-1 rounded hover:bg-primary/5 transition-all" title="New Remote Folder">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m-5-8H5a2 2 0 00-2 2v8a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2v2"/></svg>
</button>
</div>
<!-- Breadcrumb -->
<div class="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">
{{range .RemoteBreadcrumb}}
<a href="#" hx-get="/sftp/pane?pane=remote&dir={{.Path}}" hx-target="#remote-pane"
class="text-primary hover:underline cursor-pointer">{{.Name}}</a>
<svg class="w-3 h-3 text-outline/40 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
{{end}}
</div>
<!-- Search -->
<div class="p-3 border-b border-outline-variant/10 relative">
<svg class="absolute left-6 top-1/2 -translate-y-1/2 text-outline w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
<input type="search" name="q" placeholder="Filter remote files..."
hx-get="/sftp/pane?pane=remote" hx-trigger="keyup delay:200ms" hx-target="#remote-pane"
class="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>
<div id="remote-pane" class="flex-1 overflow-y-auto min-h-0">
{{template "sftp_pane" dict "Pane" "remote" "Files" .RemoteFiles "Breadcrumb" .RemoteBreadcrumb}}
</div>
</div>
</div>
<!-- Drop Zone -->
<div class="p-8 border-2 border-dashed border-outline-variant/40 rounded-2xl text-center bg-white/40 flex flex-col items-center justify-center space-y-2 relative group hover:border-primary transition-colors cursor-pointer">
<svg class="w-10 h-10 text-outline group-hover:text-primary group-hover:scale-110 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>
<h3 class="font-bold text-sm text-on-surface">Drag files directly here to start batch upload</h3>
<p class="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>
<!-- Folder Modal -->
<div id="folder-modal" class="fixed inset-0 z-50" x-data="{ open: false }" x-show="open" x-cloak
@open-folder-modal.window="open = true; folderPane = $event.detail.pane" @keydown.escape.window="open = false">
<div class="absolute inset-0 bg-black/40 backdrop-blur-sm" @click="open = false"></div>
<div class="absolute inset-0 flex items-center justify-center p-4" x-show="open" x-transition>
<div class="bg-white rounded-2xl max-w-sm w-full border border-outline-variant/30 shadow-2xl p-6 space-y-4">
<div class="flex justify-between items-center border-b border-outline-variant/30 pb-3">
<h3 class="font-bold text-lg text-on-surface">New Folder</h3>
<button @click="open = false" class="text-outline hover:text-primary p-1 rounded">Cancel</button>
</div>
<form hx-post="/sftp/mkdir" hx-target="#local-pane" hx-swap="outerHTML"
@submit="open = false" class="space-y-4 text-sm">
<input type="hidden" name="pane" :value="folderPane">
<div class="flex flex-col gap-1">
<label class="text-xs font-bold text-on-surface-variant">FOLDER NAME</label>
<input type="text" name="name" required placeholder="e.g. new-project"
class="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 class="pt-4 flex justify-end gap-3 border-t border-outline-variant/20">
<button type="button" @click="open = false"
class="px-4 py-2 text-xs font-bold text-outline hover:text-on-surface">Cancel</button>
<button type="submit"
class="bg-primary text-white py-2 px-5 rounded-lg font-bold text-xs shadow-md hover:bg-primary/90 transition-all">Create Folder</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{end}}
+77
View File
@@ -0,0 +1,77 @@
{{define "sftp_pane"}}
<div id="{{.Pane}}-pane-content" x-data="{ pane: '{{.Pane}}' }">
<table class="w-full text-left border-collapse text-xs">
<thead>
<tr class="border-b border-outline-variant/20 text-outline uppercase tracking-wider font-bold">
<th class="py-2.5 px-4 font-semibold text-[10px]">Name</th>
<th class="py-2.5 px-4 font-semibold text-[10px] text-right">Size</th>
<th class="py-2.5 px-4 font-semibold text-[10px] text-right">Modified</th>
<th class="py-2.5 px-4 font-semibold text-[10px]"></th>
</tr>
</thead>
<tbody>
{{range .Files}}
<tr class="border-b border-outline-variant/10 hover:bg-primary/5 transition-colors group cursor-pointer"
hx-get="/sftp/pane?pane={{$.Pane}}&dir={{.Name}}" hx-target="#{{$.Pane}}-pane-content" hx-swap="outerHTML">
<td class="py-2.5 px-4">
<div class="font-semibold text-on-surface flex items-center gap-2.5 max-w-[180px] cursor-pointer">
<span class="shrink-0
{{if eq .Type "folder"}}text-yellow-500{{else if eq .Type "code"}}text-purple-500{{else if eq .Type "image"}}text-secondary{{else if eq .Type "lock"}}text-red-400{{else}}text-outline/50{{end}}">
{{if eq .Type "folder"}}
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
{{else if eq .Type "code"}}
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/></svg>
{{else if eq .Type "image"}}
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
{{else if eq .Type "lock"}}
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
{{else}}
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
{{end}}
</span>
<span class="truncate group-hover:text-primary transition-colors">{{.Name}}</span>
</div>
</td>
<td class="py-2.5 px-4 text-right text-on-surface-variant font-mono">{{.Size}}</td>
<td class="py-2.5 px-4 text-right text-outline">{{.Modified}}</td>
<td class="py-2.5 px-4 text-right" @click.stop>
<div class="flex items-center justify-end gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
{{if ne .Type "folder"}}
{{if eq $.Pane "local"}}
<button @click="$dispatch('toast-message', { message: 'Uploading {{.Name}}...' })"
class="p-1 hover:bg-primary/10 rounded text-primary transition-colors" title="Upload to remote">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 10l5-5m0 0l5 5m-5-5v12"/></svg>
</button>
{{end}}
{{if eq $.Pane "remote"}}
<button @click="$dispatch('toast-message', { message: 'Downloading {{.Name}}...' })"
class="p-1 hover:bg-primary/10 rounded text-primary transition-colors" title="Download to local">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
</button>
{{end}}
{{end}}
<button hx-delete="/sftp/rm?pane={{$.Pane}}&name={{.Name}}" hx-target="#{{$.Pane}}-pane-content" hx-swap="outerHTML"
hx-confirm="Delete {{.Name}}?"
class="p-1 hover:bg-red-50 hover:text-error rounded text-outline transition-colors" title="Delete file">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
</button>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
{{if eq (len .Files) 0}}
<div class="text-center py-8 text-on-surface-variant">
<p class="text-sm">This directory is empty</p>
</div>
{{end}}
{{if gt (len .Files) 0}}
<div class="p-3 bg-surface-container-low border-t border-outline-variant/30 text-[10px] text-outline text-center font-bold">
TIP: Click file or {{if eq .Pane "local"}}upload{{else}}download{{end}} button to transmit to server
</div>
{{end}}
</div>
{{end}}
+57
View File
@@ -0,0 +1,57 @@
{{define "snippet_grid"}}
<script id="snippet-data" type="application/json">{{.SnippetsJSON}}</script>
{{range .Snippets}}
<div class="bg-white border border-outline-variant/30 rounded-2xl overflow-hidden shadow-sm flex flex-col group">
<div class="p-5 flex justify-between items-start gap-4">
<div class="space-y-1">
<div class="flex flex-wrap items-center gap-2">
<h3 class="font-bold text-on-surface text-base group-hover:text-primary transition-colors">{{.Name}}</h3>
<div class="flex flex-wrap gap-1">
{{range .Tags}}
<span class="px-2 py-0.5 bg-surface-container text-[10px] font-bold rounded text-on-surface-variant">{{.}}</span>
{{end}}
</div>
</div>
{{if .Description}}
<p class="text-xs text-on-surface-variant leading-relaxed">{{.Description}}</p>
{{end}}
</div>
<div class="flex items-center gap-2 shrink-0">
<button data-copy="{{.Content}}"
class="p-1.5 border border-outline-variant/40 rounded-lg bg-surface-container-low hover:border-primary text-outline hover:text-primary transition-colors"
title="Copy code to clipboard">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
</button>
<button hx-delete="/snippets/{{.ID}}" hx-target="#snippet-grid" hx-confirm="Delete {{.Name}}?"
class="p-1.5 border border-outline-variant/40 rounded-lg bg-surface-container-low hover:border-error text-outline hover:text-error transition-colors"
title="Delete code snippet">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
</button>
</div>
</div>
<div class="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 class="text-on-surface select-all leading-relaxed whitespace-pre font-medium">{{.Content}}</pre>
<button data-copy="{{.Content}}"
class="absolute right-4 top-4 bg-white/90 backdrop-blur border border-outline-variant/30 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">
COPY
</button>
</div>
<div class="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 {{.CreatedAt}}</span>
<span class="flex items-center gap-1 text-primary">
<svg class="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
Ready to inject to shell
</span>
</div>
</div>
{{end}}
{{if eq (len .Snippets) 0}}
<div class="p-12 border border-dashed border-outline-variant/40 rounded-2xl text-center text-outline">
No matching snippet found.
</div>
{{end}}
{{end}}
+184
View File
@@ -0,0 +1,184 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snippets · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
<script src="/static/js/clipboard.js"></script>
<script src="/static/js/utils.js"></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 flex items-center px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-lg font-semibold text-on-surface">{{.Title}}</h1>
</header>
<main id="main-content" class="flex-1 overflow-auto p-6">
<div class="max-w-7xl mx-auto space-y-8">
<!-- Search Header Panel -->
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
<div>
<h2 class="text-xl font-bold text-on-surface tracking-tight">Snippets & Scripts Library</h2>
<p class="text-xs text-on-surface-variant mt-0.5">Quickly reuse and catalog command line shortcuts across remote clusters</p>
</div>
<div class="flex items-center gap-3">
<div class="relative">
<svg class="absolute left-3 top-1/2 -translate-y-1/2 text-outline w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
<input type="search" name="q" placeholder="Search code snippets..."
hx-get="/snippets/grid" hx-trigger="keyup delay:200ms" hx-target="#snippet-grid"
class="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 @click="$dispatch('open-snippet-modal')"
class="flex items-center gap-1.5 bg-primary text-white hover:bg-primary/90 font-bold text-xs py-2 px-4 rounded-xl shadow-md transition-all">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
New Snippet
</button>
</div>
</div>
<!-- Grid: Sidebar + Cards -->
<div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
<!-- Sidebar -->
<div class="lg:col-span-3 space-y-5" x-data="sidebarManager()" x-init="init()">
<div class="bg-white rounded-2xl border border-outline-variant/30 p-4 space-y-4">
<h4 class="text-xs font-bold text-outline-variant uppercase tracking-wider px-2">Collections</h4>
<div class="space-y-1 text-sm font-semibold">
<button hx-get="/snippets/grid" hx-target="#snippet-grid"
:class="activeColl === 'all' ? 'bg-primary/10 text-primary' : 'text-on-surface-variant hover:bg-surface-container-low'"
class="w-full flex items-center justify-between p-2 rounded-lg transition-colors"
@click="activeColl = 'all'">
<span class="flex items-center gap-2"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg> All Code Blocks</span>
<span class="text-xs text-outline" x-text="total"></span>
</button>
<button hx-get="/snippets/grid?collection=favorites" hx-target="#snippet-grid"
:class="activeColl === 'favorites' ? 'bg-primary/10 text-primary' : 'text-on-surface-variant hover:bg-surface-container-low'"
class="w-full flex items-center justify-between p-2 rounded-lg transition-colors"
@click="activeColl = 'favorites'">
<span class="flex items-center gap-2"><svg class="w-4 h-4 text-amber-500" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg> Starred Favorites</span>
<span class="text-xs text-outline" x-text="favCount"></span>
</button>
<button hx-get="/snippets/grid?collection=recent" hx-target="#snippet-grid"
:class="activeColl === 'recent' ? 'bg-primary/10 text-primary' : 'text-on-surface-variant hover:bg-surface-container-low'"
class="w-full flex items-center justify-between p-2 rounded-lg transition-colors"
@click="activeColl = 'recent'">
<span class="flex items-center gap-2"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> Recent</span>
<span class="text-xs text-outline" x-text="recentCount"></span>
</button>
</div>
</div>
<div class="bg-white rounded-2xl border border-outline-variant/30 p-4 space-y-3">
<h4 class="text-xs font-bold text-outline-variant uppercase tracking-wider px-2">Tag Categories</h4>
<div class="flex flex-wrap gap-1.5 p-1">
<button hx-get="/snippets/grid" hx-target="#snippet-grid"
:class="activeTag === 'all' ? 'bg-primary text-white' : 'bg-surface-container-low text-on-surface-variant hover:bg-surface-container'"
class="px-3 py-1 rounded-full text-xs font-bold transition-all"
@click="activeTag = 'all'">All Tags</button>
{{range .AllTags}}
<button hx-get="/snippets/grid?tag={{.}}" hx-target="#snippet-grid"
:class="activeTag === '{{.}}' ? 'bg-primary text-white' : 'bg-surface-container-low text-on-surface-variant hover:bg-surface-container'"
class="px-3 py-1 rounded-full text-xs font-bold transition-all"
@click="activeTag = '{{.}}'">
{{.}}
</button>
{{end}}
</div>
</div>
</div>
<!-- Snippet Cards -->
<div class="lg:col-span-9 space-y-6" id="snippet-grid">
{{template "snippet_grid" .}}
</div>
</div>
</div>
<!-- Add Snippet Modal -->
<div id="snippet-modal" class="fixed inset-0 z-50" x-data="{ open: false }" x-show="open" x-cloak
@open-snippet-modal.window="open = true" @keydown.escape.window="open = false">
<div class="absolute inset-0 bg-black/40 backdrop-blur-sm" @click="open = false"></div>
<div class="absolute inset-0 flex items-center justify-center p-4" x-show="open" x-transition>
<div class="bg-white rounded-2xl max-w-lg w-full border border-outline-variant/30 shadow-2xl p-6 space-y-4">
<div class="flex justify-between items-center border-b border-outline-variant/30 pb-3">
<h3 class="font-bold text-lg text-on-surface">Store Custom Snippet</h3>
<button @click="open = false" class="text-outline hover:text-primary p-1 rounded">Cancel</button>
</div>
<form hx-post="/snippets" hx-target="#snippet-grid" hx-swap="innerHTML"
@submit="open = false" class="space-y-4 text-sm">
<div class="flex flex-col gap-1">
<label class="text-xs font-bold text-on-surface-variant">SNIPPET TITLE</label>
<input type="text" name="name" required placeholder="e.g. Purge Docker Cache"
class="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 class="flex flex-col gap-1">
<label class="text-xs font-bold text-on-surface-variant">SHORT DESCRIPTION / USAGE</label>
<input type="text" name="description" placeholder="e.g. Safe cleanup to recover workspace disk capacity."
class="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 class="flex flex-col gap-1">
<label class="text-xs font-bold text-on-surface-variant">CODE SYNTAX BLOCK</label>
<textarea name="content" required rows="4" placeholder="e.g. systemctl restart nginx"
class="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"></textarea>
</div>
<div class="flex flex-col gap-1">
<label class="text-xs font-bold text-on-surface-variant">PRIMARY TAG CATEGORY</label>
<select name="tags"
class="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>
<input type="hidden" name="collection" value="recent">
<div class="pt-4 flex justify-end gap-3 border-t border-outline-variant/20">
<button type="button" @click="open = false"
class="px-4 py-2 text-xs font-bold text-outline hover:text-on-surface">Cancel</button>
<button type="submit"
class="bg-primary text-white py-2 px-5 rounded-lg font-bold text-xs shadow-md hover:bg-primary/90 transition-all">Save Code Snippet</button>
</div>
</form>
</div>
</div>
</div>
</main>
</div>
</div>
<script>
function sidebarManager() {
return {
activeColl: 'all',
activeTag: 'all',
total: 0,
favCount: 0,
recentCount: 0,
init() {
this.updateCounts();
document.body.addEventListener('htmx:afterSwap', () => this.updateCounts());
},
updateCounts() {
const el = document.getElementById('snippet-data');
if (!el) return;
try {
const snippets = JSON.parse(el.textContent) || [];
this.total = snippets.length;
this.favCount = snippets.filter(s => s.Collection === 'favorites').length;
this.recentCount = snippets.filter(s => s.Collection === 'recent').length;
} catch(e) {}
}
};
}
</script>
</body>
</html>
+38
View File
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Terminal · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<link rel="stylesheet" href="/static/xterm/xterm.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden" x-data="terminalManager()" x-init="init()">
<header class="h-14 border-b border-outline-variant/30 flex items-center gap-2 px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-xl font-bold tracking-tight text-on-surface">{{.Title}}</h1>
<span class="text-xs text-on-surface-variant mt-0.5">Interactive SSH shell with multi-tab session management</span>
<div class="flex-1"></div>
<button @click="addTab()"
class="p-1.5 rounded-lg bg-surface-container hover:bg-primary-container hover:text-on-primary-container text-on-surface-variant transition-all" title="New Tab">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
</button>
</header>
<main id="main-content" class="flex-1 flex flex-col overflow-auto p-6">
{{template "terminal_content" .}}
</main>
</div>
</div>
<script id="hosts-data" type="application/json">{{.HostsJSON}}</script>
<script id="selected-host" type="application/json">"{{.SelectedHost}}"</script>
<script src="/static/xterm/xterm.js"></script>
<script src="/static/js/terminal.js"></script>
</body>
</html>
+85
View File
@@ -0,0 +1,85 @@
{{define "terminal_content"}}
<div class="max-w-7xl mx-auto space-y-6 flex flex-col flex-1 min-h-0 w-full">
<!-- Session Tab Toolbar -->
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-3">
<div class="flex items-center gap-2 overflow-x-auto no-scrollbar scroll-smooth pr-6">
<template x-for="(tab, i) in tabs" :key="tab.id">
<div @click="switchTab(i)"
:class="activeTab === i ? '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'"
class="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">
<svg class="w-3.5 h-3.5" :class="activeTab === i ? 'text-primary' : 'text-outline'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 17V7c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v10c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 014 17zm6 0V7c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v10c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 0110 17zm6 0V7c0-.621.504-1.125 1.125-1.125h2.25C19.496 5.875 20 6.379 20 7v10c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 0116 17z"/></svg>
<span class="truncate max-w-[120px]" x-text="tab.name"></span>
<button @click.stop="closeTab(i)" class="p-0.5 hover:bg-black/10 rounded transition-colors">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>
</template>
<button @click="addTab()"
class="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">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
</button>
</div>
<div class="flex items-center gap-4 text-xs font-mono shrink-0">
<div class="flex items-center gap-1.5 text-secondary">
<span class="w-2 h-2 rounded-full bg-secondary animate-pulse"></span>
<span>SECURE CRYPTO PATH</span>
</div>
<div class="text-outline">
HOST: <span class="text-on-surface font-semibold" x-text="tabs.length ? tabs[activeTab].host : '—'"></span>
</div>
</div>
</div>
<!-- Terminal shell frame -->
<div class="flex-1 bg-white border border-outline-variant rounded-2xl shadow-sm flex flex-col overflow-hidden min-h-0">
<!-- Terminal Header -->
<div class="px-4 py-2 bg-surface-container-low border-b border-outline-variant/30 flex justify-between items-center shrink-0">
<div class="flex items-center gap-1.5">
<span class="w-3 h-3 rounded-full bg-error/80"></span>
<span class="w-3 h-3 rounded-full bg-primary-container/80"></span>
<span class="w-3 h-3 rounded-full bg-secondary/80"></span>
<span class="text-[10px] font-mono font-bold text-outline ml-2">ssh -i id_ed25519 root@<span x-text="tabs.length ? tabs[activeTab].host : '—'"></span></span>
</div>
<div class="flex items-center gap-3">
<button @click="clearBuffer()"
class="text-[10px] uppercase font-bold text-outline hover:text-primary transition-colors flex items-center gap-1">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182"/></svg>
Clear Buffer
</button>
</div>
</div>
<!-- xterm.js containers — managed by JS, not Alpine -->
<div id="xterm-wrapper" class="flex-1 relative min-h-0"></div>
<!-- Input prompt -->
<form @submit.prevent="submitCommand()"
class="p-3 border-t border-outline-variant/40 bg-surface-container-low flex items-center gap-2.5 shrink-0">
<span class="font-mono text-xs font-bold text-primary pl-2 shrink-0 flex items-center gap-1">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.75 17.25L12 21m0 0l-3.75-3.75M12 21V3"/></svg>
root@<span x-text="tabs.length ? tabs[activeTab].name : 'host'"></span>:~$
</span>
<input type="text" x-model="command" autofocus
placeholder='Type a command (e.g. "help", "ls", "docker ps", "ping google.com")...'
class="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"
class="p-1.5 bg-primary text-white rounded-lg hover:bg-primary-container hover:text-on-primary-container transition-all" title="Execute Command">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z"/></svg>
</button>
</form>
</div>
<!-- Shortcut pills -->
<div class="flex flex-wrap items-center gap-2 text-[11px] font-mono font-bold text-on-surface-variant">
<span class="text-outline">SHORTCUT SUGGESTIONS:</span>
<button type="button" @click="insertCommand('help')" class="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">help</button>
<button type="button" @click="insertCommand('ls')" class="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">ls</button>
<button type="button" @click="insertCommand('docker ps')" class="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">docker ps</button>
<button type="button" @click="insertCommand('uname -a')" class="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">uname -a</button>
<button type="button" @click="insertCommand('ping 8.8.8.8')" class="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">ping 8.8.8.8</button>
<button type="button" @click="insertCommand('cat server.js')" class="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">cat server.js</button>
<button type="button" @click="insertCommand('keychain')" class="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">keychain</button>
<button type="button" @click="insertCommand('clear')" class="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">clear</button>
</div>
</div>
{{end}}
-21
View File
@@ -1,21 +0,0 @@
package main
import (
"fmt"
"os"
)
var (
version = "dev"
buildTime = "unknown"
)
func main() {
if len(os.Args) > 1 && os.Args[1] == "--version" {
fmt.Printf("hostkeeper %s (built: %s)\n", version, buildTime)
return
}
fmt.Println("HostKeeper - SSH/SFTP Management Tool")
fmt.Println("Run 'hostkeeper --help' for usage.")
}
+1303
View File
File diff suppressed because it is too large Load Diff
+446
View File
@@ -0,0 +1,446 @@
# Hostkeeper V2 — Architecture
> **Status**: Migrasi React → HTMX
> **Last Updated**: 2026-07-07
> **Dokumen arsitektur baru**: [ARCHITECTURE_HTMX.md](ARCHITECTURE_HTMX.md)
> **V1 (existing)**: CLI/TUI SSH/SFTP manager — frozen, no changes.
---
## ⚠️ Keputusan Arsitektur
Hostkeeper V2 menggunakan **GoFiber + HTMX**, **bukan React/SPA**.
Keputusan ini diambil karena:
1. Developer lebih nyaman dengan Go daripada JavaScript
2. ~90% kode adalah Go + HTML template
3. Hanya ~410 baris JS yang diperlukan (xterm.js, clipboard, toggle)
4. Build lebih sederhana — tanpa Vite, npm, TypeScript
5. Bisa berjalan di browser biasa tanpa Electron
**Dokumen arsitektur lengkap ada di** [`ARCHITECTURE_HTMX.md`](ARCHITECTURE_HTMX.md).
---
### 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 planning)
│ ├── 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
│ └── TIMELINE.md # Project timeline
├── CHANGELOG.md
├── README.md
├── AGENTS.md # AI session checkpoint
├── v1/ # V1 CLI/TUI (FROZEN)
│ ├── cmd/hostkeeper/
│ ├── internal/
│ ├── pkg/
│ ├── test/
│ ├── docs/ # V1 docs
│ ├── go.mod
│ └── Makefile
├── template/ # React UI template (Lumina System)
└── app/ # V2 app (scaffolding not started)
├── backend/
├── frontend/
└── electron/
```
---
## 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/...
```
+385
View File
@@ -0,0 +1,385 @@
# Hostkeeper V2 — Architecture (HTMX)
> **Status**: Approved — Menggantikan arsitektur React sebelumnya
> **Last Updated**: 2026-07-07
> **Keputusan**: React → GoFiber + HTMX + Alpine.js + minimal JS
---
## 1. Arsitektur Baru
Hostkeeper V2 menggunakan arsitektur **server-rendered HTML** dengan interaktivitas via HTMX, bukan SPA React.
```
┌────────────────────────────────────────────────────┐
│ Browser / Electron WebView │
│ ┌──────────────────────────────────────────────┐ │
│ │ HTMX (14kb) + Alpine.js (15kb) + xterm.js │ │
│ │ │ │
│ │ ● HTMX: semua interaksi (search, filter, │ │
│ │ modal, form, navigasi) │ │
│ │ ● Alpine.js: client state (toast, toggle, │ │
│ │ passphrase reveal, tab) │ │
│ │ ● xterm.js: terminal emulator (hanya │ │
│ │ halaman terminal) │ │
│ │ ● Vanilla JS: clipboard, toggle switch, │ │
│ │ strength calc │ │
│ └────────────────┬─────────────────────────────┘ │
│ │ hx-get/hx-post/hx-ws │
│ ┌────────────────▼─────────────────────────────┐ │
│ │ GoFiber v2 Backend (localhost:1947) │ │
│ │ │ │
│ │ ┌──────────────┐ ┌──────────────────────┐ │ │
│ │ │ HTML handlers │ │ WebSocket /xterm.js │ │ │
│ │ │ (Fiber + html│ │ (SSH I/O via WS) │ │ │
│ │ │ template) │ └──────────────────────┘ │ │
│ │ └──────┬───────┘ │ │
│ │ │ go.mod replace │ │
│ │ ┌────▼────┐ │ │
│ │ │ v1/pkg/ │ ssh, crypto, storage, config │ │
│ │ └─────────┘ │ │
│ └───────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
```
### Alur Request
```
1. User klik tombol "Filter Active"
│ hx-get="/hosts?filter=active"
│ hx-target="#host-list"
2. GoFiber handler:
func (h *Handler) ListHosts(c fiber.Ctx) error {
hosts := h.store.Filter("active")
return c.Render("partials/host_list", fiber.Map{
"Hosts": hosts,
})
}
3. Server return HTML partial
<div id="host-list" hx-swap-oob="true">
{{range .Hosts}}
<div class="host-card">...</div>
{{end}}
</div>
4. HTMX swap HTML ke DOM (tanpa reload)
```
---
## 2. Tech Stack
| Layer | Teknologi | Versi | Fungsi |
|-------|-----------|-------|--------|
| Backend | GoFiber v2 | v2.52+ | HTTP server, routing, middleware |
| Template | html/template | stdlib | Server-side HTML rendering |
| Frontend | HTMX | v2.0+ | HTML-over-HTTP interaktivitas |
| Client state | Alpine.js | v3.14+ | Modal, toast, toggle state |
| Terminal | xterm.js | v5.5+ | SSH terminal emulator |
| Styling | TailwindCSS v4 | v4.0+ | Utility-first CSS |
| CSS custom | Custom CSS | — | dot-grid, glassmorphism, keyframes |
| Icons | Lucide (inline SVG) | — | SVG icon system |
| Desktop | Electron (opsional) | v35+ | Browser wrapper |
| Mobile | WebView | — | Android/iOS shell |
---
## 3. Struktur Folder
```
app/backend/
├── main.go ← Entry point Fiber app
├── go.mod ← module git.tukangketik.id/swanadiva/hostkeeper/v2
├── go.sum
├── internal/
│ ├── handler/ ← HTTP handlers (render HTML + HTMX partials)
│ │ ├── dashboard.go GET/POST /hosts, /hosts/{id}
│ │ ├── terminal.go GET /terminal, WS /terminal/ws
│ │ ├── sftp.go GET /sftp/ls, POST /sftp/{action}
│ │ ├── snippets.go GET/POST /snippets
│ │ ├── keychain.go GET/POST /keys
│ │ ├── settings.go GET/POST /settings
│ │ ├── brief.go GET /brief (overlay)
│ │ └── health.go GET /api/health
│ │
│ ├── model/ ← Go structs (data models)
│ │ ├── host.go Host, HostFilter
│ │ ├── file.go FileItem
│ │ ├── snippet.go Snippet
│ │ ├── keychain.go KeychainItem
│ │ ├── device.go Device
│ │ ├── transfer.go BackgroundTransfer
│ │ └── config.go Config, Toggle
│ │
│ ├── template/ ← Template helpers/funcs
│ │ └── funcs.go activeClass, formatBytes, timeAgo, strengthBadge
│ │
│ └── middleware/
│ └── viewdata.go Inject .View, .ActiveNav, .User ke semua template
├── static/ ← Static assets (served via Fiber)
│ ├── css/
│ │ ├── output.css ← TailwindCSS v4 build output
│ │ └── custom.css ← dot-grid, glassmorphism, keyframes, scrollbar
│ ├── js/
│ │ ├── htmx.min.js ← HTMX (14kb)
│ │ ├── alpine.min.js ← Alpine.js (15kb)
│ │ ├── terminal.js ← xterm.js + WebSocket init
│ │ ├── clipboard.js ← navigator.clipboard.writeText()
│ │ ├── toggles.js ← Custom toggle switch click handler
│ │ └── utils.js ← passphrase reveal, strength calc, toast
│ ├── xterm/ ← xterm.js build files
│ └── img/ ← Images/icons
└── views/ ← Go HTML templates
├── layout.html ← Base layout (sidebar, header, scripts)
├── index.html ← Entry page (extends layout + content block)
└── partials/ ← HTMX-swappable partials
├── nav.html ← Sidebar navigation
├── dashboard.html ← Host page container
├── host_list.html ← Host card grid/list (HTMX swap target)
├── host_card.html ← Single host card
├── host_modal.html ← Add host modal form
├── terminal.html ← Terminal page (xterm.js container)
├── sftp.html ← Dual-pane file browser
├── sftp_pane.html ← Single file pane (for HTMX swap)
├── snippets.html ← Snippet page
├── snippet_grid.html ← Snippet cards (HTMX swap target)
├── snippet_modal.html ← Add snippet form
├── keychain.html ← Key page
├── key_grid.html ← Key cards (HTMX swap target)
├── key_modal.html ← Add key form
├── settings.html ← Settings form + toggles
├── brief.html ← Brief overlay panel
└── toast.html ← Toast notification
```
---
## 4. Komponen UI & State Management
### 4.1 Navigasi (HTMX)
Sidebar navigation menggunakan HTMX untuk swap halaman:
```html
<a href="/hosts"
hx-get="/hosts"
hx-target="#main-content"
hx-push-url="true"
class="nav-item {{if eq .View "hosts"}}active{{end}}">
{{svg "server"}}
<span>Hosts</span>
</a>
```
### 4.2 State Client (Alpine.js)
State yang butuh client-side reactivity:
```html
<!-- Toggle view mode -->
<div x-data="{ view: 'grid' }">
<button @click="view = 'list'" :class="view === 'list' ? 'bg-primary text-white' : ''">
List
</button>
<div x-show="view === 'grid'" id="host-grid">
{{template "host_list" .}}
</div>
</div>
<!-- Modal -->
<div x-data="{ open: false }">
<button @click="open = true">Add Host</button>
<div x-show="open" class="modal-backdrop">
<div @click.outside="open = false" class="modal-content">
<form hx-post="/hosts" hx-target="#host-list" @submit="open = false">
...
</form>
</div>
</div>
</div>
<!-- Toast -->
<div x-data="{ toast: '', show: false }"
x-init="$watch('show', v => v && setTimeout(() => show = false, 3000))"
x-show="show"
class="toast">
<span x-text="toast"></span>
</div>
```
### 4.3 JS Murni (Vanilla)
```javascript
// clipboard.js — copy to clipboard
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
// trigger toast via Alpine
document.querySelector('[x-data]').__x.$data.toast = 'Copied!';
document.querySelector('[x-data]').__x.$data.show = true;
}
// toggles.js — custom toggle switch
function toggleSwitch(el) {
const checked = el.getAttribute('aria-checked') === 'true';
el.setAttribute('aria-checked', !checked);
fetch(`/settings/toggle?key=${el.dataset.key}&val=${!checked}`, { method: 'POST' });
}
```
---
## 5. Data Models (Go Structs)
Semua data model di `internal/model/`, mapping dari template React `types.ts`:
```go
// model/host.go
type Host struct {
ID string `json:"id"`
Name string `json:"name"`
IP string `json:"ip"`
OS string `json:"os"`
Provider string `json:"provider"`
Status string `json:"status"` // "active" | "offline"
LastSeen string `json:"lastSeen"`
Type string `json:"type"` // "api" | "db" | "edge" | "web" | "desktop" | "server"
}
// model/snippet.go
type Snippet struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Code string `json:"code"`
Tags []string `json:"tags"`
Collection string `json:"collection"` // "favorites" | "recent" | "all"
UpdatedAt string `json:"updatedAt"`
Icon string `json:"icon"`
}
```
Lihat `docs/DATA_MODELS.md` untuk definisi lengkap.
---
## 6. HTMX Patterns yang Digunakan
| Pattern | Contoh | Keterangan |
|---------|--------|------------|
| Search | `hx-get="/hosts?q=..." hx-trigger="keyup delay:200ms" hx-target="#host-list"` | Debounced search |
| Filter | `hx-get="/hosts?filter=active" hx-target="#host-list"` | Tab filter |
| Modal | Alpine `x-show` + `hx-post` | Form dalam modal |
| Infinite scroll | `hx-get="/hosts?page=2" hx-trigger="revealed" hx-target="#host-list" hx-swap="beforeend"` | Load more |
| Delete | `hx-delete="/hosts/123" hx-target="#host-card-123" hx-swap="delete" hx-confirm="Yakin?"` | Confirm + delete |
| Toast | Alpine state + `hx-trigger="htmx:afterRequest"` dari response header `HX-Trigger: showToast` | Notifikasi |
| Tab | Alpine `x-data` + `x-show` | Panel tab |
---
## 7. Keuntungan HTMX Dibanding React
| Aspek | React (sebelumnya) | HTMX (sekarang) |
|-------|-------------------|-----------------|
| Dependency JS | 10+ library (React, Zustand, dll) | 3 library (HTMX, Alpine, xterm) |
| Baris JS | ~2.878 baris TS/JSX | ~410 baris vanilla JS |
| Build step | Vite + TypeScript + npm | CSS build + copy static |
| Bahasa dominan | 60% TS + 40% Go | 90% Go + 10% HTML/JS |
| State management | Zustand store | Server-side (HTMX) + Alpine |
| API layer | REST JSON + manual fetch | HTML partials langsung |
| Electron | Wajib (SPA) | Opsional (bisa browser) |
| Debugging | React DevTools | Browser DevTools (HTML langsung) |
| Time to implement | ~6 minggu | ~4 minggu (estimasi) |
---
## 8. Cara Kerja: React → HTMX Mapping per Halaman
### Dashboard (Host List)
| React | HTMX |
|-------|------|
| `useState` searchQuery | `hx-get="/hosts?q={search}"` |
| `useState` statusFilter | `hx-get="/hosts?filter=active"` |
| `useState` viewMode | Alpine `x-data="{ view: 'grid' }"` |
| `useState` showAddModal | Alpine `x-show="open"` |
| `onChange` filter | HTML `<select>` + `hx-get` |
| `onSubmit` add host | `hx-post="/hosts"` |
| `transfers` progress | `{{range}}` template loop |
### Terminal
| React | HTMX |
|-------|------|
| `useState` tabs | Alpine `x-data="{ tabs: [], active: '1' }"` |
| `useRef` scroll | `xterm.scrollToBottom()` (built-in) |
| `useEffect` autoScroll | `terminal.onData(() => scrollToBottom())` |
| Command parser | WebSocket → Go backend → SSH |
| Multi-tab | Alpine + multiple xterm instances |
### SFTP
| React | HTMX |
|-------|------|
| `useState` local/remote path | `hx-get="/sftp/ls?path=..." hx-target="#pane"` |
| `useState` search | `hx-get="/sftp/ls?q=..." hx-trigger="keyup"` |
| File click navigation | `hx-get="/sftp/ls?path={dir}" hx-push-url` |
| Upload/download | `hx-post="/sftp/upload"` |
| Toast | Alpine `x-data` + `setTimeout` |
### Snippets
| React | HTMX |
|-------|------|
| `useState` search/tag/collection | `hx-get="/snippets?q=&tag=&col="` |
| `useState` copiedId | JS `copyToClipboard()` |
| `useState` showAddForm | Alpine `x-show="open"` |
| Copy | `onclick="copyToClipboard('code')"` |
### Keychain
| React | HTMX |
|-------|------|
| `useState` search | `hx-get="/keys?q=..."` |
| `useState` revealPassId | Alpine `x-data="{ reveal: false }"` |
| `useState` copiedId | JS `copyToClipboard()` |
| Strength badge | Go template: `{{if gt (len .Passphrase) 12}}secure{{end}}` |
### Settings
| React | HTMX |
|-------|------|
| Form state | HTML `<form>` + `hx-post="/settings"` |
| Toggle switches | JS click handler + `fetch POST /settings/toggle` |
| Danger zone | `onclick="localStorage.clear(); location.reload()"` |
### Brief Overlay
| React | HTMX |
|-------|------|
| `isOpen` + `onClose` | Alpine `x-show="open"` + `@click="open = false"` |
| Konten statis | Go template render (HTML murni) |
---
## 9. File yang Tidak Berubah
Dokumen ini **melengkapi** (bukan mengganti) dokumen yang masih relevan:
| Dokumen | Status | Alasan |
|---------|--------|--------|
| `docs/DATA_MODELS.md` | ✅ Tetap | Go struct masih sama |
| `docs/API.md` | ✅ Tetap | REST endpoint masih sama |
| `docs/PERFORMANCE.md` | ✅ Tetap | Performance tips masih relevan |
| `docs/UI_TERMIUS_REFERENCE.md` | ✅ Tetap | Visual design masih sama |
| `docs/ARCHITECTURE.md` | 🔄 Diupdate | Ditimpa dengan ringkasan + link ke ARCHITECTURE_HTMX.md |
| `docs/SPRINT_PLAN.md` | 🔄 Diupdate | Sprint tasks diubah ke HTMX |
| `docs/UI_COMPONENTS.md` | 🔄 Diganti | React → HTMX + Alpine |
| `docs/BUILD_SYSTEM.md` | 🔄 Diupdate | Hapus Vite, tambah CSS build |
| `docs/TIMELINE.md` | 🔄 Diupdate | Timeline disesuaikan |
| `docs/PROGRESS.md` | 🔄 Diupdate | Status tracker diperbarui |
+183
View File
@@ -0,0 +1,183 @@
# Hostkeeper V2 — Build System
> **Status**: Updated untuk HTMX
> **Last Updated**: 2026-07-07
> **Frontend**: Go HTML template + HTMX + TailwindCSS v4 (tanpa Vite/npm/React)
---
## 1. Build Overview
Hostkeeper V2 adalah **single Go binary** yang melayani HTML + static files.
| Platform | Output | Wrapper | Backend |
|----------|--------|---------|---------|
| macOS (ARM64) | `.dmg` | Electron (opsional) | Go binary |
| macOS (x64) | `.dmg` | Electron (opsional) | Go binary |
| Windows (x64) | `.exe` installer | Electron (opsional) | Go binary |
| Linux (x64) | `.AppImage` | Electron (opsional) | Go binary |
| Android (ARM64) | `.aab` | WebView | Go library (.aar) |
| iOS (ARM64) | `.ipa` | WKWebView | Go framework (.xcframework) |
**Catatan**: Tanpa Electron app tetap bisa jalan — tinggal buka `http://localhost:1947` di browser.
---
## 2. Build Pipeline
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ TailwindCSS │ │ Go Build │ │ Platform │
│ Build │ → │ (single │ → │ Package │
│ (CSS) │ │ binary) │ │ (opsional) │
└──────────────┘ └──────────────┘ └──────────────┘
```
### Step 1: CSS Build
```bash
# TailwindCSS v4 — input.css → output.css
npx @tailwindcss/cli -i static/css/input.css -o static/css/output.css
# Atau via Makefile
make css
```
### Step 2: Go Build
```bash
# Development (hot reload via air)
go run .
# Production (single binary with embedded static)
CGO_ENABLED=0 go build -ldflags="-s -w" -o dist/hostkeeper .
# Cross-compile
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o dist/hostkeeper-darwin-arm64 .
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o dist/hostkeeper-linux-amd64 .
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o dist/hostkeeper-windows-amd64.exe .
```
### Step 3: Elektron Package (Opsional)
```bash
cd app/electron
npm install
npm run build # produces .dmg / .exe / .AppImage
```
---
## 3. Development Workflow
```bash
# Terminal 1: Go backend (dengan hot reload)
cd app/backend
go run .
# Terminal 2: CSS watch
cd app/backend
npx @tailwindcss/cli -i static/css/input.css -o static/css/output.css --watch
# Buka browser
open http://localhost:1947
```
### Hot Reload Tools
```bash
# Install air
go install github.com/air-verse/air@latest
# Run
air
```
---
## 4. Struktur Build Output
```
dist/
├── hostkeeper ← Go binary (single file)
├── static/ ← Embedded static assets
│ ├── css/
│ ├── js/
│ ├── xterm/
│ └── img/
└── views/ ← Embedded HTML templates
├── layout.html
└── partials/
```
GoFiber `embed` package untuk embed static + views:
```go
//go:embed static/* views/*
var embedFS embed.FS
func main() {
app := fiber.New()
app.Static("/static", "./static")
engine := html.NewFileSystem(http.FS(embedFS), ".html")
app.Settings.Views = engine
}
```
---
## 5. Dependencies
### Go
```
github.com/gofiber/fiber/v2
github.com/gofiber/contrib/websocket
github.com/gofiber/template/html/v2
github.com/fasthttp/websocket
```
### JavaScript (static files — download, bukan npm)
```
static/js/htmx.min.js ← https://unpkg.com/htmx.org@2
static/js/alpine.min.js ← https://cdn.jsdelivr.net/npm/alpinejs@3
static/xterm/xterm.js ← https://unpkg.com/@xterm/xterm
static/xterm/xterm.css ← https://unpkg.com/@xterm/xterm/css
```
### CSS Tooling
```
@tailwindcss/cli ← npx, build time only
```
---
## 6. Makefile
```makefile
.PHONY: dev build css clean
dev:
@echo "Starting dev server..."
@go run .
css:
npx @tailwindcss/cli -i static/css/input.css -o static/css/output.css
css-watch:
npx @tailwindcss/cli -i static/css/input.css -o static/css/output.css --watch
build:
CGO_ENABLED=0 go build -ldflags="-s -w" -o dist/hostkeeper .
build-all:
GOOS=darwin GOARCH=arm64 go build -o dist/hostkeeper-darwin-arm64 .
GOOS=darwin GOARCH=amd64 go build -o dist/hostkeeper-darwin-amd64 .
GOOS=linux GOARCH=amd64 go build -o dist/hostkeeper-linux-amd64 .
GOOS=windows GOARCH=amd64 go build -o dist/hostkeeper-windows-amd64.exe .
clean:
rm -rf dist/
```
+391
View File
@@ -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.
+709
View File
@@ -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 |
+214
View File
@@ -0,0 +1,214 @@
# 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-07-07
> **Status**: Sprint 0—6 selesai. V2 HTMX feature complete.
---
## 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 + HTMX + xterm.js + Alpine.js |
| **Mobile** | Go mobile library + WebView wrapper (Android/iOS) |
| **Backend language** | Go 1.26 |
| **HTTP framework** | GoFiber v2 (fasthttp-based) |
| **Frontend** | HTMX + Alpine.js + xterm.js (minimal JS, server-rendered HTML) |
| **Styling** | TailwindCSS v4 + custom CSS (Lumina System) |
| **Desktop wrapper** | Electron (opsional — bisa lewat browser saja) |
| **Mobile wrapper** | gomobile + WebView |
| **V1 (existing)** | CLI/TUI SSH/SFTP manager — 105 tests, all passing. Frozen. |
**Keputusan arsitektur**: Migrasi dari React/SPA ke HTMX/server-rendered HTML.
Lihat [ARCHITECTURE_HTMX.md](ARCHITECTURE_HTMX.md) untuk detail.
---
## 2. Current Status Summary
| Item | Status |
|------|--------|
| Planning documents (HTMX) | DONE |
| Sprint 0 — Setup GoFiber + HTMX | DONE |
| Sprint 1 — Dashboard + Host List | DONE |
| Sprint 2 — Snippets + Keychain | DONE |
| Sprint 3 — Settings + Brief | DONE |
| Sprint 4 — SFTP Dual-Pane | DONE |
| Sprint 5 — Terminal + xterm.js | DONE |
| Sprint 6 — Storage Integration | DONE |
---
## 3. Sprint Checklist (HTMX)
### Sprint 0 — Setup GoFiber + HTMX
- [x] Go module init (`app/backend/go.mod`)
- [x] Install GoFiber v2 + deps
- [x] Minimal Fiber server (`main.go`) — port 1947
- [x] Static files serving (`/static/`)
- [x] HTML template engine (html/template via gofiber/template)
- [x] Download HTMX + Alpine.js (`static/js/`)
- [x] Setup TailwindCSS v4 — `input.css``output.css`
- [x] Custom CSS (Lumina) — dot-grid, glassmorphism, keyframes, toggle, modal, x-cloak
- [x] Layout template (`views/layout.html`) — sidebar + header + main
- [x] Nav template (`views/nav.html`) — nav items with active state
- [x] Index + routing (`views/index.html` + `handler/dashboard.go`)
- [x] Health endpoint (`handler/health.go`)
- **Verify**: `curl :1947/api/health``{"app":"hostkeeper-v2","status":"ok"}`
### Sprint 1 — Dashboard + Host List
- [x] Model Host + HostStore (`internal/model/host.go`) — mock data (8 hosts)
- [x] Dashboard handler — full page render (`handler/dashboard.go`)
- [x] Host list partial (`views/host_list.html`) — cards + list view
- [x] Search HTMX — `hx-get="/hosts?q=..." hx-trigger="keyup delay:200ms"`
- [x] Filter status — `<select>` + `hx-get="/hosts?filter=..."`
- [x] View toggle (grid/list) — Alpine `x-data="{ view: 'grid' }"` + `x-show`
- [x] Add host modal (`views/host_modal.html`) — Alpine event-driven `$dispatch('open-modal')`
- [x] POST /hosts — create host via HTMX form swap
- [x] DELETE /hosts/:id — hx-delete with confirm
- [x] Background transfers panel — static placeholder in nav
- **Verify**: Homepage renders with 8 hosts, search+filter works, create+delete CRUD
### Sprint 2 — Snippets + Keychain
- [x] Model Snippet + SnippetStore (`internal/model/snippet.go`)
- [x] Model Key + KeyStore (`internal/model/keychain.go`)
- [x] Snippets handler (`internal/handler/snippets.go`)
- [x] Keychain handler (`internal/handler/keychain.go`)
- [x] Snippets template (`views/snippets.html`) — standalone page (no layout inheritance)
- [x] Snippet grid partial (`views/snippet_grid.html`) — HTMX partial
- [x] Keychain template (`views/keychain.html`) — standalone page
- [x] Key grid partial (`views/key_grid.html`) — HTMX partial
- [x] Clipboard JS (`static/js/clipboard.js`)
- [x] Utils JS (`static/js/utils.js`)
- **Note**: Removed `layout.html` — all pages are now standalone (Go template `{{define}}` conflict)
- **Verify**: Both pages render, CRUD works, clipboard copies, strength badges display
### Sprint 3 — Settings + Brief
- [x] Model Device + Config (`internal/model/device.go`, `internal/model/config.go`)
- [x] Settings handler + UpdateConfig (`internal/handler/settings.go`)
- [x] Brief handler (`internal/handler/brief.go`)
- [x] Settings template (`views/settings.html`) — profile, tabs, toggles, devices, danger zone
- [x] Brief template (`views/brief.html`) — keyboard shortcuts, about
- [x] Toggle switch JS (`static/js/toggles.js`) — Alpine toggle data
- [x] Danger zone — confirm flow with localStorage.clear()
- **Verify**: Settings page renders with tabs, toggles work via Alpine, brief page shows shortcuts
### Sprint 4 — SFTP Dual-Pane
- [x] Model FileItem + Transfer (`internal/model/file.go`, `internal/model/transfer.go`)
- [x] SFTP handler (`internal/handler/sftp.go`) — page, pane partial, create folder, delete file
- [x] SFTP template (`views/sftp.html`) — dual-pane (local/remote), breadcrumb, search, drop-zone, toast, folder modal
- [x] SFTP pane partial (`views/sftp_pane.html`) — file table with icons by type, hover actions
- [x] `dict` helper fungsitambah di template engine (`main.go`)
- [x] Folder create (Alpine modal + POST) + delete (hx-delete)
- **Verify**: Dual-pane renders, file list per type icons, CRUD works, drop-zone + toast present
### Sprint 5 — Terminal + xterm.js
- [x] Download xterm.js v5.3.0 + xterm.css (`static/xterm/`)
- [x] Install gofiber/contrib/websocket v1.3.4
- [x] Terminal handler (`internal/handler/terminal.go`) — page + WebSocket mock shell (ls, pwd, cd, cat, whoami, etc.)
- [x] Terminal template (`views/terminal.html`) — dark theme, tab bar with Alpine, xterm containers
- [x] Terminal JS (`static/js/terminal.js`) — Alpine terminalManager, xterm init, WS connect, tab CRUD
- [x] Tab management — add/switch/close tabs, random host assignment
- **Verify**: Terminal page renders, xterm.js loaded, WS endpoint returns Upgrade Required
### Sprint 6 — Data Store Integration
- [x] `go.mod` replace directive → `v1/pkg/crypto` + `v1/pkg/knownhosts` importable
- [x] `store/` package — JSON file persistence for hosts, snippets, keys, settings (stored at `~/Library/Application Support/hostkeeper/v2/`)
- [x] Model SSH fields (Hostname, Port, Username, AuthType, Password, KeyID, Group, Tags, Notes)
- [x] Handlers updated to use persistent store instead of in-memory mock data
- [x] `sshconn/` package — real SSH client via `golang.org/x/crypto/ssh`
- [x] Terminal WebSocket — real SSH connection (falls back to mock)
- [x] Dynamic host list in terminal page (server-rendered via JSON script tag)
- [x] All mock defaults removed from model packages (Host, Snippet, Key no longer have `defaultXxx()`)
- [x] Settings persist via JSON file
---
## 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) | — |
| 2026-07-07 | Sprint 0: GoFiber+HTMX scaffolding, TailwindCSS, layout, nav, health | `43a19b7` |
| 2026-07-07 | Sprint 1: Host model+store, dashboard CRUD, HTMX partials (grid/list, search, filter, modal, delete), transfers panel | `d771925`, `86620b0` |
| 2026-07-07 | Sprint 2 dimulai: Snippet + Keychain models created | — |
| 2026-07-07 | Sprint 2 selesai: all CRUD, standalone templates, clipboard.js, utils.js, fix template {{define}} conflict | `c4b0d7d` |
| 2026-07-07 | Sprint 3 selesai: settings page, tabs, toggles, connected devices, danger zone, brief page | `c5ac07e` |
| 2026-07-07 | Sprint 4 selesai: SFTP dual-pane, breadcrumb, per-type icons, create/delete, toast, drop-zone | `941a67b` |
| 2026-07-07 | Sprint 5 selesai: xterm.js terminal, WebSocket mock shell, tab management | `04d9cfb` |
| 2026-07-07 | Sprint 6 selesai: JSON persistence, go.mod replace, real SSH client, dynamic hosts, model SSH fields | `(pending — akan commit)` |
---
## 6. How to Continue
### For a new AI agent:
All Sprint 0—6 tasks for HTMX are **complete**. The V2 backend is fully functional with:
- GoFiber v2 server on `:1947`
- HTMX + Alpine.js for interactivity
- JSON file persistence in `~/Library/Application Support/hostkeeper/v2/`
- Real SSH terminal (with mock fallback)
- All CRUD operations for hosts, snippets, keychain, settings
Future work areas (beyond Sprint 6):
- **Real SFTP**: Connect SFTP dual-pane to real SSH via `github.com/pkg/sftp`
- **Mobile wrapper**: `gomobile` + WebView
- **Electron wrapper**: Wrap in Electron for standalone desktop app
- **Tests**: Write Go unit/integration tests for handlers and store
- **CI/CD**: GitHub Actions for build + test
- **Encryption**: Wire up `v1/pkg/crypto` to encrypt stored data
- **Known Hosts**: Integrate `v1/pkg/knownhosts` for SSH host key verification
### For a returning AI agent:
1. **Read this file** — check "Last Session Notes" for context
2. **Check git log**`git log --oneline -10`
3. **All Sprint items are `[x]`** — pick from "Future work areas" above
4. **Update this file** when done
---
## 7. Reference Documents Index
| Document | When to read |
|----------|-------------|
| `docs/PROGRESS.md` | Always (first) — know where to continue |
| `AGENTS.md` (root) | Architecture, paths, important rules |
| `docs/ARCHITECTURE_HTMX.md` | System design, component flow |
| `docs/ARCHITECTURE.md` | Summary + pointer to HTMX doc |
| `docs/SPRINT_PLAN.md` | Detailed file-by-file task instructions |
| `docs/API.md` | REST + WebSocket endpoint specs |
| `docs/DATA_MODELS.md` | Go struct definitions |
| `docs/UI_COMPONENTS.md` | HTMX partials / Alpine components |
| `docs/BUILD_SYSTEM.md` | Build pipeline (Go + CSS) |
| `docs/UI_TERMIUS_REFERENCE.md` | Visual layout reference |
| `docs/PERFORMANCE.md` | Performance & stability notes |
| `template/` dir | Visual reference only (Lumina System) |
---
## 8. Git History Reference
| Commit | Description |
|--------|-------------|
| `43a19b7` | Sprint 0 — GoFiber + HTMX + TailwindCSS v4 scaffolding |
| `d771925` | Sprint 1 — host model, mock store, dashboard CRUD, HTMX partials |
| `86620b0` | Sprint 1 final — delete host, Alpine modal events, grid/list toggle, transfers panel |
---
**IMPORTANT**: This file MUST be updated after every development session to ensure continuity.
+252
View File
@@ -0,0 +1,252 @@
# Hostkeeper V2 — Sprint Plan (HTMX)
> **Status**: Migrasi React → HTMX
> **Last Updated**: 2026-07-07
> **Framework**: GoFiber v2 + HTMX + Alpine.js + TailwindCSS v4
---
## Sprint 0 — Setup GoFiber + HTMX
**Goal**: GoFiber server running, layout HTML renders, TailwindCSS works.
### Tasks
| # | Task | Files | Verify |
|---|------|-------|--------|
| 0.1 | Go module init | `app/backend/go.mod` | `go mod init` clean |
| 0.2 | Install GoFiber + deps | `go.mod` | `go get github.com/gofiber/fiber/v2` |
| 0.3 | Minimal Fiber server | `app/backend/main.go` | Server starts on :1947 |
| 0.4 | Static files serving | `main.go` | `/static/` serves files |
| 0.5 | HTML template engine | `main.go` + `views/layout.html` | Template renders |
| 0.6 | Download HTMX + Alpine | `static/js/htmx.min.js`, `static/js/alpine.min.js` | JS files exist |
| 0.7 | Setup TailwindCSS v4 | `static/css/output.css` | Tailwind classes work |
| 0.8 | Custom CSS (Lumina) | `static/css/custom.css` | dot-grid, glassmorphism, keyframes |
| 0.9 | Layout template | `views/layout.html` | Sidebar + header + main |
| 0.10 | Nav template | `views/partials/nav.html` | Nav items with active state |
| 0.11 | Index + routing | `views/index.html` + `handler/dashboard.go` | Dashboard renders |
| 0.12 | Health endpoint | `handler/health.go` | `curl :1947/api/health` |
### Files to Create (Sprint 0)
```
app/backend/
├── main.go
├── go.mod
├── go.sum
├── internal/
│ ├── handler/
│ │ ├── dashboard.go
│ │ └── health.go
│ └── middleware/
│ └── viewdata.go
├── static/
│ ├── css/
│ │ ├── output.css
│ │ └── custom.css
│ └── js/
│ ├── htmx.min.js
│ └── alpine.min.js
└── views/
├── layout.html
├── index.html
└── partials/
└── nav.html
```
---
## Sprint 1 — Dashboard + Host List
**Goal**: Dashboard halaman dengan host list, search, filter, add host modal.
### Tasks
| # | Task | Files |
|---|------|-------|
| 1.1 | Model Host | `internal/model/host.go` |
| 1.2 | Dashboard handler | `internal/handler/dashboard.go` |
| 1.3 | Dashboard template | `views/partials/dashboard.html` |
| 1.4 | Host list partial | `views/partials/host_list.html` |
| 1.5 | Host card partial | `views/partials/host_card.html` |
| 1.6 | Search HTMX | `hx-get="/hosts?q=..." hx-trigger="keyup delay:200ms"` |
| 1.7 | Filter status | `hx-get="/hosts?filter=active"` + `<select>` |
| 1.8 | View toggle (grid/list) | Alpine `x-data` |
| 1.9 | Add host modal | `views/partials/host_modal.html` + Alpine |
| 1.10 | POST /hosts | Handler create host |
| 1.11 | Background transfers | `views/partials/dashboard.html` |
### Files to Create (Sprint 1)
```
internal/model/host.go
views/partials/dashboard.html
views/partials/host_list.html
views/partials/host_card.html
views/partials/host_modal.html
views/partials/toast.html
static/js/clipboard.js ← mulai buat
```
---
## Sprint 2 — Snippets + Keychain
**Goal**: Snippet library + credential keychain dengan CRUD.
### Tasks
| # | Task | Files |
|---|------|-------|
| 2.1 | Model Snippet | `internal/model/snippet.go` |
| 2.2 | Model Keychain | `internal/model/keychain.go` |
| 2.3 | Snippets handler | `internal/handler/snippets.go` |
| 2.4 | Keychain handler | `internal/handler/keychain.go` |
| 2.5 | Snippets template | `views/partials/snippets.html` |
| 2.6 | Snippet grid partial | `views/partials/snippet_grid.html` |
| 2.7 | Snippet modal | `views/partials/snippet_modal.html` |
| 2.8 | Keychain template | `views/partials/keychain.html` |
| 2.9 | Key grid partial | `views/partials/key_grid.html` |
| 2.10 | Key modal | `views/partials/key_modal.html` |
| 2.11 | Clipboard JS | `static/js/clipboard.js` |
| 2.12 | Passphrase reveal + strength | `static/js/utils.js` |
### Files to Create (Sprint 2)
```
internal/model/snippet.go
internal/model/keychain.go
internal/handler/snippets.go
internal/handler/keychain.go
views/partials/snippets.html
views/partials/snippet_grid.html
views/partials/snippet_modal.html
views/partials/keychain.html
views/partials/key_grid.html
views/partials/key_modal.html
static/js/clipboard.js
static/js/utils.js
```
---
## Sprint 3 — Settings + Brief Overlay
**Goal**: Settings page with profile form, toggles, connected devices.
### Tasks
| # | Task | Files |
|---|------|-------|
| 3.1 | Model Device + Config | `internal/model/device.go`, `internal/model/config.go` |
| 3.2 | Settings handler | `internal/handler/settings.go` |
| 3.3 | Brief handler | `internal/handler/brief.go` |
| 3.4 | Settings template | `views/partials/settings.html` |
| 3.5 | Brief template | `views/partials/brief.html` |
| 3.6 | Toggle switch JS | `static/js/toggles.js` |
| 3.7 | Toggle CSS | In custom.css |
| 3.8 | Danger zone | `localStorage.clear()` handler |
### Files to Create (Sprint 3)
```
internal/model/device.go
internal/model/config.go
internal/handler/settings.go
internal/handler/brief.go
views/partials/settings.html
views/partials/brief.html
static/js/toggles.js
```
---
## Sprint 4 — SFTP Dual-Pane
**Goal**: File browser dual-pane dengan navigasi folder, upload/download.
### Tasks
| # | Task | Files |
|---|------|-------|
| 4.1 | Model FileItem | `internal/model/file.go` |
| 4.2 | Model Transfer | `internal/model/transfer.go` |
| 4.3 | SFTP handler | `internal/handler/sftp.go` |
| 4.4 | SFTP template | `views/partials/sftp.html` |
| 4.5 | SFTP pane partial | `views/partials/sftp_pane.html` |
| 4.6 | Breadcrumb navigation | In sftp.html |
| 4.7 | Folder create + delete | Modal Alpine + POST |
| 4.8 | Toast notification | Alpine `x-data` |
### Files to Create (Sprint 4)
```
internal/model/file.go
internal/model/transfer.go
internal/handler/sftp.go
views/partials/sftp.html
views/partials/sftp_pane.html
```
---
## Sprint 5 — Terminal + xterm.js
**Goal**: SSH terminal via WebSocket + xterm.js dengan multi-tab.
### Tasks
| # | Task | Files |
|---|------|-------|
| 5.1 | Download xterm.js | `static/xterm/xterm.js`, `static/xterm/xterm.css` |
| 5.2 | Terminal handler | `internal/handler/terminal.go` |
| 5.3 | WebSocket handler | `internal/handler/terminal.go` (WS upgrade) |
| 5.4 | Terminal template | `views/partials/terminal.html` |
| 5.5 | Terminal JS | `static/js/terminal.js` (xterm init + WS) |
| 5.6 | Tab management | Alpine `x-data="terminalTabs()"` |
| 5.7 | SSH pipe (mock dulu) | Go backend → SSH via v1/pkg/ssh |
| 5.8 | Multi-tab per host | Alpine state + multiple xterm instances |
### Files to Create (Sprint 5)
```
internal/handler/terminal.go
views/partials/terminal.html
static/js/terminal.js
static/xterm/xterm.js
static/xterm/xterm.css
```
---
## Sprint 6 — Data Store Integration
**Goal**: Ganti mock data dengan real storage dari v1/pkg/. Integrasi SSH, SFTP, crypto.
### Tasks
| # | Task | Files |
|---|------|-------|
| 6.1 | replace directive go.mod | `app/backend/go.mod` |
| 6.2 | Integrate v1/pkg/storage | Semua handler |
| 6.3 | Integrate v1/pkg/config | `handler/settings.go` |
| 6.4 | Integrate v1/pkg/crypto | `handler/keychain.go` |
| 6.5 | Integrate v1/pkg/knownhosts | `handler/terminal.go` |
| 6.6 | Real SSH via v1/pkg/ssh | `handler/terminal.go` WS |
| 6.7 | Real SFTP via v1/pkg/ssh | `handler/sftp.go` |
| 6.8 | Remove all mock data | Semua handler |
---
## Total Files
| Sprint | Go Files | HTML Templates | JS Files | CSS Files |
|--------|----------|---------------|----------|-----------|
| Sprint 0 | 4 | 3 | 2 | 2 |
| Sprint 1 | 2 | 5 | 1 | 0 |
| Sprint 2 | 4 | 6 | 2 | 0 |
| Sprint 3 | 4 | 2 | 1 | 0 |
| Sprint 4 | 3 | 2 | 0 | 0 |
| Sprint 5 | 1 | 1 | 1 | 0 |
| Sprint 6 | (modify existing) | 0 | 0 | 0 |
| **Total** | **18** | **19** | **7** | **2** |
+129
View File
@@ -0,0 +1,129 @@
# Hostkeeper V2 — Timeline & Milestones (HTMX)
> **Status**: Updated untuk HTMX
> **Last Updated**: 2026-07-07
> **Start Date**: 2026-07-07
> **Target MVP**: 2026-08-01 (estimasi ~3.5 minggu)
---
## Timeline Overview
```
Minggu 1 │ Sprint 0 ─ Sprint 1 ─ │── Foundation + Dashboard
Minggu 2 │ Sprint 2 ─ Sprint 3 ─ │── Snippets + Keychain + Settings
Minggu 3 │ Sprint 4 ─────────────│── SFTP
Minggu 4 │ Sprint 5 ─ Sprint 6 ─ │── Terminal + Storage Integration
└────────────────────────┘
7 Jul 14 Jul 21 Jul 28 Jul
```
---
## Detailed Timeline
### Sprint 0 + Sprint 1 — Foundation + Dashboard
**5 hari — 7 Jul s.d. 11 Jul**
| Day | Date | Deliverable |
|-----|------|-------------|
| 1 | 7 Jul | Go module, Fiber server, static files, HTMX + Alpine |
| 2 | 8 Jul | Layout template, nav sidebar, health endpoint |
| 3 | 9 Jul | Host model, dashboard handler, host list template |
| 4 | 10 Jul | Search HTMX, filter, view toggle, add host modal |
| 5 | 11 Jul | Background transfers, toast notification, CSS final |
**Milestone M1 — Dashboard Functional (11 Jul)**
- GoFiber server running on :1947
- Layout dengan sidebar navigasi
- Dashboard dengan host list, search, filter, add host
- HTMX interaktivitas berfungsi
### Sprint 2 — Snippets + Keychain
**3 hari — 14 Jul s.d. 16 Jul**
| Day | Date | Deliverable |
|-----|------|-------------|
| 6 | 14 Jul | Snippet model + handler + template + search/filter |
| 7 | 15 Jul | Add snippet modal, clipboard JS, tag filter |
| 8 | 16 Jul | Keychain model + handler + template + passphrase reveal |
**Milestone M2 — Snippets + Keys CRUD (16 Jul)**
- Snippet library dengan search, tag filter, add modal
- Keychain dengan strength badge, passphrase reveal, copy
### Sprint 3 — Settings + Brief
**2 hari — 17 Jul s.d. 18 Jul**
| Day | Date | Deliverable |
|-----|------|-------------|
| 9 | 17 Jul | Settings handler + template + toggle switches |
| 10 | 18 Jul | Brief overlay, connected devices, danger zone |
**Milestone M3 — Settings Complete (18 Jul)**
- Profile form, toggle switches, connected devices
- Brief design system overlay
### Sprint 4 — SFTP
**4 hari — 21 Jul s.d. 24 Jul**
| Day | Date | Deliverable |
|-----|------|-------------|
| 11 | 21 Jul | FileItem + Transfer model, SFTP handler |
| 12 | 22 Jul | Dual-pane layout, breadcrumb navigation |
| 13 | 23 Jul | Folder create/delete, upload/download |
| 14 | 24 Jul | Search pane, toast notification, polish |
**Milestone M4 — SFTP Works (24 Jul)**
- Dual-pane file browser dengan navigasi folder
- Upload/download, create/delete folder
### Sprint 5 — Terminal
**3 hari — 25 Jul s.d. 28 Jul**
| Day | Date | Deliverable |
|-----|------|-------------|
| 15 | 25 Jul | xterm.js setup, WebSocket handler |
| 16 | 26 Jul | SSH pipe via v1/pkg/ssh, terminal I/O |
| 17 | 28 Jul | Multi-tab Alpine, polish, error handling |
**Milestone M5 — Terminal Works (28 Jul)**
- SSH terminal via WebSocket + xterm.js
- Multi-tab support
### Sprint 6 — Storage Integration + Polish
**3 hari — 29 Jul s.d. 31 Jul**
| Day | Date | Deliverable |
|-----|------|-------------|
| 18 | 29 Jul | replace directive, v1/pkg/storage integration |
| 19 | 30 Jul | v1/pkg/crypto, config, knownhosts integration |
| 20 | 31 Jul | Remove mock data, final testing, bug fixes |
**Milestone MVP — Hostkeeper V2 Ready (31 Jul)**
- All features functional with real data persistence
- Single Go binary, ready for Electron wrapping
---
## Key Milestones
| Milestone | Date | Deliverable |
|-----------|------|-------------|
| M1 | 11 Jul | Dashboard + search/filter + add host |
| M2 | 16 Jul | Snippets + Keychain CRUD |
| M3 | 18 Jul | Settings + Brief overlay |
| M4 | 24 Jul | SFTP dual-pane file browser |
| M5 | 28 Jul | Terminal SSH via WebSocket |
| MVP | 31 Jul | Full integration with real storage |
---
## Estimasi vs React (dulu)
| Metrik | React (rencana lama) | HTMX (sekarang) |
|--------|---------------------|-----------------|
| Total waktu | ~6 minggu (30 Jun - 7 Aug) | ~3.5 minggu (7 Jul - 31 Jul) |
| Files | ~50 (Go + React + TS + Vite) | ~38 (Go + HTML + JS) |
| JS dependencies | 10+ library + npm | 3 file JS (HTMX, Alpine, xterm) |
| Build complexity | Vite + TypeScript + npm + Electron | CSS build + Go build |
+510
View File
@@ -0,0 +1,510 @@
# Hostkeeper V2 — HTMX Components & Partials
> **Status**: Menggantikan React Component Tree
> **Last Updated**: 2026-07-07
> **Framework**: Go HTML Template + HTMX + Alpine.js
---
## 1. Template Structure
```
views/
├── layout.html ← Base layout (html, head, body, sidebar, header, scripts)
├── index.html ← Entry: {{template "layout" .}} + {{template "content" .}}
└── partials/ ← HTMX-swappable partial fragments
├── nav.html
├── dashboard.html
├── host_list.html
├── host_card.html
├── host_modal.html
├── terminal.html
├── sftp.html
├── sftp_pane.html
├── snippets.html
├── snippet_grid.html
├── snippet_modal.html
├── keychain.html
├── key_grid.html
├── key_modal.html
├── settings.html
├── brief.html
└── toast.html
```
---
## 2. Komponen per Halaman
### 2.1 Navigasi (layout.html + nav.html)
```html
<!-- layout.html — base shell -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
<script src="/static/js/utils.js"></script>
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<title>Hostkeeper V2</title>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid" hx-boost="true">
<div class="flex h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 ...">
<h1 class="text-lg font-semibold">{{.Title}}</h1>
</header>
<main id="main-content" class="flex-1 overflow-auto p-6">
{{block "content" .}}{{end}}
</main>
</div>
</div>
</body>
</html>
<!-- nav.html — sidebar -->
<nav x-data="{ collapsed: false }"
class="w-[260px] ... glass-sidebar border-r border-outline-variant/30 flex flex-col">
<div class="p-4 ...">
<span class="text-primary font-bold text-lg">Hostkeeper</span>
</div>
<div class="flex-1 px-3 space-y-1">
{{range .NavItems}}
<a href="/{{.ID}}"
hx-get="/{{.ID}}" hx-target="#main-content" hx-push-url="true"
class="flex items-center gap-3 px-3 py-2 rounded-lg
{{if eq $.View .ID}}bg-primary/10 text-primary font-medium
{{else}}text-on-surface-variant hover:bg-surface-container-low{{end}}">
{{svg .Icon}}
<span>{{.Label}}</span>
</a>
{{end}}
</div>
</nav>
```
### 2.2 Dashboard (partials/dashboard.html)
```html
<!-- Container: halaman utama -->
<div id="dashboard-page" x-data="{ view: 'grid' }">
<!-- Header stats -->
<div class="grid grid-cols-3 gap-4 mb-6">
<div class="stat-card">...</div>
<div class="stat-card">...</div>
<div class="stat-card">...</div>
</div>
<!-- Search + Filter + ViewToggle -->
<div class="flex items-center gap-3 mb-6">
<input type="search" name="q" placeholder="Search hosts..."
hx-get="/hosts?q=..." hx-trigger="keyup delay:200ms"
hx-target="#host-list" hx-include="[name='filter']"
class="...">
<select name="filter"
hx-get="/hosts?filter={value}" hx-target="#host-list">
<option value="all">All</option>
<option value="active">Active</option>
<option value="offline">Offline</option>
</select>
<button @click="view = 'grid'" :class="view === 'grid' ? 'bg-primary/10' : ''">
{{svg "layout-grid"}}
</button>
<button @click="view = 'list'" :class="view === 'list' ? 'bg-primary/10' : ''">
{{svg "list"}}
</button>
</div>
<!-- Host list (swap target) -->
<div id="host-list"
x-show="view === 'grid'"
class="grid grid-cols-4 gap-4">
{{template "host_list" .Hosts}}
</div>
<div x-show="view === 'list'" class="...">
{{template "host_list_table" .Hosts}}
</div>
</div>
```
### 2.3 Terminal (partials/terminal.html)
```html
<div id="terminal-page" x-data="terminalTabs()">
<!-- Tab bar -->
<div class="flex items-center gap-1 mb-4">
<template x-for="tab in tabs" :key="tab.id">
<button @click="switchTab(tab.id)"
:class="activeTab === tab.id ? 'bg-primary/10 text-primary' : ''"
class="px-3 py-1 rounded text-sm">
<span x-text="tab.title"></span>
<span @click.stop="closeTab(tab.id)" class="ml-2 cursor-pointer">&times;</span>
</button>
</template>
<button @click="addTab()" class="...">+</button>
</div>
<!-- Terminal container -->
<div x-ref="terminalContainer"
class="bg-[#1e1e1e] rounded-xl p-4 font-mono text-sm min-h-[400px]">
<div id="xterm-container" class="..."></div>
</div>
</div>
<script src="/static/xterm/xterm.js"></script>
<script src="/static/js/terminal.js"></script>
```
### 2.4 SFTP (partials/sftp.html)
```html
<div id="sftp-page" x-data="{ toast: '', showToast: false }">
<div class="grid grid-cols-2 gap-6">
<!-- Local pane -->
<div class="pane glass-panel">
<div class="flex items-center gap-2 mb-4">
{{svg "hard-drive"}}
<span class="font-medium">Local Workstation</span>
<input type="search" placeholder="Search files..." class="...">
</div>
<div class="breadcrumb">
{{range .LocalBreadcrumb}}
<a href="#" hx-get="/sftp/ls?path={{.Path}}"
hx-target="#local-pane" class="...">{{.Name}}</a>
{{end}}
</div>
<div id="local-pane" class="file-table">
{{template "sftp_pane" .LocalFiles}}
</div>
</div>
<!-- Remote pane -->
<div class="pane glass-panel">
... sama seperti local pane ...
</div>
</div>
<!-- Drop zone -->
<div class="drop-zone ...">Drop files here</div>
<!-- Toast -->
<div x-show="showToast"
x-text="toast"
x-init="$watch('showToast', v => v && setTimeout(() => showToast = false, 3000))"
class="toast">
</div>
</div>
```
### 2.5 Snippets (partials/snippets.html)
```html
<div id="snippets-page" x-data="{ showForm: false, copiedId: null }">
<div class="flex gap-6">
<!-- Sidebar filters -->
<div class="w-48 space-y-4">
<div class="space-y-1">
<h3 class="text-sm font-medium text-on-surface-variant">Collections</h3>
<a href="#" hx-get="/snippets?col=all" hx-target="#snippet-grid"
class="filter-item {{if eq .Collection "all"}}active{{end}}">All</a>
<a href="#" hx-get="/snippets?col=favorites" hx-target="#snippet-grid"
class="filter-item">Favorites</a>
<a href="#" hx-get="/snippets?col=recent" hx-target="#snippet-grid"
class="filter-item">Recent</a>
</div>
<div class="space-y-1">
<h3 class="text-sm font-medium text-on-surface-variant">Tags</h3>
{{range .AllTags}}
<a href="#" hx-get="/snippets?tag={{.}}" hx-target="#snippet-grid"
class="filter-item">{{.}}</a>
{{end}}
</div>
</div>
<!-- Main grid -->
<div class="flex-1">
<div class="flex items-center gap-3 mb-4">
<input type="search" placeholder="Search snippets..."
hx-get="/snippets?q=..." hx-trigger="keyup delay:200ms"
hx-target="#snippet-grid" class="...">
<button @click="showForm = true" class="btn-primary">
+ Snippet
</button>
</div>
<div id="snippet-grid" class="grid grid-cols-2 gap-4">
{{template "snippet_grid" .Snippets}}
</div>
</div>
</div>
<!-- Add snippet modal -->
<div x-show="showForm" class="modal-backdrop">
<div @click.outside="showForm = false" class="modal-content">
<form hx-post="/snippets" hx-target="#snippet-grid" @submit="showForm = false">
<input name="title" placeholder="Title" required>
<input name="description" placeholder="Description">
<textarea name="code" placeholder="Code" rows="8" required></textarea>
<input name="tags" placeholder="Tags (comma separated)">
<button type="submit">Save</button>
<button type="button" @click="showForm = false">Cancel</button>
</form>
</div>
</div>
</div>
```
### 2.6 Keychain (partials/keychain.html)
```html
<div id="keychain-page" x-data="{ showForm: false, revealPass: null }">
<div class="flex items-center gap-3 mb-6">
<input type="search" placeholder="Search credentials..."
hx-get="/keys?q=..." hx-trigger="keyup delay:200ms"
hx-target="#key-grid" class="...">
<button @click="showForm = true" class="btn-primary">+ Credential</button>
</div>
<div id="key-grid" class="grid grid-cols-2 gap-4">
{{range .Keys}}
<div class="card glass-panel p-4">
<div class="flex items-center justify-between mb-3">
<div class="flex items-center gap-2">
{{svg "key"}}
<span class="font-medium">{{.Name}}</span>
</div>
<span class="strength-badge-{{.Strength}}">{{.Strength}}</span>
</div>
<div class="space-y-1 text-sm">
<div class="flex justify-between">
<span class="text-on-surface-variant">User</span>
<span>{{.User}}</span>
</div>
<div class="flex justify-between">
<span class="text-on-surface-variant">Passphrase</span>
<div x-data="{ reveal: false }" class="flex items-center gap-2">
<span x-text="reveal ? '{{.Passphrase}}' : '••••••••'"></span>
<button @click="reveal = !reveal">
{{svg "eye"}}
</button>
<button onclick='copyToClipboard("{{.Passphrase}}")'>
{{svg "copy"}}
</button>
</div>
</div>
<div class="flex justify-between">
<span class="text-on-surface-variant">{{.Fingerprint}}</span>
</div>
</div>
</div>
{{end}}
</div>
</div>
```
### 2.7 Settings (partials/settings.html)
```html
<div id="settings-page">
<div class="max-w-2xl space-y-8">
<!-- Profile form -->
<div class="card glass-panel p-6">
<h2 class="text-lg font-semibold mb-4">Profile</h2>
<form hx-post="/settings" hx-target="#settings-form" class="space-y-4">
<div class="grid grid-cols-2 gap-4">
<div>
<label>Name</label>
<input name="name" value="{{.Profile.Name}}" class="...">
</div>
<div>
<label>Email</label>
<input name="email" value="{{.Profile.Email}}" class="...">
</div>
</div>
<button type="submit" class="btn-primary">Save</button>
</form>
</div>
<!-- Toggles -->
<div class="card glass-panel p-6">
<h2 class="text-lg font-semibold mb-4">Security & Transmission</h2>
{{range .Toggles}}
<div class="flex items-center justify-between py-3">
<div>
<span class="font-medium">{{.Label}}</span>
<p class="text-sm text-on-surface-variant">{{.Desc}}</p>
</div>
<button class="toggle-switch {{if .Enabled}}active{{end}}"
data-key="{{.Key}}"
onclick="toggleSwitch(this)"
aria-checked="{{.Enabled}}">
<span class="toggle-knob"></span>
</button>
</div>
{{end}}
</div>
<!-- Connected devices -->
<div class="card glass-panel p-6">
<h2 class="text-lg font-semibold mb-4">Connected Devices</h2>
{{range .Devices}}
<div class="flex items-center gap-3 py-2">
{{svg .Type}}
<span>{{.Name}}</span>
<span class="ml-auto text-sm {{if eq .Status "online"}}text-secondary{{end}}">
{{.Status}}
</span>
</div>
{{end}}
</div>
<!-- Danger zone -->
<div class="card border border-red-400/30 bg-red-50 p-6">
<h2 class="text-lg font-semibold text-red-600 mb-4">Danger Zone</h2>
<p class="text-sm text-red-600 mb-4">Flush all app state — this cannot be undone.</p>
<button onclick="if(confirm('Yakin?')){localStorage.clear();location.reload()}"
class="btn-danger">
Flush All App State
</button>
</div>
</div>
</div>
```
### 2.8 Brief Overlay (partials/brief.html)
```html
<!-- Brief overlay — static design system reference -->
<div x-data="{ open: false }">
<button @click="open = true" class="...">
{{svg "file-question"}}
</button>
<div x-show="open" class="fixed inset-0 z-50">
<div class="absolute inset-0 bg-black/20" @click="open = false"></div>
<div class="absolute right-0 top-0 h-full w-[400px] glass-sidebar p-6 overflow-auto">
<div class="flex items-center justify-between mb-6">
<h2 class="text-lg font-semibold">System Brief</h2>
<button @click="open = false">{{svg "x"}}</button>
</div>
<!-- Static content dari template BriefOverlay.tsx -->
<div class="space-y-6">
<section>
<h3 class="font-medium text-primary mb-2">Color Palette</h3>
<div class="grid grid-cols-2 gap-2">
<div class="h-12 rounded-lg bg-primary"></div>
<div class="h-12 rounded-lg bg-secondary"></div>
</div>
</section>
<section>
<h3 class="font-medium text-primary mb-2">Typography</h3>
<p class="font-inter text-lg">Inter — Interface UI</p>
<p class="font-mono text-sm">JetBrains Mono — Code & Data</p>
</section>
<section>
<h3 class="font-medium text-primary mb-2">Glassmorphism</h3>
<p>backdrop-blur-md + rgba(255,255,255,0.7)</p>
</section>
</div>
</div>
</div>
</div>
```
---
## 3. Alpine.js Components (State Management)
### 3.1 Terminal Tabs
```javascript
// inline dalam terminal.html
function terminalTabs() {
return {
tabs: [{ id: '1', title: 'localhost' }],
activeTab: '1',
addTab() {
const id = String(Date.now());
this.tabs.push({ id, title: `host-${this.tabs.length + 1}` });
this.activeTab = id;
this.$nextTick(() => initTerminal(id));
},
closeTab(id) {
this.tabs = this.tabs.filter(t => t.id !== id);
if (this.activeTab === id) this.activeTab = this.tabs[0]?.id;
},
switchTab(id) {
this.activeTab = id;
this.$nextTick(() => focusTerminal(id));
}
}
}
```
### 3.2 Toast Notifications
```javascript
// inline dalam sftp.html, dashboard.html
function toastManager() {
return {
message: '',
visible: false,
show(msg) {
this.message = msg;
this.visible = true;
setTimeout(() => this.visible = false, 3000);
}
}
}
```
---
## 4. JavaScript Files (Vanilla)
### static/js/clipboard.js
```javascript
function copyToClipboard(text, triggerId) {
navigator.clipboard.writeText(text).then(() => {
// trigger toast via htmx event
document.body.dispatchEvent(new CustomEvent('showToast', {
detail: { message: 'Copied!' }
}));
});
}
```
### static/js/toggles.js
```javascript
function toggleSwitch(el) {
const checked = el.getAttribute('aria-checked') === 'true';
el.setAttribute('aria-checked', !checked);
el.classList.toggle('active');
fetch(`/settings/toggle?key=${el.dataset.key}&val=${!checked}`, {
method: 'POST'
});
}
```
### static/js/utils.js
```javascript
function revealPassphrase(el) {
const span = el.closest('.pass-row').querySelector('.pass-text');
const isHidden = span.dataset.hidden === 'true';
span.textContent = isHidden ? span.dataset.value : '••••••••';
span.dataset.hidden = isHidden ? 'false' : 'true';
}
function strengthClass(len) {
if (len > 12) return 'secure';
if (len > 7) return 'moderate';
return 'weak';
}
```
+558
View File
@@ -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
+9
View File
@@ -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"
+8
View File
@@ -0,0 +1,8 @@
node_modules/
build/
dist/
coverage/
.DS_Store
*.log
.env*
!.env.example
+75
View File
@@ -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.
+20
View File
@@ -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`
+17
View File
@@ -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>
+6
View File
@@ -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"]
}
+35
View File
@@ -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"
}
}
+261
View File
@@ -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>
);
}
+165
View File
@@ -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>
);
}
+467
View File
@@ -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>
);
}
+359
View File
@@ -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>
);
}
+249
View File
@@ -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>
);
}
+389
View File
@@ -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>
);
}
+350
View File
@@ -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>
);
}
+304
View File
@@ -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>
);
}
+136
View File
@@ -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 */
}
+10
View File
@@ -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>,
);
+61
View File
@@ -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';
}
+26
View File
@@ -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
}
}
+22
View File
@@ -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 : {},
},
};
});
+12 -1
View File
@@ -1,4 +1,4 @@
.PHONY: build run test clean lint fmt vet install release help .PHONY: build run test test-short test-coverage clean fmt vet lint install tidy deps verify release help
# Binary name # Binary name
BINARY_NAME=hostkeeper BINARY_NAME=hostkeeper
@@ -37,10 +37,17 @@ test:
test-short: test-short:
$(GOTEST) ./... -v -short $(GOTEST) ./... -v -short
## test-coverage: Run tests with coverage report
test-coverage:
$(GOTEST) ./... -v -coverprofile=coverage.out -covermode=atomic
$(GOCMD) tool cover -html=coverage.out -o coverage.html
@echo "Coverage report generated: coverage.html"
## clean: Remove build artifacts ## clean: Remove build artifacts
clean: clean:
$(GOCLEAN) $(GOCLEAN)
rm -rf $(BUILD_DIR) rm -rf $(BUILD_DIR)
rm -f coverage.out coverage.html
## fmt: Format all Go files ## fmt: Format all Go files
fmt: fmt:
@@ -66,6 +73,10 @@ tidy:
deps: deps:
$(GOCMD) mod download $(GOCMD) mod download
## verify: Verify module dependencies
verify:
$(GOCMD) mod verify
## release: Build for multiple platforms ## release: Build for multiple platforms
release: clean release: clean
mkdir -p $(BUILD_DIR) mkdir -p $(BUILD_DIR)
+172 -36
View File
@@ -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**: 2024-06-22 (Session 2) > **Last Updated**: 2025-01-31 (Phase 3 Testing Complete)
> **Current Status**: Implementation In Progress - Tasks 1-5 Complete > **Current Status**: ✅ MVP Complete — Phase 1 Done, Phase 2 Done, Phase 3 Testing Done
> **Phase**: MVP Development (Phase 1) > **Phase**: Phase 3 (Documentation)
--- ---
@@ -27,11 +27,51 @@
**Task 3**: Configuration management (`pkg/config/config.go`) **Task 3**: Configuration management (`pkg/config/config.go`)
**Task 4**: Error handling framework (`internal/errors/`) + tests passing **Task 4**: Error handling framework (`internal/errors/`) + tests passing
**Task 5**: SSH client (`pkg/ssh/`) + tests passing **Task 5**: SSH client (`pkg/ssh/`) + tests passing
**Task 6**: CLI Framework Setup - Cobra root, version, completion (`cmd/hostkeeper/`)
**Task 7**: Add command (`cmd/hostkeeper/add.go`) - add hosts with flags/interactive + tests
**Task 8**: List command (`cmd/hostkeeper/list.go`) - list/filter/sort hosts + tests
**Bug Fix**: Fixed deadlock in JSON storage (RLock within Lock)
### What Needs to Happen Next ### What's Been Done
🔄 **Task 6**: CLI Framework Setup (Cobra commands in `cmd/hostkeeper/`) **Task 13**: Documentation — README, INSTALLATION, USAGE, ARCHITECTURE
🔄 Build and test core features **Task 14**: Release — CHANGELOG, RELEASE_CHECKLIST, git tag v1.0.0
🔄 Prepare MVP release
**🔥 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 (60100 / 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)
--- ---
@@ -47,12 +87,13 @@
| **Config** | ✅ 100% | Cross-platform config management | | **Config** | ✅ 100% | Cross-platform config management |
| **Errors** | ✅ 100% | AppError + ConnectionError + SSH error handler | | **Errors** | ✅ 100% | AppError + ConnectionError + SSH error handler |
| **SSH Client** | ✅ 100% | Password + key auth, Execute, Connect/Close | | **SSH Client** | ✅ 100% | Password + key auth, Execute, Connect/Close |
| **CLI Commands** | 🔲 0% | User interface commands | | **CLI Framework** | ✅ 100% | Cobra root, version, completion commands |
| **TUI** | 🔲 0% | Terminal user interface | | **CLI Commands** | ✅ 100% | All 11 commands: add, list, connect, edit, delete, export, import, tui, completion, version, help |
| **Testing** | 🔲 0% | Test suite and integration | | **TUI** | ✅ 100% | Bubble Tea TUI with host list navigation |
| **Documentation** | 🔲 0% | Usage guides and API docs | | **Testing** | ✅ 100% | All unit + integration tests passing |
| **Documentation** | ✅ 100% | README, INSTALLATION, USAGE, ARCHITECTURE guides |
### Overall Progress: **~40% Complete** (Tasks 1-5 done) ### Overall Progress: **🎉 100% Complete** (All 14 MVP Tasks Done)
--- ---
@@ -103,25 +144,109 @@
- `pkg/ssh/auth.go` — Password/key/both auth, default key discovery - `pkg/ssh/auth.go` — Password/key/both auth, default key discovery
- `test/ssh/ssh_test.go` — 4 test functions, all passing - `test/ssh/ssh_test.go` — 4 test functions, all passing
#### 🔲 Task 6: CLI Framework Setup #### Task 6: CLI Framework Setup
- **Status**: Not Started - **Status**: ✅ Completed
- **Priority**: CRITICAL - **Priority**: CRITICAL
- **Estimated Time**: 1-2 hours
- **Dependencies**: Task 1 complete
- **Deliverables**: Cobra framework, basic commands - **Deliverables**: Cobra framework, basic commands
- **Files to Create**: - **Files Created**:
- `cmd/hostkeeper/*.go` - `cmd/hostkeeper/main.go` — Entry point with Execute() function
- `cmd/hostkeeper/root.go` — Root command with PersistentPreRunE config init
- `cmd/hostkeeper/completion.go` — Shell completion (bash/zsh/fish/powershell)
- Includes `version` subcommand and `-v/--verbose`, `--debug` flags
#### 🔲 Task 7-14: Remaining Tasks #### Task 7: Add Command
- **Status**: Not Started - **Status**: ✅ Completed (all tests passing)
- **Details**: See `docs/plans/2024-06-22-hostkeeper-implementation.md` - **Priority**: CRITICAL
- **Deliverables**: `add` command for registering hosts
- **Files Created**:
- `cmd/hostkeeper/add.go` — add host with flags/interactive, password/key auth, groups, tags, notes
- `cmd/hostkeeper/add_test.go` — tests for add command (flag parsing, storage integration)
#### ✅ Task 8: List Command
- **Status**: ✅ Completed (all tests passing)
- **Priority**: CRITICAL
- **Deliverables**: `list` command for displaying hosts
- **Files Created**:
- `cmd/hostkeeper/list.go` — list hosts with filter (group/tag), sort, table/JSON/wide output formats
- `cmd/hostkeeper/list_test.go` — tests for list command (filtering, formatting)
#### ✅ Task 9: Connect Host Command
- **Status**: ✅ Completed
- **Priority**: CRITICAL
- **Deliverables**: Connect to saved SSH hosts via native SSH or Go SSH client
- **Files Created**:
- `cmd/hostkeeper/connect.go` — Connect command with native SSH (default) and direct Go SSH (--direct) modes
- `cmd/hostkeeper/connect_test.go` — Tests for command existence, flags, and SSH arg building
#### ✅ Edit Host Command
- **Status**: ✅ Completed
- **Priority**: HIGH
- **Deliverables**: Edit existing SSH host configurations
- **Files Created**:
- `cmd/hostkeeper/edit.go` — Edit command with flag-based and interactive modes
- `cmd/hostkeeper/edit_test.go` — Tests for command existence and flags
#### ✅ Delete Host Command
- **Status**: ✅ Completed
- **Priority**: HIGH
- **Deliverables**: Delete SSH hosts with confirmation prompt
- **Files Created**:
- `cmd/hostkeeper/delete.go` — Delete command with --force flag to skip confirmation
- `cmd/hostkeeper/delete_test.go` — Tests for command existence, alias, and flags
#### ✅ Task 10: Basic TUI Implementation
- **Status**: ✅ Completed
- **Priority**: HIGH
- **Deliverables**: Bubble Tea TUI with host list screen
- **Files Created**:
- `pkg/tui/tui.go` — TUI model with Init/Update/View (Bubble Tea)
- `pkg/tui/host_list.go` — Host list renderer with keyboard navigation
- `pkg/tui/tui_test.go` — Tests for TUI initialization and host loading
- `cmd/hostkeeper/tui.go` — CLI `tui` command
#### ✅ Task 11: Export/Import Commands
- **Status**: ✅ Completed
- **Priority**: HIGH
- **Deliverables**: Export/import hosts, keys, snippets for backup/transfer
- **Files Created**:
- `cmd/hostkeeper/export.go` — Export command with JSON format (default) and include-keys flag
- `cmd/hostkeeper/import.go` — Import command with replace/merge strategies and dry-run preview
- `test/storage/export_import_test.go` — Integration test for export/import round-trip
#### ✅ Task 12: Build and Testing
- **Status**: ✅ Completed
- **Priority**: HIGH
- **Deliverables**: Build system and integration tests
- **Files Created/Modified**:
- `Makefile` — Added test-coverage, verify targets; updated clean to remove coverage files
- `build.sh` — Cross-platform build script with SHA256 checksums
- `test/integration/integration_test.go` — End-to-end workflow tests (add, list, get, update, export/import, delete, config)
#### ✅ Task 13: Documentation
- **Status**: ✅ Completed
- **Priority**: HIGH
- **Deliverables**: README, INSTALLATION, USAGE, ARCHITECTURE guides
- **Files Created/Updated**:
- `README.md` — Full rewrite with features, quick start, commands, tech info
- `docs/INSTALLATION.md` — Cross-platform installation guide
- `docs/USAGE.md` — Detailed command usage with examples
- `docs/ARCHITECTURE.md` — System architecture overview
#### ✅ Task 14: Final Testing and Release
- **Status**: ✅ Completed
- **Priority**: HIGH
- **Deliverables**: Release preparation, CHANGELOG, git tag v1.0.0
- **Files Created**:
- `CHANGELOG.md` — Release changelog
- `RELEASE_CHECKLIST.md` — Pre/post-release checklist
- **Git Tag**: `v1.0.0`
--- ---
## 🗺️ Development Roadmap ## 🗺️ Development Roadmap
### Current Week Focus ### Current Week Focus
**Target**: Complete Tasks 1-6 (Foundation + Core Features) **Target**: Complete Tasks 12+ (Build, Testing, Docs, Release)
### This Sprint ### This Sprint
- [x] Project setup and dependencies - [x] Project setup and dependencies
@@ -129,17 +254,25 @@
- [x] Configuration management - [x] Configuration management
- [x] Error handling framework - [x] Error handling framework
- [x] SSH client implementation - [x] SSH client implementation
- [ ] CLI framework setup - [x] CLI framework setup
- [x] Add host command
- [x] List hosts command
- [x] Connect host command
- [x] Edit host command
- [x] Delete host command
- [x] TUI implementation
- [x] Export/Import commands
- [x] Build system and integration tests
### Next Sprint ### Next Sprint
- [ ] CLI commands (add, list, connect) - [ ] SFTP Performance: caching directory listings, batch directory reads
- [ ] Basic TUI implementation - [ ] SFTP File Transfer: download (remote→local), upload (local→remote)
- [ ] Export/import functionality - [ ] 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
--- ---
@@ -285,7 +418,7 @@ go test ./... -watch
### Current Test Coverage ### Current Test Coverage
- **Target**: 80%+ coverage - **Target**: 80%+ coverage
- **Current**: 0% (no tests yet) - **Current**: ~30% (error handling + SSH client tests passing)
- **Priority**: Write tests first (TDD approach) - **Priority**: Write tests first (TDD approach)
--- ---
@@ -318,15 +451,15 @@ go test ./... -watch
### Additional Documentation ### Additional Documentation
- `README.md` - Project overview and quick start - `README.md` - Project overview and quick start
- `docs/INSTALLATION.md` - Installation guide - `docs/INSTALLATION.md` - Installation guide
- `docs/USAGE.md` - Usage documentation (to be created) - `docs/USAGE.md` - Usage documentation
- `docs/ARCHITECTURE.md` - Detailed architecture (to be created) - `docs/ARCHITECTURE.md` - Detailed architecture
--- ---
## 🎯 Success Criteria ## 🎯 Success Criteria
### MVP Success Metrics ### MVP Success Metrics
- ✅ Can establish SSH connections - ✅ Can establish SSH connections (via native SSH)
- ✅ Can manage multiple hosts - ✅ Can manage multiple hosts
- ✅ Can perform SFTP operations - ✅ Can perform SFTP operations
- ✅ Can export/import credentials - ✅ Can export/import credentials
@@ -334,7 +467,7 @@ go test ./... -watch
- ✅ Secure credential storage - ✅ Secure credential storage
- ✅ User-friendly error messages - ✅ User-friendly error messages
### Current Progress: 0/7 criteria met ### Current Progress: 5/7 criteria met (SFTP + encrypted storage deferred to Phase 2)
--- ---
@@ -490,12 +623,15 @@ cat go.mod
- **Start Date**: 2024-06-22 - **Start Date**: 2024-06-22
- **Planning Complete**: 2024-06-22 ✅ - **Planning Complete**: 2024-06-22 ✅
- **Target MVP**: 2024-07-20 (3-4 weeks) - **Target MVP**: 2024-07-20 (3-4 weeks)
- **Current Phase**: Implementation - **Current Phase**: MVP Release
### Milestone Tracking ### Milestone Tracking
- [~] Milestone 1: Foundation (Tasks 1-6) - Week 1 (Tasks 1-3 done) - [x] Milestone 1: Foundation (Tasks 1-6) - Week 1 ✅ COMPLETE
- [ ] Milestone 2: Core Features (Tasks 7-10) - Week 2-3 - [x] Task 7-9: Add, List, Connect commands ✅ COMPLETE
- [ ] Milestone 3: Polish & Release (Tasks 11-14) - Week 4 - [x] Edit & Delete commands ✅ COMPLETE
- [x] Milestone 2: Core Features (Tasks 7-10) - Week 2-3 ✅ COMPLETE
- [x] Milestone 3: Polish & Release (Tasks 11-14) - Week 4 ✅ COMPLETE
- [x] **🏆 ALL 14 MVP TASKS COMPLETE** 🏆
--- ---
+37
View File
@@ -0,0 +1,37 @@
# Hostkeeper V1 — CLI/TUI
> **Status**: FROZEN — no further development.
> Pembuatan V2 dilakukan di folder `../app/` dan `../mobile/`.
Hostkeeper V1 adalah SSH/SFTP management tool berbasis CLI + TUI (Bubble Tea).
## Quick Start
```bash
cd v1
make build
./hostkeeper tui
```
## Dokumentasi
- [Architecture](docs/ARCHITECTURE.md)
- [Installation](docs/INSTALLATION.md)
- [Usage](docs/USAGE.md)
- [Test Plan](docs/TEST_PLAN.md)
- [Project State](PROJECT_STATE.md)
## Tech Stack
- Go 1.26+
- Cobra (CLI)
- Bubble Tea (TUI)
- golang.org/x/crypto/ssh
## Test
```bash
cd v1
make test
# 105 tests passing
```
+41
View File
@@ -0,0 +1,41 @@
# Release Checklist
## Pre-Release
- [ ] All tests pass: `make test`
- [ ] Test coverage is adequate: `make test-coverage`
- [ ] `go vet` passes: `make vet`
- [ ] Lint passes: `make lint`
- [ ] All platforms build successfully: `./build.sh`
- [ ] `CHANGELOG.md` is up to date
- [ ] Version is updated in source
- [ ] Documentation is current
## Testing
- [ ] Integration tests pass: `go test ./test/integration/`
- [ ] Manual smoke test all commands:
- [ ] `hostkeeper add`
- [ ] `hostkeeper list`
- [ ] `hostkeeper connect`
- [ ] `hostkeeper edit`
- [ ] `hostkeeper delete`
- [ ] `hostkeeper export`
- [ ] `hostkeeper import`
- [ ] `hostkeeper tui`
- [ ] `hostkeeper version`
- [ ] `hostkeeper completion`
## Release
- [ ] Tag the release: `git tag v1.0.0`
- [ ] Push tags: `git push origin --tags`
- [ ] Build release binaries: `./build.sh`
- [ ] Verify checksums in `build/checksums.txt`
- [ ] Create GitHub release with binaries attached
- [ ] Post-release announcement (if applicable)
## Post-Release
- [ ] Update PROJECT_STATE.md
- [ ] Start next milestone planning
Executable
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
# Build script for multiple platforms
set -e
VERSION=${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo "dev")}
BUILD_DIR=${BUILD_DIR:-"build"}
BINARY_NAME="hostkeeper"
echo "Building Hostkeeper v${VERSION}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
rm -rf ${BUILD_DIR}
mkdir -p ${BUILD_DIR}
platforms=(
"linux/amd64"
"linux/arm64"
"linux/arm"
"darwin/amd64"
"darwin/arm64"
"windows/amd64"
)
for platform in "${platforms[@]}"; do
IFS='/' read -r os arch <<< "$platform"
output_name="${BINARY_NAME}-${os}-${arch}"
if [ "$os" = "windows" ]; then
output_name="${output_name}.exe"
fi
echo " Building for ${os}/${arch}..."
GOOS=$os GOARCH=$arch go build \
-ldflags "-X main.version=${VERSION} -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
-o "${BUILD_DIR}/${output_name}" \
./cmd/hostkeeper
if command -v shasum &> /dev/null; then
(cd ${BUILD_DIR} && shasum -a 256 "${output_name}" > "${output_name}.sha256")
fi
done
echo ""
echo "Build complete! Binaries in ${BUILD_DIR}/"
echo ""
echo "Available binaries:"
ls -lh ${BUILD_DIR}/
+295
View File
@@ -0,0 +1,295 @@
package main
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"time"
"github.com/google/uuid"
"github.com/spf13/cobra"
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
)
var (
addHostname string
addPort int
addUser string
addPassword string
addKeyPath string
addAuthType string
addGroup string
addTags []string
addNotes string
)
// addCmd represents the add command
var addCmd = &cobra.Command{
Use: "add [name]",
Short: "Add a new SSH host",
Long: `Add a new SSH host connection to HostKeeper.
You can add hosts using flags for quick addition or interactively.
Examples:
# Add host with password authentication
hostkeeper add myserver --host 192.168.1.10 --user admin --password mypass
# Add host with key authentication
hostkeeper add myserver --host 192.168.1.10 --user admin --key ~/.ssh/id_rsa
# Add host with custom port and group
hostkeeper add myserver --host 192.168.1.10 --port 2222 --user admin --password mypass --group production
# Add host interactively
hostkeeper add`,
Args: cobra.MaximumNArgs(1),
RunE: runAddHost,
}
func init() {
// Flags for add command
addCmd.Flags().StringVar(&addHostname, "host", "", "hostname or IP address")
addCmd.Flags().IntVar(&addPort, "port", 0, "SSH port (default: 22)")
addCmd.Flags().StringVar(&addUser, "user", "", "SSH username")
addCmd.Flags().StringVar(&addPassword, "password", "", "SSH password")
addCmd.Flags().StringVar(&addKeyPath, "key", "", "path to SSH private key")
addCmd.Flags().StringVar(&addAuthType, "auth-type", "", "authentication type: password, key, or both")
addCmd.Flags().StringVar(&addGroup, "group", "", "host group for categorization")
addCmd.Flags().StringSliceVar(&addTags, "tags", nil, "tags for the host (comma-separated)")
addCmd.Flags().StringVar(&addNotes, "notes", "", "notes about this host")
rootCmd.AddCommand(addCmd)
}
func runAddHost(cmd *cobra.Command, args []string) error {
cfg := appCfg
if cfg == nil {
var err error
cfg, err = config.New()
if err != nil {
return fmt.Errorf("failed to initialize config: %w", err)
}
}
// Determine host name
var name string
if len(args) > 0 {
name = args[0]
}
// Check if we should use interactive mode
interactive := name == "" && addHostname == ""
if interactive {
return addHostInteractive(cfg)
}
// Validate required fields
if name == "" {
return fmt.Errorf("host name is required (provide as argument or use interactive mode)")
}
if addHostname == "" {
return fmt.Errorf("hostname is required (--host flag)")
}
if addUser == "" {
return fmt.Errorf("username is required (--user flag)")
}
// Set default port from config
port := addPort
if port == 0 {
port = cfg.GetAppConfig().DefaultPort
}
// Determine auth type
authType := addAuthType
if authType == "" {
if addKeyPath != "" && addPassword != "" {
authType = "both"
} else if addKeyPath != "" {
authType = "key"
} else if addPassword != "" {
authType = "password"
} else {
return fmt.Errorf("authentication is required: provide --password, --key, or both")
}
}
// Read key if provided
keyContent := ""
if addKeyPath != "" {
data, err := os.ReadFile(addKeyPath)
if err != nil {
return fmt.Errorf("failed to read key file: %w", err)
}
keyContent = string(data)
}
// Create host
host := &models.Host{
ID: uuid.New().String(),
Name: name,
Hostname: addHostname,
Port: port,
Username: addUser,
Auth: models.AuthConfig{
Type: authType,
Password: addPassword,
},
Group: addGroup,
Tags: addTags,
Notes: addNotes,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// Store key content in password field if key-only auth (as reference)
// In a full implementation, this would store the key securely
if keyContent != "" {
host.Auth.Password = keyContent // Will be moved to secure storage
}
// Initialize storage
store, err := newStorage(cfg)
if err != nil {
return fmt.Errorf("failed to initialize storage: %w", err)
}
// Save host
ctx := context.Background()
if err := store.SaveHost(ctx, host); err != nil {
return fmt.Errorf("failed to save host: %w", err)
}
fmt.Printf("✓ Host '%s' added successfully\n", name)
fmt.Printf(" Hostname: %s:%d\n", addHostname, port)
fmt.Printf(" User: %s\n", addUser)
fmt.Printf(" Auth: %s\n", authType)
return nil
}
func addHostInteractive(cfg *config.Config) error {
input := bufio.NewReader(os.Stdin)
fmt.Println("╔══════════════════════════════════════╗")
fmt.Println("║ Add New SSH Host ║")
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
name := readLine("Host Name (e.g., myserver): ")
if name == "" {
return fmt.Errorf("host name is required")
}
// Get hostname
hostname := readLine("Hostname or IP (e.g., 192.168.1.10): ")
if hostname == "" {
return fmt.Errorf("hostname is required")
}
// Get port
defaultPort := cfg.GetAppConfig().DefaultPort
portInput := readLine(fmt.Sprintf("Port [%d]: ", defaultPort))
port := defaultPort
if portInput != "" {
fmt.Sscanf(portInput, "%d", &port)
}
// Get username
username := readLine("Username: ")
if username == "" {
return fmt.Errorf("username is required")
}
// Get auth type
authType := readLine("Auth Type (password/key/both) [password]: ")
if authType == "" {
authType = "password"
}
// Get password
var password string
if authType == "password" || authType == "both" {
password = readLine("Password: ")
}
// Get key path
var keyContent string
if authType == "key" || authType == "both" {
keyPath := readLine("Path to private key (~/.ssh/id_rsa): ")
if keyPath != "" {
data, err := os.ReadFile(keyPath)
if err != nil {
return fmt.Errorf("failed to read key file: %w", err)
}
keyContent = string(data)
}
}
// Get group
group := readLine("Group (optional): ")
// Get tags
tagsInput := readLine("Tags (comma-separated, optional): ")
var tags []string
if tagsInput != "" {
tags = strings.Split(tagsInput, ",")
for i, t := range tags {
tags[i] = strings.TrimSpace(t)
}
}
// Get notes
notes := readLine("Notes (optional): ")
// Create host
host := &models.Host{
ID: uuid.New().String(),
Name: name,
Hostname: hostname,
Port: port,
Username: username,
Auth: models.AuthConfig{
Type: authType,
Password: password,
},
Group: group,
Tags: tags,
Notes: notes,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if keyContent != "" {
host.Auth.Password = keyContent
}
// Initialize storage
store, err := newStorage(cfg)
if err != nil {
return fmt.Errorf("failed to initialize storage: %w", err)
}
// Save host
ctx := context.Background()
if err := store.SaveHost(ctx, host); err != nil {
return fmt.Errorf("failed to save host: %w", err)
}
fmt.Println()
fmt.Printf("✓ Host '%s' added successfully!\n", name)
return nil
}
+106
View File
@@ -0,0 +1,106 @@
package main
import (
"testing"
)
func TestAddCommandExists(t *testing.T) {
if addCmd == nil {
t.Fatal("addCmd should not be nil")
}
if addCmd.Use != "add [name]" {
t.Errorf("expected Use 'add [name]', got '%s'", addCmd.Use)
}
if addCmd.Short == "" {
t.Error("Short description should not be empty")
}
}
func TestAddCommandFlags(t *testing.T) {
expectedFlags := []string{"host", "port", "user", "password", "key", "auth-type", "group", "tags", "notes"}
for _, flagName := range expectedFlags {
if addCmd.Flags().Lookup(flagName) == nil {
t.Errorf("flag '%s' should be defined", flagName)
}
}
}
func TestAddCommandValidation(t *testing.T) {
tests := []struct {
name string
args []string
hostFlag string
userFlag string
passFlag string
wantError bool
errContains string
}{
{
name: "missing hostname",
args: []string{"myserver"},
userFlag: "admin",
passFlag: "pass",
wantError: true,
errContains: "hostname is required",
},
{
name: "missing username",
args: []string{"myserver"},
hostFlag: "192.168.1.10",
passFlag: "pass",
wantError: true,
errContains: "username is required",
},
{
name: "missing auth",
args: []string{"myserver"},
hostFlag: "192.168.1.10",
userFlag: "admin",
wantError: true,
errContains: "authentication is required",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Reset flags
addHostname = tt.hostFlag
addUser = tt.userFlag
addPassword = tt.passFlag
addPort = 0
addKeyPath = ""
addAuthType = ""
addGroup = ""
addTags = nil
addNotes = ""
// Set HOME to temp dir to avoid polluting real config
t.Setenv("HOME", "/tmp/hostkeeper-test-nonexistent")
err := runAddHost(addCmd, tt.args)
if tt.wantError && err == nil {
t.Errorf("expected error but got none")
}
if !tt.wantError && err != nil {
t.Errorf("unexpected error: %v", err)
}
if tt.errContains != "" && err != nil {
if !contains(err.Error(), tt.errContains) {
t.Errorf("error should contain '%s', got '%s'", tt.errContains, err.Error())
}
}
})
}
}
func contains(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}

Some files were not shown because too many files have changed in this diff Show More