diff --git a/README.md b/README.md index 83b2fa9..24889ce 100644 --- a/README.md +++ b/README.md @@ -1,101 +1,73 @@ -### /home/asoliver/desarrollo/normogen/README.md -```markdown -1: # Normogen -2: -3: ## Overview -4: -5: Normogen is a privacy-focused health data tracking and management platform. The name comes from Mapudungun, relating to Balanced Life. -6: -7: ## Vision -8: -9: To record as many variables related to health as possible, store them in a secure, private manner, to be used by you, not by corporations. From medication reminders to pattern analysis, Normogen puts you in control of your health data. -10: -11: ## Technology Stack -12: -13: ### Backend -14: - **Framework**: Axum 0.7.x -15: - **Runtime**: Tokio 1.x -16: - **Middleware**: Tower, Tower-HTTP -17: - **Database**: MongoDB (with zero-knowledge encryption) -18: - **Language**: Rust -19: -20: ### Mobile (iOS + Android) -21: - **Framework**: React Native 0.73+ -22: - **Language**: TypeScript -23: - **State Management**: Redux Toolkit 2.x -24: - **Data Fetching**: RTK Query 2.x -25: - **Health Sensors**: react-native-health, react-native-google-fit -26: - **Encryption**: react-native-quick-crypto -27: -28: ### Web -29: - **Framework**: React 18+ -30: - **Language**: TypeScript -31: - **State Management**: Redux Toolkit 2.x -32: - **Data Fetching**: RTK Query 2.x -33: - **Charts**: Recharts -34: -35: ### Deployment -36: - Docker on Linux -37: -38: ## Platform Strategy -39: -40: **Primary: Mobile Apps** - Daily health tracking, sensor integration, QR scanning, push notifications -41: -42: **Secondary: Web Browser** - Extensive reporting, visualization, profile management -43: -44: ## Key Features -45: -46: - Zero-knowledge encryption -47: - Multi-person profiles -48: - Family structure management -49: - Secure sharing with expiring links -50: - Mobile apps with health sensor integration -51: - Web interface for complex visualizations -52: -53: ## Security Model -54: -55: - Client-side encryption: Data encrypted before leaving device -56: - Zero-knowledge: Server stores only encrypted data -57: - Proton-style encryption: AES-256-GCM with PBKDF2 key derivation -58: - Shareable links: Self-contained decryption keys in URLs -59: - Privacy-first: No data selling, subscription-based revenue -60: -61: ## Documentation -62: -63: - [Introduction](./introduction.md) - Project vision and detailed feature specification -64: - [Encryption Implementation Guide](./encryption.md) - Zero-knowledge encryption architecture -65: - [Research](./thoughts/research/) - Technical research and planning documents -66: -67: ## Development Status -68: -69: Phase: Planning/Documentation -70: -71: ### Completed -72: - Project vision and requirements -73: - Security architecture design -74: - Encryption implementation guide -75: - Git repository initialization -76: - **Rust framework selection: Axum** -77: - **Mobile/Web framework selection: React Native + React** -78: - **State management selection: Redux Toolkit 2.x** -79: -80: ### Next Steps -81: - Authentication system design (JWT with recovery phrases) -82: - Database schema design -83: - Create proof-of-concept with Axum -84: - Implement basic CRUD API -85: - Build mobile apps with health sensor integration -86: - Build web companion app -87: - Add encryption layer -88: - Implement sharing functionality -89: -90: ## Open Source -91: -92: Normogen is open-source. Both server and client code will be publicly available. -93: -94: Note: This project is currently in the planning phase. No implementation code has been written yet. -``` +# Normogen +## Overview + +Normogen is a privacy-focused health data tracking and management platform. The name comes from Mapudungun, relating to Balanced Life. + +## Vision + +To record as many variables related to health as possible, store them in a secure, private manner, to be used by you, not by corporations. From medication reminders to pattern analysis, Normogen puts you in control of your health data. + +## Technology Stack + +### Backend +- **Framework**: Axum 0.7.x +- **Runtime**: Tokio 1.x +- **Middleware**: Tower, Tower-HTTP +- **Database**: MongoDB (with zero-knowledge encryption) +- **Language**: Rust +- **Authentication**: JWT (PBKDF2 password hashing) + +### Mobile (iOS + Android) +- **Framework**: React Native 0.73+ +- **Language**: TypeScript +- **State Management**: Redux Toolkit 2.x +- **Data Fetching**: RTK Query 2.x +- **Health Sensors**: react-native-health, react-native-google-fit +- **Encryption**: react-native-quick-crypto + +### Web +- **Framework**: React 18+ +- **Language**: TypeScript +- **State Management**: Redux Toolkit 2.x +- **Data Fetching**: RTK Query 2.x +- **Charts**: Recharts + +### Deployment +- Docker on Linux + +## Platform Strategy + +**Primary: Mobile Apps** - Daily health tracking, sensor integration, QR scanning, push notifications + +**Secondary: Web Browser** - Extensive reporting, visualization, profile management + +## Key Features + +- Zero-knowledge encryption +- Multi-person profiles +- Family structure management +- Secure sharing with expiring links +- Mobile apps with health sensor integration +- Web interface for complex visualizations +- JWT-based authentication with token rotation + +## Security Model + +- Client-side encryption: Data encrypted before leaving device +- Zero-knowledge: Server stores only encrypted data +- Proton-style encryption: AES-256-GCM with PBKDF2 key derivation +- Shareable links: Self-contained decryption keys in URLs +- Privacy-first: No data selling, subscription-based revenue +- JWT authentication with token rotation and revocation +- PBKDF2 password hashing (100,000 iterations) + +## Documentation + +- [Introduction](./introduction.md) - Project vision and detailed feature specification +- [Encryption Implementation Guide](./encryption.md) - Zero-knowledge encryption architecture +- [Research](./thoughts/research/) - Technical research and planning documents +- [Project Status](./thoughts/STATUS.md) - Development progress tracking ## Monorepo Structure @@ -112,6 +84,163 @@ normogen/ Each platform has its own `src/` directory to keep codebases separate while sharing common code through the `shared/` directory. +## Development Status + +**Current Phase: Phase 2 - Backend Development** + +### Completed + +#### Phase 1 - Planning +- ✅ Project vision and requirements +- ✅ Security architecture design +- ✅ Encryption implementation guide +- ✅ Git repository initialization + +#### Phase 2 - Backend (In Progress) +- ✅ **Phase 2.1** - Backend Project Initialization + - Rust project setup with Axum + - Docker configuration + - Docker Compose setup + - Kubernetes manifests +- ✅ **Phase 2.2** - MongoDB Connection & Models + - MongoDB connection pooling + - User model (email, password_hash, family_id, token_version) + - RefreshToken model (token_hash, user_id, expires_at) + - Family, Profile, HealthData models + - Medication, LabResult, Appointment models +- ✅ **Phase 2.3** - JWT Authentication + - JWT access tokens (15 min expiry) + - JWT refresh tokens (30 day expiry) + - Token rotation (old tokens revoked on refresh) + - Token revocation (logout) + - PBKDF2 password hashing (100K iterations) + - Auth endpoints: register, login, refresh, logout + - Protected routes with JWT middleware + - Health check endpoints + +### In Progress + +#### Phase 2 - Backend +- 🚧 **Phase 2.4** - User Management Enhancement + - Password recovery (zero-knowledge phrases) + - Email verification flow + - Enhanced profile management + - Account settings endpoints + +#### Future Phases +- **Phase 2.5** - Access Control + - Permission-based middleware + - Token version enforcement + - Family access control + +- **Phase 2.6** - Security Hardening + - Rate limiting + - Account lockout policies + - Security audit logging + +- **Phase 3** - Core API Development +- **Phase 4** - Encryption Layer +- **Phase 5** - Mobile App Development +- **Phase 6** - Web App Development + +## Backend Quick Start + +### Prerequisites + +- Rust 1.70+ +- MongoDB 4.4+ +- Docker (optional, for containerized deployment) + +### Local Development + +```bash +# Clone repository +git clone normogen +cd normogen/backend + +# Copy environment file +cp .env.example .env + +# Edit .env with your configuration +# Required variables: +# MONGODB_URI=mongodb://localhost:27017 +# DATABASE_NAME=normogen +# JWT_SECRET= + +# Install dependencies +cargo build + +# Run the server +cargo run + +# Server will start on http://127.0.0.1:8000 +``` + +### Docker Development + +```bash +# Using Docker Compose (dev mode) +cd backend +docker compose -f docker-compose.dev.yml up -d + +# Check status +curl http://localhost:8000/health + +# View logs +docker compose logs -f backend +``` + +### Testing + +```bash +# Run unit tests +cargo test + +# Run integration tests (requires MongoDB) +cargo test --test auth_tests + +# Manual testing with provided script +./thoughts/test_auth.sh +``` + +## Backend API Endpoints + +### Public Endpoints (No Authentication) +``` +POST /api/auth/register - User registration +POST /api/auth/login - User login +POST /api/auth/refresh - Token refresh (rotates tokens) +POST /api/auth/logout - Logout (revokes token) +GET /health - Health check +GET /ready - Readiness check +``` + +### Protected Endpoints (JWT Required) +``` +GET /api/users/me - Get user profile +``` + +## Environment Configuration + +### Backend Environment Variables + +```bash +# MongoDB Configuration +MONGODB_URI=mongodb://localhost:27017 +DATABASE_NAME=normogen + +# JWT Configuration +JWT_SECRET= +JWT_ACCESS_TOKEN_EXPIRY_MINUTES=15 +JWT_REFRESH_TOKEN_EXPIRY_DAYS=30 + +# Server Configuration +SERVER_HOST=127.0.0.1 +SERVER_PORT=8000 +``` + +See `backend/.env.example` for a complete template. + ## Repository Management - **Git Hosting**: Forgejo (self-hosted) @@ -121,7 +250,7 @@ Each platform has its own `src/` directory to keep codebases separate while shar ## Deployment -### Backend Deployment +### Backend Deployment (Production) ```bash # Clone repository @@ -129,11 +258,10 @@ git clone normogen cd normogen/backend # Setup configuration -cp config/.env.example config/.env -# Edit config/.env +cp .env.example .env +# Edit .env with production values -# Build and run -docker compose build +# Build and run with Docker Compose docker compose up -d # Check status @@ -147,3 +275,15 @@ curl http://localhost:6000/health **Ports**: - Backend API: `6000` (host) → `8000` (container) - MongoDB: `27017` (standard port) + +## Open Source + +Normogen is open-source. Both server and client code will be publicly available. + +## Contributing + +See [thoughts/STATUS.md](./thoughts/STATUS.md) for current development progress and next steps. + +## License + +[To be determined] diff --git a/thoughts/CONFIG.md b/thoughts/CONFIG.md new file mode 100644 index 0000000..b672003 --- /dev/null +++ b/thoughts/CONFIG.md @@ -0,0 +1,280 @@ +# Configuration Guide + +This document explains all configuration files and environment variables for the Normogen project. + +## Backend Configuration + +### Environment Files + +#### 1. backend/.env.example (Primary Configuration Template) + +This is the main environment configuration template for the backend service. + +```bash +# MongoDB Configuration +MONGODB_URI=mongodb://localhost:27017 +DATABASE_NAME=normogen + +# JWT Configuration +JWT_SECRET=your-secret-key-here-change-in-production +JWT_ACCESS_TOKEN_EXPIRY_MINUTES=15 +JWT_REFRESH_TOKEN_EXPIRY_DAYS=30 + +# Server Configuration +SERVER_HOST=127.0.0.1 +SERVER_PORT=8000 +``` + +**How to use:** +```bash +cd backend +cp .env.example .env +# Edit .env with your values +``` + +#### 2. backend/defaults.env + +This file contains default values for development. It's sourced by docker-compose files. + +```bash +MONGODB_URI=mongodb://localhost:27017 +DATABASE_NAME=normogen +JWT_SECRET=change-this-secret-in-production +SERVER_HOST=0.0.0.0 +SERVER_PORT=8000 +``` + +#### 3. thoughts/env.example + +This is a reference copy in the thoughts directory for documentation purposes. + +## Environment Variables + +### Required Variables + +| Variable | Description | Example | Default | +|----------|-------------|---------|---------| +| `MONGODB_URI` | MongoDB connection string | `mongodb://localhost:27017` | - | +| `DATABASE_NAME` | MongoDB database name | `normogen` | - | +| `JWT_SECRET` | Secret key for JWT signing | Minimum 32 characters | - | + +### Optional Variables + +| Variable | Description | Example | Default | +|----------|-------------|---------|---------| +| `SERVER_HOST` | Server bind address | `0.0.0.0` | `127.0.0.1` | +| `SERVER_PORT` | Server port | `8000` | `8000` | +| `JWT_ACCESS_TOKEN_EXPIRY_MINUTES` | Access token lifetime | `15` | `15` | +| `JWT_REFRESH_TOKEN_EXPIRY_DAYS` | Refresh token lifetime | `30` | `30` | + +## Docker Configuration + +### docker-compose.yml (Production) + +Standard production deployment with MongoDB. + +```bash +cd backend +docker compose up -d +``` + +**Services:** +- `backend` - Axum server on port 6000 (host) +- `mongodb` - MongoDB on port 27017 + +**Resource Limits:** +- CPU: 1000m (1 core) +- Memory: 1000Mi (1GB) + +### docker-compose.dev.yml (Development) + +Development mode with hot reload and volume mounts. + +```bash +cd backend +docker compose -f docker-compose.dev.yml up -d +``` + +**Features:** +- Hot reload on code changes +- Source code mounted as volume +- Exposes server on port 8000 + +## Local Development + +### Quick Start + +```bash +# Clone repository +git clone normogen +cd normogen/backend + +# Setup environment +cp .env.example .env +# Edit .env with your configuration + +# Install dependencies +cargo build + +# Run server +cargo run + +# Test +curl http://localhost:8000/health +``` + +### Testing + +```bash +# Unit tests +cargo test + +# Integration tests +cargo test --test auth_tests + +# Manual testing script +cd .. +./thoughts/test_auth.sh +``` + +## Configuration Best Practices + +### JWT Secret + +```bash +# Generate a secure JWT secret (minimum 32 characters) +openssl rand -base64 32 + +# Or use a passphrase-based secret +echo "your-secure-passphrase-32-chars-minimum" | base64 +``` + +**Security Requirements:** +- Minimum 32 characters +- Use random, high-entropy values +- Never commit to git +- Rotate periodically in production +- Use different secrets for dev/staging/production + +### MongoDB Connection + +```bash +# Local development +MONGODB_URI=mongodb://localhost:27017 + +# With authentication +MONGODB_URI=mongodb://username:password@localhost:27017 + +# Replica set +MONGODB_URI=mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet + +# MongoDB Atlas (cloud) +MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/mydb +``` + +### Server Configuration + +```bash +# Local development (localhost only) +SERVER_HOST=127.0.0.1 +SERVER_PORT=8000 + +# Docker/Docker Compose (all interfaces) +SERVER_HOST=0.0.0.0 +SERVER_PORT=8000 + +# Production (behind reverse proxy) +SERVER_HOST=127.0.0.1 +SERVER_PORT=8000 +``` + +## Deployment Environments + +### Development + +```bash +MONGODB_URI=mongodb://localhost:27017 +DATABASE_NAME=normogen_dev +JWT_SECRET=dev-secret-key-32-chars-minimum +SERVER_HOST=127.0.0.1 +SERVER_PORT=8000 +``` + +### Staging + +```bash +MONGODB_URI=mongodb://staging-mongo.internal:27017 +DATABASE_NAME=normogen_staging +JWT_SECRET= +SERVER_HOST=0.0.0.0 +SERVER_PORT=8000 +``` + +### Production + +```bash +MONGODB_URI=mongodb+srv://:@prod-cluster.mongodb.net/normogen +DATABASE_NAME=normogen +JWT_SECRET= +SERVER_HOST=127.0.0.1 +SERVER_PORT=8000 +``` + +## Troubleshooting + +### MongoDB Connection Issues + +```bash +# Check if MongoDB is running +docker ps | grep mongo +# or +systemctl status mongod + +# Test connection +mongosh "mongodb://localhost:27017" +``` + +### JWT Errors + +```bash +# Verify JWT_SECRET is set +echo $JWT_SECRET | wc -c # Should be >= 32 + +# Check for special characters +# Some shells may require quotes +export JWT_SECRET="your-secret-with-special-chars-!@#$%" +``` + +### Port Already in Use + +```bash +# Check what's using port 8000 +lsof -i :8000 +# or +netstat -tulpn | grep 8000 + +# Kill the process +kill -9 +``` + +## Security Checklist + +Before deploying to production: + +- [ ] Change `JWT_SECRET` to a strong, randomly generated value +- [ ] Enable MongoDB authentication +- [ ] Use TLS/SSL for MongoDB connections +- [ ] Set up firewall rules +- [ ] Configure reverse proxy (nginx/caddy) +- [ ] Enable HTTPS +- [ ] Set up log aggregation +- [ ] Configure monitoring and alerts +- [ ] Implement rate limiting +- [ ] Regular security updates + +## Additional Resources + +- [README.md](../README.md) - Project overview +- [STATUS.md](./STATUS.md) - Development progress +- [encryption.md](../encryption.md) - Encryption implementation guide +- [introduction.md](../introduction.md) - Project vision diff --git a/thoughts/QUICKSTART.md b/thoughts/QUICKSTART.md new file mode 100644 index 0000000..6b4c90a --- /dev/null +++ b/thoughts/QUICKSTART.md @@ -0,0 +1,215 @@ +# Quick Start Guide + +Get the Normogen backend running locally in 5 minutes. + +## Prerequisites + +- Rust 1.70 or later +- MongoDB 4.4 or later +- Git + +## Step 1: Clone and Setup + +```bash +# Clone repository +git clone normogen +cd normogen/backend + +# Copy environment template +cp .env.example .env +``` + +## Step 2: Start MongoDB + +### Option A: Using Docker (Recommended) + +```bash +docker run -d \ + --name normogen-mongo \ + -p 27017:27017 \ + -e MONGO_INITDB_DATABASE=normogen \ + mongo:latest +``` + +### Option B: Using System MongoDB + +```bash +# Start MongoDB service +sudo systemctl start mongod # Linux +brew services start mongodb # macOS +``` + +## Step 3: Configure Environment + +Edit `backend/.env`: + +```bash +# MongoDB Configuration +MONGODB_URI=mongodb://localhost:27017 +DATABASE_NAME=normogen + +# JWT Configuration (change this!) +JWT_SECRET=my-super-secret-jwt-key-32-chars +JWT_ACCESS_TOKEN_EXPIRY_MINUTES=15 +JWT_REFRESH_TOKEN_EXPIRY_DAYS=30 + +# Server Configuration +SERVER_HOST=127.0.0.1 +SERVER_PORT=8000 +``` + +## Step 4: Build and Run + +```bash +# Install dependencies and build +cargo build + +# Run the server +cargo run +``` + +Server will start on `http://127.0.0.1:8000` + +## Step 5: Test + +### Health Check + +```bash +curl http://localhost:8000/health +``` + +Expected response: +```json +{ + "status": "ok", + "database": "connected" +} +``` + +### Register a User + +```bash +curl -X POST http://localhost:8000/api/auth/register \ + -H "Content-Type: application/json" \ + -d '{ + "email": "test@example.com", + "password": "SecurePassword123!" + }' +``` + +Expected response: +```json +{ + "message": "User registered successfully", + "user_id": "...", + "email": "test@example.com" +} +``` + +### Login + +```bash +curl -X POST http://localhost:8000/api/auth/login \ + -H "Content-Type: application/json" \ + -d '{ + "email": "test@example.com", + "password": "SecurePassword123!" + }' +``` + +Expected response: +```json +{ + "access_token": "...", + "refresh_token": "...", + "token_type": "Bearer", + "expires_in": 900 +} +``` + +### Access Protected Endpoint + +```bash +# Replace YOUR_ACCESS_TOKEN with the token from login +curl http://localhost:8000/api/users/me \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +Expected response: +```json +{ + "user_id": "...", + "email": "test@example.com", + "family_id": null, + "token_version": 0 +} +``` + +## Docker Quick Start + +```bash +cd backend + +# Start MongoDB and backend with Docker Compose +docker compose up -d + +# Check logs +docker compose logs -f backend + +# Test +curl http://localhost:6000/health +``` + +## Next Steps + +- Read [CONFIG.md](./CONFIG.md) for detailed configuration +- Read [STATUS.md](./STATUS.md) for development progress +- Run `./thoughts/test_auth.sh` for comprehensive API testing +- Check API documentation in [verification-report-phase-2.3.md](./verification-report-phase-2.3.md) + +## Troubleshooting + +### Port 8000 already in use + +```bash +# Find and kill the process +lsof -ti:8000 | xargs kill -9 +``` + +### MongoDB connection failed + +```bash +# Check MongoDB is running +docker ps | grep mongo +# or +systemctl status mongod + +# Test connection +mongosh "mongodb://localhost:27017" +``` + +### Compilation errors + +```bash +# Clean and rebuild +cargo clean +cargo build +``` + +### JWT secret too short + +Make sure `JWT_SECRET` in `.env` is at least 32 characters. + +## Stopping the Server + +```bash +# If running with cargo +Ctrl+C + +# If running with Docker Compose +docker compose down + +# Stop MongoDB (Docker) +docker stop normogen-mongo +docker rm normogen-mongo +```