# Dangerous Pi - Development Guide for Claude ## Project Overview Dangerous Pi is a modern web-based management interface for the Proxmark3 RFID research tool, designed to run on a Raspberry Pi Zero 2 W. It extends the existing pi-pm3 project with advanced features and a Python/FastAPI backend. ## Architecture ### Backend (Python + FastAPI) - **Location**: `/app/backend/` - **Framework**: FastAPI with async support - **Database**: SQLite (aiosqlite) - **Transport**: REST + WebSocket for real-time events ### Frontend (Remix.js) - **Location**: `/app/frontend/` - **Framework**: Remix v2 (React Router with SSR) - **Styling**: Vanilla CSS (cyberpunk theme, ~15KB) - **Charts**: Victory (cross-platform, mobile-first) - **Transport**: REST API + WebSocket for notifications - **Target Users**: Mobile (primary), Desktop (secondary) ### Key Components 1. **PM3 Worker** (`workers/pm3_worker.py`) - Uses built-in `pm3` Python module from RfidResearchGroup/proxmark3 - API: `pm3.open(device)` and `.cmd(command)` - Handles async command execution - Single-threaded, sequential command processing 2. **PM3 Device Manager** (`managers/pm3_device_manager.py`) - Multi-device support with unique device IDs - Device discovery via pyudev - Per-device worker management - Firmware version tracking 3. **Session Manager** (`managers/session_manager.py`) - Per-device session management - Takeover mechanism for new sessions - Idle timeout (default: 5 minutes) 4. **Update Manager** (`managers/update_manager.py`) - Polls GitHub Releases API - Downloads and applies updates - Rebuilds PM3 client after updates - WebSocket notifications for update status 5. **Service Layer** (`services/`) - **ServiceContainer** - Dependency injection - **PM3Service** - PM3 command execution - **SystemService** - System operations - **WiFiService** - WiFi management - **UpdateService** - Update operations 6. **Wi-Fi Manager** (`managers/wifi_manager.py`) - Detects available interfaces (wlan0, wlan1) - Manages modes: AP, Client, Auto, Dual (client+AP) - Integrates with existing RaspAP setup initially 7. **UPS Manager** (`managers/ups_manager.py`) - Multiple driver support (auto-detection) - PiSugar TCP driver - I2C fuel gauge driver (MAX17040/48) - Safe shutdown triggers - Battery percentage reporting 8. **WebSocket Manager** (`websocket/`) - Real-time event broadcasting - Connection management - Event types: system_stats, pm3_status, ups_battery, etc. 9. **BLE Manager** (`managers/ble_manager.py`) - Uses built-in Pi Zero 2 W Bluetooth - Sends notifications for updates, backups, low battery - Auto-detects BLE capability - **Planned**: Full GATT server for React Native app - **Planned**: Command execution via BLE (offline operation) 10. **Plugin Manager** (`managers/plugin_manager.py`) - Extensible plugin architecture - Remote plugin installation from GitHub releases - Automatic pip dependency management - Hardware access (GPIO, I2C, SPI, serial, camera) - Permission system for user consent - See `.claude/instructions/plugin-architecture.md` for details ## Proxmark3 Python API The RfidResearchGroup/proxmark3 (iceman fork) includes SWIG-based Python bindings: ```python # Standalone mode (for our backend) import pm3 device = pm3.open("/dev/ttyACM0") result = device.cmd("hw status") ``` **Important Notes:** - PM3 does NOT support streaming responses - Most commands complete and return full output - Use REST endpoints for commands - Use WebSocket for backend-to-frontend notifications ## Current Status ### ✅ Completed (MVP Features) - **Backend Foundation** - FastAPI application with async support - SQLite database (sessions, config, crash_reports, command_history) - Health check endpoints - Configuration management - PM3 worker with built-in pm3 module integration (SWIG) - PM3 device manager for multi-device support - Session manager (per-device with takeover) - Service layer (PM3Service, SystemService, WiFiService) - WebSocket for real-time notifications - **WiFi Manager (Full MVP)** - Interface detection (USB vs built-in) - Network scanning with signal strength - Full mode switching (AP/Client/Dual/Auto/Off) - Network connection with password support - Hidden SSID support - Saved networks management - Forget network functionality - Static IP configuration - DHCP management - 10 WiFi API endpoints - **Frontend (Complete)** - Cyberpunk-themed responsive UI - Dashboard with system status - PM3 command interface - Settings with WiFi management - Command logs - Connection dialog with password input - Saved networks UI - Theme toggle (Dark/Light/Auto) ### ✅ Update Manager (Complete) - GitHub releases API integration - Automatic periodic update checks (configurable interval) - Version comparison (semantic versioning) - Update download with progress tracking - Checksum verification (SHA256) - Automatic installation with backup - PM3 client rebuild after updates - Rollback on installation failure - 6 Update API endpoints - Frontend UI with release notes and progress tracking ### 📋 Next Phase Features **Visualization & Guided Workflows (In Planning)** 1. Victory charts integration (cross-platform) 2. PM3 output parsers (text → JSON) 3. Real-time tuning visualizations 4. Guided workflow framework 5. Mobile-optimized touch interactions **Cross-Platform Apps (Planned)** 1. React Native mobile app (iOS/Android) 2. Electron desktop app (Windows/Mac/Linux) 3. Enhanced BLE manager (full feature parity) 4. Shared component library (~90% code reuse) ## Development Guidelines ### Code Style - Use async/await throughout - Type hints on all functions - Docstrings for all modules and classes - Keep functions focused and simple ### API Design - REST for all client-initiated actions - WebSocket for server-initiated notifications - Clear error messages with appropriate status codes - Consistent response format ### Security - Run services as non-root user - Optional authentication (configurable) - Optional HTTPS (self-signed cert) - Input validation on all endpoints - No secrets in code (use environment variables) ### Testing Strategy - Test endpoints with curl before building frontend - Mock PM3 module for testing without hardware - Test on actual Pi Zero 2 W for performance ## Data Visualization (Victory Charts) ### Why Victory? Victory is the **only** major charting library designed for true cross-platform development: - **Web**: Works with Remix/React - **React Native**: `victory-native` with native rendering - **Electron**: Same as web version - **Mobile-First**: Touch gestures, responsive, 44px targets - **Bundle Size**: ~50KB (acceptable with code splitting) ### Parser Layer Architecture PM3 commands return text output. We need parsers to convert to structured data: ```python # app/backend/parsers/pm3_output.py def parse_antenna_tuning(output: str) -> dict: """Parse hw tune output into plottable data.""" # Input: "# LF antenna: 50.00 V @ 125.00 kHz" # Output: {"voltage": 50.0, "frequency": 125.0} def parse_waveform_data(output: str) -> dict: """Parse data samples into array.""" # Output: {"samples": [1, 2, 3, ...], "rate": 48000} def parse_protocol_trace(output: str) -> dict: """Parse hf list output into structured frames.""" # Output: {"frames": [...], "timestamps": [...]} ``` ### Enhanced API Response Format ```python # New response format class CommandWithDataResponse(BaseModel): success: bool output: str # Original text (for compatibility) data: Optional[Dict] = None # Structured data for charts visualization_type: Optional[str] = None # "waveform", "tune", "trace" ``` ### Shared Chart Components Create in `/app/shared/components/charts/` for cross-platform reuse: ```typescript // TuneChart.tsx - Works on Web + React Native + Electron import { VictoryLine, VictoryChart, VictoryAxis } from 'victory' export function TuneChart({ data, title }) { return ( ) } ``` ### Guided Workflow Framework Multi-step wizards for common PM3 operations: ```typescript // Workflow definition const cloneMifareWorkflow = { steps: [ { id: 'tune', component: StepTuneAntenna, validation: () => tuned }, { id: 'read', component: StepReadSource, validation: () => hasData }, { id: 'write', component: StepWriteTarget } ] } ``` ### Testing Strategy - Mock PM3 output for parser testing - Test charts with sample data (no hardware needed) - Verify touch interactions on actual mobile device - Performance testing on Pi Zero 2 W ## File Structure ``` /home/work/dangerous-pi/ ├── .claude/ │ ├── instructions/ # Custom instructions for Claude │ │ └── plugin-architecture.md # Plugin system guide │ └── plans/ # Implementation plans ├── app/ │ ├── backend/ │ │ ├── main.py # FastAPI app entry │ │ ├── config.py # Configuration │ │ ├── api/ # REST endpoints │ │ │ ├── health.py # Health checks │ │ │ ├── pm3.py # Proxmark3 commands │ │ │ ├── system.py # System management │ │ │ └── plugins.py # Plugin management │ │ ├── websocket/ # WebSocket real-time events │ │ │ ├── manager.py # Connection manager │ │ │ ├── routes.py # WebSocket endpoint │ │ │ └── notifications.py # Event broadcasting │ │ ├── services/ # Business logic layer │ │ │ ├── container.py # Dependency injection │ │ │ ├── pm3_service.py # PM3 operations │ │ │ ├── system_service.py │ │ │ └── wifi_service.py │ │ ├── workers/ # Background workers │ │ │ └── pm3_worker.py # PM3 command executor │ │ ├── managers/ # State management │ │ │ ├── pm3_device_manager.py # Multi-device PM3 │ │ │ ├── session_manager.py │ │ │ ├── update_manager.py │ │ │ ├── wifi_manager.py │ │ │ ├── ups_manager.py │ │ │ ├── ups_drivers/ # UPS driver implementations │ │ │ ├── ble_manager.py │ │ │ └── plugin_manager.py # Plugin lifecycle │ │ └── models/ # Database models │ │ └── database.py │ ├── frontend/ # Remix.js web UI │ ├── plugins/ # Installed plugins │ │ └── hello_world/ # Demo plugin │ └── scripts/ # Helper scripts ├── data/ # SQLite database, backups ├── logs/ # Application logs ├── pi-gen/ # Custom OS image builder ├── requirements.txt # Python dependencies └── claude.md # This file ``` ## Integration with Existing pi-pm3 The existing pi-pm3 project provides: - Custom Raspberry Pi OS image (pi-gen based) - RaspAP (PHP-based WiFi management on port 80) - ttyd web terminals (bash on 8000, pm3 on 8080) - PM3 client built and installed Dangerous Pi will: - Keep RaspAP initially, potentially replace later - Replace ttyd terminals with web UI - Add FastAPI backend on port 8000 (conflicts with ttyd-bash) - Update pi-gen stage to install new application ## Next Steps for Implementation 1. **Complete core backend**: ✅ DONE - PM3 worker with SWIG bindings - PM3 device manager for multi-device - Session manager with per-device locking - WebSocket event system for notifications 2. **Add system management**: - Wi-Fi detection and mode switching - Update manager with GitHub integration - UPS monitoring daemon 3. **Build frontend**: - Decide: Remix vs minimal SPA - Dashboard with status indicators - Command interface (simpler than full terminal) - Settings pages 4. **Create installer**: - Update pi-gen stage scripts - Create systemd service units - Handle port conflicts with existing ttyd ## Useful Resources - [Proxmark3 Python API Discussion](https://github.com/RfidResearchGroup/proxmark3/issues/897) - [Python API Bug Fix](https://github.com/RfidResearchGroup/proxmark3/issues/1870) - [RaspAP Documentation](https://docs.raspap.com) - [FastAPI Documentation](https://fastapi.tiangolo.com) ## Environment Variables ```bash # PM3 Configuration PM3_DEVICE=/dev/ttyACM0 PM3_TIMEOUT=30 # Session Configuration SESSION_TIMEOUT=300 # Server Configuration HOST=0.0.0.0 PORT=8000 # Update Configuration GITHUB_REPO=yourusername/dangerous-pi UPDATE_CHECK_INTERVAL=3600 # Wi-Fi Configuration WLAN_INTERFACE=wlan0 USB_WLAN_INTERFACE=wlan1 # UPS Configuration UPS_I2C_ADDRESS=0x36 UPS_CHECK_INTERVAL=60 # BLE Configuration BLE_ENABLED=true BLE_DEVICE_NAME=DangerousPi # Security AUTH_ENABLED=false HTTPS_ENABLED=false ``` ## Common PM3 Commands For testing the PM3 worker: ``` hw version # Get hardware/firmware version hw status # Get hardware status hw tune # Tune antenna hf search # Search for HF tags lf search # Search for LF tags hf mf autopwn # Auto-attack MIFARE Classic ``` ## Notes - Pi Zero 2 W has limited CPU/RAM - optimize for efficiency - WebSocket provides bidirectional real-time communication with better reconnection handling - SQLite is sufficient for single-device deployment - Keep bundles small for faster load times - Test thoroughly on actual hardware, not just desktop - Multi-device PM3 support requires per-device session management