Files
VPNTray/CLAUDE.md
2025-09-07 23:33:55 +02:00

313 lines
15 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Common Commands
### Running the Application
- `uv run python main.py` - Start the VPN manager GUI application
- `uv run python main.py &` - Start the application in background for testing
- The application runs as a system tray application and can be minimized to the tray
### Managing Running Instances
- `ps aux | grep "python main.py" | grep -v grep` - Check for running instances
- `pkill -f "uv run python main.py"` - Kill running instances (recommended)
- Note: `KillBash` only kills the shell, not the spawned uv process - use `pkill` instead
### Development Environment
- This project uses `uv` for Python package management
- `uv sync` - Install dependencies from pyproject.toml
- Python 3.13+ required
- Dependencies: PyGObject (GTK3), pystray, Pillow, PyYAML
### Configuration Management
- `python init_config.py` - Initialize configuration directory with examples
- `python data_loader.py --init` - Alternative way to create example files
- Configuration location: `~/.vpntray/customers/`
- Each customer gets their own YAML file (e.g., `customer_name.yaml`)
## Code Architecture
### Core Components
**main.py** - Main GUI application entry point
- `VPNManagerWindow` class: Primary PyGObject/GTK3-based GUI application
- Two-column layout: active customers (left) vs inactive customers (right)
- Features system tray integration using `pystray`
- Uses GNOME-style theming with CSS card styling
- Includes comprehensive logging system with collapsible log view
- HeaderBar for native GNOME look and feel
- Current location tracking and enhanced display with network topology
**models.py** - Type-safe data model definitions using dataclasses and enums
- `ServiceType`: Enum for service types (SSH, Web GUI, RDP, VNC, SMB, Database, FTP)
- `HostType`: Enum for host types (Linux, Windows, Windows Server, Proxmox, ESXi, Router, Switch)
- `VPNType`: Enum for VPN types (OpenVPN, WireGuard, IPSec)
- `Service`: Individual services on hosts with type-safe enums and port numbers
- `Host`: Physical/virtual machines with multiple IP addresses, services, and recursive sub-hosts (VMs)
- `Location`: Customer locations with VPN configurations and host infrastructure
- `CustomerService`: Customer's cloud/web services (O365, CRM, etc.)
- `Customer`: Top-level entities containing services and locations
- Each model includes comprehensive helper methods for common operations
**data_loader.py** - YAML-based data management layer
- `load_customers()`: Loads customer configurations from `~/.vpntray/customers/*.yaml` files
- `save_customer()`: Saves customer data back to YAML files with proper enum serialization
- `initialize_example_customers()`: Creates example configuration files
- Robust parsing with enum conversion, error handling, and graceful fallbacks
- Falls back to demo data if no configuration files exist
- Supports both `.yaml` and `.yml` file extensions
**views/** - High-level UI view management (MVC pattern)
- `active_view.py`: `ActiveView` class for displaying active locations with full interaction
- `inactive_view.py`: `InactiveView` class for search results (inactive locations)
- Clean separation of concerns with dedicated view controllers
- `__init__.py`: View exports for clean imports
**widgets/** - Modular UI components using PyGObject
- `customer_card.py`: `ActiveCustomerCard` and `InactiveCustomerCard` classes
- **Compact tree-like design**: Hierarchical layout with expand/collapse arrows
- **Card styling**: Customer cards contain location subcards with proper visual hierarchy
- **Multi-column layout**: Fixed-width columns for proper alignment (name, IP, actions)
- **Service action icons**: Direct access buttons for SSH, RDP, Web GUI with tooltips
- **Multiple IP support**: Display primary IP with hover tooltip showing all addresses
- Active cards: Full interaction with connection controls and infrastructure details
- Inactive cards: Activation buttons and current location setting
- `location_card.py`: `ActiveLocationCard` and `InactiveLocationCard` classes
- Active cards: Connection controls, deactivation (X button), and infrastructure details
- Inactive cards: Current location setting and activation buttons
- `host_item.py`: `HostItem` class for displaying hosts and their services
- Hierarchical display supporting hypervisors with sub-hosts (VMs)
- Service buttons for direct access to SSH, Web GUI, RDP services
- `__init__.py`: Widget exports for clean imports
**services/** - VPN and credential management (modular architecture)
- `vpn_manager.py`: NetworkManager (nmcli) integration with .ovpn file support
- `passbolt_client.py`: Passbolt CLI client for secure credential management
- `connection_manager.py`: High-level orchestrator combining VPN and credentials
- Support for flexible credential storage (direct username/password or Passbolt UUIDs)
**views/** - Comprehensive logging system
- `log_view.py`: `LogView` class with collapsible interface
- **Command logging**: Real-time capture of nmcli and system command output
- **Color-coded levels**: Info, success, warning, error with visual distinction
- **Auto-scroll**: Automatic scrolling to latest entries with manual override
- **Expandable/collapsible**: Bottom panel that can be hidden to save space
**Configuration Files**
- `init_config.py`: Helper script to initialize user configuration with examples
- `example_customer.yaml`: Complete example showing YAML schema with all features
- User config: `~/.vpntray/customers/*.yaml` - One file per customer
### Key Architecture Patterns
**Hierarchical Data Structure**: Customer → Location → Host → Service
- Customers have cloud services (accessible anywhere) and multiple physical locations
- Each location has VPN configuration, connection state, and host infrastructure
- Hosts can have sub-hosts (VMs under hypervisors) with recursive nesting
- Services represent endpoints (SSH, Web GUI, RDP, etc.) with specific ports
**Location State Management**:
- **Active/Inactive**: Locations can be activated for VPN management
- **Current Location**: User's physical location (separate from VPN connections)
- **Connection State**: VPN connection status independent of location activation
- **Network Topology**: Each location includes internal networks and external endpoints
- **Credential Management**: Flexible credential storage (direct or Passbolt UUID)
- Automatic UI updates based on state changes with immediate feedback
**Two-Column Layout Architecture**:
- **Left column**: Active customers with full location details and infrastructure
- **Right column**: Inactive customers available for activation
- **Compact design**: Tree-like hierarchy with proper indentation and alignment
- **Real-time filtering**: Search affects both columns simultaneously
- **Dynamic reorganization**: Customers move between columns based on location state
**Widget-Based Component System**:
- Modular widget classes handle their own GTK widget creation and event handling
- Callback system for widget-to-main-window communication
- Clear separation between data models and UI representation
- Different widget behavior for active vs inactive states
**Type-Safe Configuration System**:
- Comprehensive enum usage for all categorical data
- YAML-based configuration with robust parsing and validation
- Graceful error handling and fallback mechanisms
- Easy extensibility for new service types, host types, and VPN protocols
### Current Location Tracking
The application tracks two distinct location concepts:
- **Current Location**: Where the user physically is (set via "Set as Current" button)
- **Active Locations**: Locations available for VPN connections
**Enhanced Current Location Display**:
- **Prominent info box** with customer name, location, and VPN type
- **Host count summary** with VM breakdown (e.g., "3 hosts (7 total with VMs)")
- **Collapsible infrastructure section** with detailed host and VM information
- **Network topology display**: Internal networks and external endpoints
- **Visual host type icons** (🐧 Linux, 🪟 Windows, 📦 Proxmox, 🌐 Router, etc.)
- **Hierarchical VM display** with service counts and multiple IP addresses
- **Multi-interface support**: Hosts can have multiple IP addresses (firewalls, routers)
- Users can set current location from inactive location cards without activating VPN
### Search and Discovery Features
**Advanced Search Functionality**:
- Real-time search across customers, locations, hosts, and services
- **Wildcard support**: Type `*` to show all inactive locations
- **Smart filtering**: Search includes IP addresses, service types, and port numbers
- **Context switching**: Empty search shows active view, any text shows search results
- **Auto-clear**: Activating a location automatically clears search and returns to active view
### Data Flow
1. **Initialization**: `data_loader.load_customers()` loads configurations from YAML files in `~/.vpntray/customers/`
2. **UI Setup**: Creates views and widgets using callback architecture
3. **Search/Filter**: Real-time filtering with wildcard support and smart matching
4. **View Management**: `Gtk.Stack` manages smooth transitions between active/inactive views
5. **User Interactions**: Callbacks update dataclass attributes with immediate UI feedback
6. **Persistence**: Changes can be saved back to YAML files using `save_customer()`
7. **State Updates**: Location activation, connection changes, and current location updates
### UI Layout Structure
**Modern Two-Column Design**:
- HeaderBar with title and current location display
- **Enhanced current location info box** with network topology and collapsible infrastructure
- Search entry with real-time filtering across both columns
- **Left column**: Active customers with full interaction (connections, services, infrastructure)
- **Right column**: Inactive customers with activation and current location setting
- **Compact tree-like cards** with customer cards containing location subcards
- **Fixed-width columns**: Proper alignment of host names, IP addresses, and action icons
- **Collapsible log view**: Bottom panel for command output and system logs
- GNOME-style cards with CSS theming, proper spacing, and visual hierarchy
- System tray integration for minimize-to-tray behavior
**Customer Card Features**:
- **Active cards**: Start expanded, show full location details and services
- **Inactive cards**: Start collapsed to save space during search
- **Location count badges**: Show number of locations in parentheses
- **Smooth expand/collapse**: Click arrow buttons to toggle content visibility
### GTK3/PyGObject Specific Features
- **CSS styling**: GNOME-style cards with borders, shadows, and adaptive theming
- **Native widgets**: HeaderBar, SearchEntry, ScrolledWindow, Stack with crossfade transitions
- **Proper GNOME HIG compliance**: Spacing, margins, typography, and layout
- **Button styling**: suggested-action and destructive-action classes for clear visual hierarchy
- **Thread-safe integration**: System tray using GLib.idle_add for thread safety
- **Responsive design**: Proper scrolling and adaptive layouts
### Mock Implementation Status
- Currently a UI mockup with no actual VPN functionality
- All VPN operations (connect, disconnect, routes) are placeholder methods
- Button actions update UI state but don't perform real network operations
- Rich configuration system ready for real VPN client integration
- Comprehensive infrastructure modeling supports complex network topologies
### YAML Configuration Schema
Customer files in `~/.vpntray/customers/` follow this structure:
```yaml
name: Customer Name
# Cloud/web services (always accessible)
services:
- name: Service Name
url: https://service.url
service_type: Service Category
description: Optional description
# Physical locations with VPN and infrastructure
locations:
- name: Location Name
vpn_type: OpenVPN|WireGuard|IPSec
vpn_config: /path/to/config/file
# VPN credentials (three options):
# Option 1: Dictionary with username/password
vpn_credentials:
username: vpnuser
password: password123
# Option 2: Passbolt UUID (for future implementation)
# vpn_credentials: "550e8400-e29b-41d4-a716-446655440000"
# Option 3: Omit or set to null if no credentials needed
# vpn_credentials: null
# Note: active and connected are runtime state (not stored in config)
# Network topology information
external_addresses: [vpn.domain.com, backup.domain.com] # VPN endpoints
networks: [192.168.1.0/24, 10.0.1.0/24] # Internal networks
hosts:
- name: Host Name
ip_addresses: [192.168.1.10, 10.0.1.10] # Multiple interfaces supported
host_type: Linux|Windows|Windows Server|Proxmox|ESXi|Router|Switch
description: Optional description
services:
- name: Service Name
service_type: SSH|Web GUI|RDP|VNC|SMB|Database|FTP
port: Port Number
sub_hosts: # Optional VMs/containers (recursive structure)
- name: VM Name
ip_addresses: [192.168.1.20] # VMs can also have multiple IPs
host_type: Linux|Windows|Windows Server
services: # Same structure as parent host
- name: Service Name
service_type: SSH|Web GUI|RDP
port: Port Number
```
### Future Extensibility
**VPN Integration Ready**:
- Implement actual VPN connection logic in placeholder methods
- Add real-time VPN status monitoring and automatic reconnection
- Support for multiple VPN clients (OpenVPN, WireGuard, IPSec)
- Integration with system network management
**Configuration Management**:
- Import/export functionality for customer configurations
- Configuration validation with detailed error reporting
- Backup and restore capabilities
- Multi-user configuration support
**UI Enhancements**:
- Settings panel for application preferences
- Connection logs and monitoring
- Network diagnostics and troubleshooting tools
- Custom themes and layout preferences
- Notification system for connection status changes
**Advanced Features**:
- Auto-discovery of network services and hosts
- Integration with network monitoring tools
- SSH key management and authentication
- Bookmark system for frequently accessed services
- Connection history and analytics
## Development Notes
**Code Quality**:
- Type hints throughout codebase for better IDE support
- Comprehensive error handling with graceful degradation
- Clean separation of concerns (MVC pattern)
- Extensive use of dataclasses and enums for type safety
**Testing Strategy**:
- Configuration can be tested with example YAML files
- UI components are modular and independently testable
- Mock data system allows UI testing without VPN dependencies
**Performance Considerations**:
- Efficient YAML loading with caching
- Minimal UI updates with smart re-rendering
- Background thread for system tray to prevent UI blocking
- Lazy loading of complex widget hierarchies