Files
mesh/server/CLAUDE.md
Gilles Soulier 1d177e96a6 first
2026-01-05 13:20:54 +01:00

263 lines
7.2 KiB
Markdown

# CLAUDE.md — Mesh Server
This file provides server-specific guidance for the Mesh control plane implementation.
## Server Role
The Mesh Server is the **control plane only**. It:
- Authenticates users and agents
- Manages rooms and ACL
- Issues capability tokens (60-180s TTL)
- Provides WebRTC signaling
- Orchestrates P2P sessions (QUIC)
- Sends Gotify notifications
**The server NEVER transports media or heavy data.** This is a fundamental architectural constraint.
## Technology Stack
- **Python 3.12+** (IMPORTANT: Utiliser `python3` pour les commandes, pas `python`)
- **FastAPI** for REST API
- **WebSocket** for real-time events
- **JWT** for authentication
- **SQLAlchemy** for database (SQLite initially, PostgreSQL for production)
- **httpx** for Gotify integration
- **Docker** recommandé pour éviter les problèmes de compatibilité de versions
## Project Structure
```
server/
├── src/
│ ├── main.py # FastAPI app entry point
│ ├── config.py # Configuration management
│ ├── auth/
│ │ ├── jwt.py # JWT token management
│ │ ├── capabilities.py # Capability token generation
│ │ └── models.py # Auth data models
│ ├── rooms/
│ │ ├── manager.py # Room management
│ │ ├── acl.py # Access control lists
│ │ └── models.py # Room data models
│ ├── websocket/
│ │ ├── connection.py # WebSocket connection manager
│ │ ├── events.py # Event handlers
│ │ └── router.py # WebSocket routing
│ ├── signaling/
│ │ ├── webrtc.py # WebRTC signaling
│ │ └── p2p.py # QUIC P2P session orchestration
│ ├── notifications/
│ │ └── gotify.py # Gotify client
│ └── db/
│ ├── models.py # Database models
│ └── session.py # Database session management
├── tests/
├── requirements.txt
├── Dockerfile
└── CLAUDE.md
```
## Development Commands
### Setup Local (avec virtualenv)
```bash
cd server
python3 -m venv venv
source venv/bin/activate # or venv\Scripts\activate on Windows
pip install -r requirements.txt
cp .env.example .env
# Éditer .env avec votre configuration
```
### Setup avec Docker (Recommandé)
```bash
cd server
cp .env.example .env
# Éditer .env avec votre configuration
# Construire l'image
docker build -t mesh-server:dev .
# Lancer le serveur
docker run -d --name mesh-server -p 8000:8000 --env-file .env mesh-server:dev
# Voir les logs
docker logs mesh-server -f
# Arrêter et supprimer
docker rm -f mesh-server
```
### Run Development Server (Local)
```bash
python3 -m uvicorn src.main:app --reload --host 0.0.0.0 --port 8000
```
### Run Tests
```bash
# Tester l'API (avec le serveur lancé)
python3 test_api.py
# Tests unitaires
pytest tests/
```
### Type Checking
```bash
mypy src/
```
## Event Protocol
All WebSocket events follow this structure (see [protocol_events_v_2.md](../protocol_events_v_2.md)):
```json
{
"type": "event.type",
"id": "uuid",
"timestamp": "ISO-8601",
"from": "peer_id|device_id|server",
"to": "peer_id|device_id|room_id|server",
"payload": {}
}
```
## Capability Tokens
Capability tokens are **short-lived JWTs** (60-180s) that authorize specific P2P actions:
```python
{
"sub": "peer_id or device_id",
"room_id": "room_id",
"caps": ["call", "screen", "share:file", "terminal:view"],
"exp": timestamp,
"target_peer_id": "optional",
"max_size": "optional",
"max_rate": "optional"
}
```
**Critical rules**:
- Never accept WebRTC offers without valid capability tokens
- Never create P2P sessions without valid capability tokens
- Validate token expiration on every use
- Terminal control requires explicit `terminal:control` capability
## Security Checklist
- [ ] All WebSocket connections authenticated with JWT
- [ ] Capability tokens have short TTL (60-180s)
- [ ] Room ACL enforced server-side
- [ ] No sensitive data in logs
- [ ] TURN credentials are temporary (when implemented)
- [ ] Rate limiting on auth endpoints
- [ ] Input validation on all endpoints
## Database Schema
Key entities:
- **User**: user_id, username, hashed_password, created_at
- **Device**: device_id, user_id, name, last_seen
- **Room**: room_id, name, owner_user_id, created_at
- **RoomMember**: room_id, user_id, role (owner/member/guest)
- **Session**: session_id, peer_id, device_id, room_id, expires_at
## WebSocket Events to Implement
### System
- `system.hello` (client → server)
- `system.welcome` (server → client)
### Rooms
- `room.join`, `room.joined`
- `room.leave`, `room.left`
- `presence.update`
### Chat
- `chat.message.send`, `chat.message.created`
### WebRTC Signaling
- `rtc.offer`, `rtc.answer`, `rtc.ice`
### P2P Sessions (QUIC)
- `p2p.session.request`, `p2p.session.created`
- `p2p.session.closed`
### Terminal Control
- `terminal.control.take`, `terminal.control.granted`
- `terminal.control.release`
## Gotify Integration
Send notifications for:
- New chat messages (when user offline)
- Missed calls
- Share completed
- Terminal share started
- Agent offline
**Never include secrets in notification text.**
## Error Handling
Return structured errors:
```json
{
"type": "error",
"code": "CAP_EXPIRED",
"message": "Capability token expired"
}
```
Error codes:
- `CAP_REQUIRED`: Missing capability token
- `CAP_EXPIRED`: Token expired
- `CAP_INVALID`: Token invalid or tampered
- `ROOM_NOT_FOUND`: Room doesn't exist
- `ACCESS_DENIED`: User not in room or insufficient permissions
- `P2P_SESSION_DENIED`: P2P session creation failed
- `UNROUTABLE`: Peer not connected
## Testing Strategy
1. **Unit tests**: Individual functions (JWT, capabilities, validation)
2. **Integration tests**: WebSocket event flows
3. **E2E tests**: Complete user journeys (join room, send message, start call)
## Notes sur Python et Dépendances
### Python 3.13 Compatibility
⚠️ **Important**: Les dépendances actuelles (`pydantic==2.5.3` avec `pydantic-core==2.14.6`) ne sont pas compatibles avec Python 3.13.
**Solutions**:
1. **Docker (Recommandé)**: Utiliser l'image Docker qui utilise Python 3.12
2. **Mise à jour**: Upgrader vers `pydantic>=2.10` pour Python 3.13 (nécessite tests de régression)
3. **Downgrade**: Installer Python 3.12 localement
### Dépendances Importantes
- `pydantic[email]==2.5.3` - Inclut `email-validator` pour la validation des emails
- `passlib[bcrypt]==1.7.4` + `bcrypt==4.1.2` - Hash des mots de passe
- `python-jose[cryptography]==3.3.0` + `pyjwt[crypto]==2.8.0` - JWT tokens
- `sqlalchemy==2.0.25` + `alembic==1.13.1` - ORM et migrations
### Commandes Python
Toujours utiliser `python3` explicitement sur les systèmes Unix/Linux:
```bash
python3 -m pip install -r requirements.txt
python3 -m uvicorn src.main:app --reload
python3 test_api.py
```
## Performance Considerations
- Keep WebSocket connections lightweight
- Use connection pooling for database
- Cache room membership lookups
- Implement backpressure for high-frequency events
- Monitor active connections count
---
**Remember**: The server is control plane only. Any attempt to route media or large data through the server violates the architecture.