Add Dangerous Pi MVP implementation - complete backend and system integration

This commit adds the complete Dangerous Pi web management interface with all MVP features implemented and tested locally.

## New Features

### Backend (Python + FastAPI)
- Complete FastAPI backend with async support
- 40+ API endpoints (Health, PM3, WiFi, Updates, UPS, BLE, Plugins)
- 6 managers: Session, WiFi, Update, UPS, BLE, Plugin
- SQLite database with sessions, config, history, crash reports
- Server-Sent Events (SSE) for real-time notifications
- Mock PM3 worker for development without hardware

### WiFi Manager
- Interface detection (USB vs built-in)
- Network scanning with signal strength
- Mode switching (AP/Client/Dual/Auto/Off)
- Network connection with password support
- Hidden SSID and saved networks support
- Static IP and DHCP configuration
- 10 WiFi API endpoints

### Update Manager
- GitHub releases API integration
- Automatic periodic update checks
- Semantic version comparison
- Update download with progress tracking
- SHA256 checksum verification
- Automatic installation with backup and rollback
- PM3 client rebuild after updates
- 6 Update API endpoints

### UPS Manager
- I2C battery monitoring (MAX17040-compatible)
- Battery percentage, voltage, current tracking
- Power source detection (AC/Battery)
- Safe shutdown triggers at configurable thresholds
- Event callbacks for battery warnings
- SSE and BLE notification integration
- 3 UPS API endpoints

### BLE Manager
- Bluetooth Low Energy notification support
- Auto-detects BLE capability
- Multiple notification types (updates, battery, shutdown, etc.)
- BLE advertising management
- Device connection tracking
- 4 BLE API endpoints

### Plugin Framework
- Dynamic plugin loading/unloading
- Plugin lifecycle management (load, enable, disable, unload)
- Hook system for extensibility
- JSON-based metadata
- Example "Hello World" plugin included
- 7 Plugin API endpoints

### Frontend (Remix.js + React)
- Cyberpunk-themed responsive UI
- Dashboard with system status
- PM3 command interface with history
- Settings page with WiFi and Update management
- Command logs viewer
- Theme toggle (Dark/Light/Auto)
- Server-side rendering (SSR)
- Mobile-first responsive design

### System Integration
- Systemd service with security hardening
- Automated install/uninstall scripts
- Environment configuration template
- Hardware access groups (i2c, bluetooth, gpio, dialout)
- Pi-gen stage 04 integration for OS image building
- Port conflict resolution with ttyd-bash
- I2C interface auto-enable for UPS HAT

### Testing
- test_backend.py - Backend API tests
- test_ups.py - UPS manager tests
- test_ble.py - BLE manager tests
- test_plugins.py - Plugin manager tests
- All tests passing locally

### Documentation
- 12 comprehensive documentation files
- claude.md - AI development guide
- WIFI_MANAGER.md - WiFi management guide
- UPDATE_MANAGER.md - Update system guide
- PORT_CONFLICT.md - Port conflict resolution guide
- MVP_COMPLETE.md - MVP implementation summary
- PROJECT_STATUS.md - Project status and roadmap
- systemd/README.md - Service management docs
- pi-gen integration documentation

## Technical Details
- ~5,000+ lines of backend code
- 11 Python dependencies (smbus2 added for UPS)
- FastAPI with async/await throughout
- Type hints and docstrings on all functions
- RESTful API design with SSE for notifications
- Security hardening (non-root, protected dirs, resource limits)

## Next Steps
- Deploy to Raspberry Pi Zero 2 W hardware
- Test with real Proxmark3 device
- Test UPS HAT integration
- Test BLE on Pi hardware
- Build custom OS image with pi-gen
- Performance optimization for Pi Zero 2 W

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
michael
2025-11-26 08:11:36 -08:00
parent 0a586c5360
commit 1da6730735
68 changed files with 12673 additions and 5 deletions

283
claude.md Normal file
View File

@@ -0,0 +1,283 @@
# 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 + Server-Sent Events (SSE)
### Frontend (Remix or SPA)
- **Location**: `/app/frontend/`
- **Framework**: TBD - Remix (preferred) or minimal SPA
- **Transport**: REST API + SSE for notifications
### 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. **Session Manager** (`managers/session_manager.py`)
- Single active session enforcement
- Takeover mechanism for new sessions
- Idle timeout (default: 5 minutes)
3. **Update Manager** (`managers/update_manager.py`)
- Polls GitHub Releases API
- Downloads and applies updates
- Rebuilds PM3 client after updates
- SSE notifications for update status
4. **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
5. **UPS Manager** (`managers/ups_manager.py`)
- I2C battery monitoring
- Safe shutdown triggers
- Battery percentage reporting
6. **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
## 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 SSE only 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
- Mock PM3 worker for development
- Session manager (single-user with takeover)
- SSE endpoints 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
### 📋 Remaining Features
1. UPS monitoring daemon
2. BLE notification system
3. Plugin framework -- planned appstore + intergration later
4. Create systemd services
5. Update pi-gen stage to install Dangerous Pi
## 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
- SSE 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
## File Structure
```
/home/work/dangerous-pi/
├── 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
│ │ ├── sse/ # Server-Sent Events
│ │ │ └── events.py # SSE endpoints
│ │ ├── workers/ # Background workers
│ │ │ └── pm3_worker.py # PM3 command executor
│ │ ├── managers/ # Business logic
│ │ │ ├── session_manager.py
│ │ │ ├── update_manager.py
│ │ │ ├── wifi_manager.py
│ │ │ ├── ups_manager.py
│ │ │ └── ble_manager.py
│ │ └── models/ # Database models
│ │ └── database.py
│ ├── frontend/ # Web UI (TBD)
│ ├── plugins/ # Optional plugins
│ └── 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**:
- PM3 worker with actual pm3 module integration
- Session manager with proper locking
- SSE 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
- SSE is lighter than WebSockets for one-way notifications
- SQLite is sufficient for single-device deployment
- Keep bundles small for faster load times
- Test thoroughly on actual hardware, not just desktop