🧙‍♂️ Transform LifeRPG into The Wizard's Grimoire - Production-Ready Application

 Major Features Added:
- Complete magical theming and rebranding from LifeRPG to The Wizard's Grimoire
- Production-grade React frontend with Tailwind CSS v4 and magical aesthetics
- Comprehensive analytics dashboard with Recharts integration (ScryingPortal)
- Push notifications system with PWA service worker support
- Drag & drop functionality using @dnd-kit for habit reordering
- Social features with friends system and leaderboards
- Performance optimization tools and monitoring
- Mobile app enhancement with PWA installation support

🏗️ Technical Infrastructure:
- Advanced service worker with offline support and background sync
- Zustand state management for scalable application state
- Production-ready UI component system with enhanced Button, Card, Input
- Progressive Web App (PWA) with manifest and app installation
- FastAPI backend with comprehensive API endpoints
- Docker containerization and CI/CD pipeline setup

📱 Progressive Web App Features:
- Offline functionality with intelligent caching
- Push notification support for habit reminders
- App installation on mobile and desktop platforms
- Background sync for offline data management
- Performance monitoring and optimization tools

🎨 User Experience:
- Magical wizard/grimoire theming throughout application
- Responsive design optimized for all device sizes
- Drag & drop habit management with smooth animations
- Interactive analytics with multiple chart types
- Social connectivity with friends and competitive features
- Comprehensive notification and performance settings

🔧 Developer Experience:
- Modern development stack with Vite and React
- Comprehensive testing setup and CI/CD pipelines
- Code quality tools with pre-commit hooks
- Docker development environment
- Detailed documentation and implementation guides

This represents a complete transformation from prototype to production-ready application with enterprise-grade features and magical user experience.
This commit is contained in:
TLimoges33
2025-08-30 17:32:42 +00:00
committed by GitHub
parent 00ad1bd8d4
commit 7fe4ae5365
270 changed files with 46366 additions and 7824 deletions
+552
View File
@@ -0,0 +1,552 @@
# LifeRPG API Documentation
This document provides comprehensive documentation for the LifeRPG REST API.
## Base URL
```
http://localhost:8000/api/v1
```
## Authentication
Most endpoints require authentication using a Bearer token in the Authorization header:
```
Authorization: Bearer <your-jwt-token>
```
## Endpoints
### Authentication
#### POST /auth/login
Authenticate a user and return a JWT token.
**Request Body:**
```json
{
"email": "user@example.com",
"password": "password123"
}
```
**Response:**
```json
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"user": {
"id": 1,
"email": "user@example.com",
"display_name": "User Name",
"role": "user"
}
}
```
#### POST /auth/register
Register a new user account.
**Request Body:**
```json
{
"email": "user@example.com",
"password": "password123",
"display_name": "User Name"
}
```
**Response:**
```json
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"user": {
"id": 1,
"email": "user@example.com",
"display_name": "User Name",
"role": "user"
}
}
```
#### GET /me
Get current user information.
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
{
"id": 1,
"email": "user@example.com",
"display_name": "User Name",
"role": "user"
}
```
### Habits
#### GET /habits
Get all habits for the current user.
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
[
{
"id": 1,
"title": "Exercise",
"description": "Daily exercise routine",
"category": "health",
"target_frequency": "daily",
"streak": 5,
"total_completions": 10,
"created_at": "2025-08-29T10:00:00Z",
"updated_at": "2025-08-30T10:00:00Z"
}
]
```
#### POST /habits
Create a new habit.
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"title": "Read Books",
"description": "Read for 30 minutes daily",
"category": "learning",
"target_frequency": "daily"
}
```
**Response:**
```json
{
"id": 2,
"title": "Read Books",
"description": "Read for 30 minutes daily",
"category": "learning",
"target_frequency": "daily",
"streak": 0,
"total_completions": 0,
"created_at": "2025-08-30T10:00:00Z",
"updated_at": "2025-08-30T10:00:00Z"
}
```
#### POST /habits/{habit_id}/complete
Mark a habit as completed for today.
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
{
"success": true,
"message": "Habit completed successfully",
"xp_earned": 20,
"new_streak": 6,
"achievement_unlocked": {
"id": "streak_5",
"title": "Streak Master",
"description": "Complete a habit 5 days in a row"
}
}
```
### Gamification
#### GET /gamification/profile
Get user's gamification profile.
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
{
"level": 5,
"xp": 1250,
"xp_to_next_level": 250,
"total_achievements": 8,
"current_streaks": 3,
"longest_streak": 15
}
```
#### GET /gamification/achievements
Get user's achievements.
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
[
{
"id": "first_habit",
"title": "First Steps",
"description": "Create your first habit",
"icon": "🎯",
"unlocked_at": "2025-08-29T10:00:00Z"
}
]
```
#### GET /gamification/leaderboard
Get the global leaderboard.
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
[
{
"rank": 1,
"user_id": 1,
"display_name": "User One",
"level": 10,
"xp": 5000,
"total_achievements": 25
}
]
```
### Analytics
#### GET /analytics/habits/heatmap
Get habit completion heatmap data.
**Headers:** `Authorization: Bearer <token>`
**Query Parameters:**
- `start_date`: Start date (YYYY-MM-DD)
- `end_date`: End date (YYYY-MM-DD)
**Response:**
```json
{
"2025-08-29": {
"completed": 3,
"total": 5
},
"2025-08-30": {
"completed": 4,
"total": 5
}
}
```
#### GET /analytics/habits/trends
Get habit completion trends over time.
**Headers:** `Authorization: Bearer <token>`
**Query Parameters:**
- `period`: Time period ('week', 'month', 'year')
**Response:**
```json
[
{
"date": "2025-08-29",
"completions": 3,
"total_habits": 5,
"completion_rate": 0.6
}
]
```
### Telemetry
#### POST /telemetry/events
Send telemetry events.
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"events": [
{
"event_type": "habit_completed",
"timestamp": "2025-08-30T10:00:00Z",
"properties": {
"habit_id": 1,
"category": "health"
}
}
]
}
```
**Response:**
```json
{
"success": true,
"events_processed": 1
}
```
#### GET /telemetry/summary
Get telemetry summary (admin only).
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
{
"total_events": 1500,
"events_today": 45,
"active_users": 12,
"top_events": [
{
"event_type": "habit_completed",
"count": 500
}
]
}
```
### Plugins
#### GET /plugins
Get all plugins.
**Headers:** `Authorization: Bearer <token>`
**Query Parameters:**
- `status`: Filter by status ('active', 'disabled', 'pending_review', 'rejected')
**Response:**
```json
[
{
"id": "com.example.myplugin",
"name": "My Custom Plugin",
"version": "1.0.0",
"author": "Plugin Author",
"description": "A custom plugin for LifeRPG",
"status": "active",
"permissions": ["habits:read", "ui:dashboard"],
"created_at": "2025-08-30T10:00:00Z"
}
]
```
#### POST /plugins
Register a new plugin.
**Headers:** `Authorization: Bearer <token>`
**Request:** Multipart form data
- `metadata`: JSON metadata
- `wasm_file`: WASM binary file
**Response:**
```json
{
"id": "com.example.myplugin",
"status": "registered"
}
```
#### PATCH /plugins/{plugin_id}/status
Update plugin status.
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"status": "active"
}
```
**Response:**
```json
{
"id": "com.example.myplugin",
"status": "active"
}
```
#### GET /plugins/extension-points
Get all extension points from loaded plugins.
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
{
"extension_points": {
"dashboard": [
{
"id": "myplugin_widget",
"plugin_id": "com.example.myplugin",
"config": {
"title": "My Widget",
"size": "medium"
}
}
]
}
}
```
## Error Responses
All endpoints may return error responses in the following format:
```json
{
"detail": "Error message describing what went wrong"
}
```
### Common HTTP Status Codes
- `200 OK`: Request successful
- `201 Created`: Resource created successfully
- `400 Bad Request`: Invalid request data
- `401 Unauthorized`: Authentication required or invalid token
- `403 Forbidden`: Insufficient permissions
- `404 Not Found`: Resource not found
- `422 Unprocessable Entity`: Validation error
- `500 Internal Server Error`: Server error
## Rate Limiting
The API implements rate limiting to prevent abuse:
- **Authenticated requests**: 1000 requests per hour per user
- **Unauthenticated requests**: 100 requests per hour per IP
Rate limit headers are included in responses:
- `X-RateLimit-Limit`: Request limit per window
- `X-RateLimit-Remaining`: Requests remaining in current window
- `X-RateLimit-Reset`: Window reset time (Unix timestamp)
## Examples
### Complete Workflow Example
1. **Register a new user:**
```bash
curl -X POST http://localhost:8000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password123","display_name":"Test User"}'
```
2. **Create a habit:**
```bash
curl -X POST http://localhost:8000/api/v1/habits \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"title":"Exercise","description":"Daily workout","category":"health","target_frequency":"daily"}'
```
3. **Complete the habit:**
```bash
curl -X POST http://localhost:8000/api/v1/habits/1/complete \
-H "Authorization: Bearer YOUR_TOKEN"
```
4. **Check your gamification profile:**
```bash
curl -X GET http://localhost:8000/api/v1/gamification/profile \
-H "Authorization: Bearer YOUR_TOKEN"
```
## WebSocket Events (Future)
The API will support real-time updates via WebSocket connections:
- `habit.completed`: When a habit is completed
- `achievement.unlocked`: When an achievement is unlocked
- `level.up`: When user levels up
- `plugin.loaded`: When a plugin is loaded/unloaded
## Plugin API
Plugins have access to a subset of the API through host functions:
### Available Host Functions
- `get_habits()`: Get user's habits
- `create_habit(name)`: Create a new habit
- `register_dashboard_widget(config)`: Register a dashboard widget
- `console_log(message)`: Log a message
- `console_error(message)`: Log an error
### Plugin Permissions
Plugins must request specific permissions:
- `habits:read`: Read habit data
- `habits:write`: Create/modify habits
- `projects:read`: Read project data
- `projects:write`: Create/modify projects
- `ui:dashboard`: Add dashboard widgets
- `ui:settings`: Add settings pages
- `storage:plugin`: Use plugin storage
- `network:same-origin`: Make same-origin requests
- `network:external`: Make external requests
## SDK and Tools
### Frontend SDK
```javascript
import { LifeRPGClient } from '@liferpg/client-sdk';
const client = new LifeRPGClient({
baseURL: 'http://localhost:8000/api/v1',
token: 'your-jwt-token'
});
// Create a habit
const habit = await client.habits.create({
title: 'Exercise',
category: 'health'
});
// Complete a habit
await client.habits.complete(habit.id);
```
### Plugin SDK
```typescript
import { LifeRPG, PluginContext } from '@liferpg/plugin-sdk';
export function initialize(context: PluginContext): void {
// Register a dashboard widget
context.ui.registerDashboardWidget({
id: 'my-widget',
title: 'My Custom Widget',
render: () => '<div>Widget content</div>'
});
}
```
## Support
For API support and questions:
- **Documentation**: https://liferpg.dev/docs
- **GitHub Issues**: https://github.com/TLimoges33/LifeRPG/issues
- **Community Discord**: https://discord.gg/liferpg (placeholder)
## Changelog
### v1.0.0 (2025-08-30)
- Initial API release
- Authentication endpoints
- Habits CRUD operations
- Gamification system
- Analytics endpoints
- Telemetry system
- Plugin system with WASM support
+433
View File
@@ -0,0 +1,433 @@
# LifeRPG Architecture Guide
This document outlines the architecture of the LifeRPG modern application, explaining key design decisions, component interactions, and technical implementation details.
## System Architecture Overview
LifeRPG follows a modern microservices-inspired architecture with clear separation of concerns:
```
┌─────────────────────────────────────────────────────────────────┐
│ Client Applications │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Web Frontend │ │ Mobile App │ │ Public API │ │
│ │ (React/Vite) │ │ (React Native)│ │ Consumers │ │
│ └──────┬───────┘ └───────┬──────┘ └───────┬──────┘ │
└──────────┼──────────────────────┼────────────────────┼──────────┘
│ │ │
▼ ▼ ▼
┌──────────────────────────────────────────────────────────────────┐
│ REST API Gateway │
│ │
│ (FastAPI with JWT auth, rate limiting, CORS) │
└────────────┬───────────────────┬───────────────────┬─────────────┘
│ │ │
▼ ▼ ▼
┌──────────────────┐ ┌────────────────┐ ┌───────────────────────┐
│ Core Services │ │ Integrations │ │ Auxiliary Services │
│ │ │ │ │ │
│ - Auth Service │ │ - Todoist │ │ - Telemetry Service │
│ - Habit Service │ │ - GitHub │ │ - Analytics Service │
│ - User Service │ │ - Google Cal │ │ - Gamification │
│ - Project Service│ │ - Slack │ │ - Notification Service│
└────────┬─────────┘ └───────┬────────┘ └────────┬──────────────┘
│ │ │
▼ ▼ ▼
┌──────────────────────────────────────────────────────────────────┐
│ Data Layer │
│ │
│ ┌──────────────┐ ┌───────────────┐ ┌────────────────────┐ │
│ │ PostgreSQL │ │ Redis Cache & │ │ Background Workers │ │
│ │ (SQLAlchemy)│ │ Queue (RQ) │ │ (Integration Sync) │ │
│ └──────────────┘ └───────────────┘ └────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌──────────────────────────────────────────────────────────────────┐
│ Observability │
│ │
│ ┌──────────────┐ ┌───────────────┐ ┌────────────────────┐ │
│ │ Prometheus │ │ Grafana │ │ Structured Logging │ │
│ │ Metrics │ │ Dashboards │ │ (JSON, Loki) │ │
│ └──────────────┘ └───────────────┘ └────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────┘
```
## Core Components
### 1. Backend API (FastAPI)
The backend uses FastAPI to provide a modern, high-performance API with automatic OpenAPI documentation, data validation, and asynchronous request handling.
**Key Design Patterns:**
- **Repository Pattern**: Separates data access logic from business logic
- **Dependency Injection**: Clean dependency management via FastAPI's dependency system
- **Service Layer**: Business logic encapsulated in service classes
- **Unit of Work**: Transactions and session management
- **CQRS-inspired**: Separation of command and query responsibilities
**Security Features:**
- JWT authentication with proper token rotation
- OAuth2/OIDC integration with PKCE
- 2FA with TOTP
- Rate limiting
- CSRF protection
- Security headers (CSP, HSTS)
**Code Structure:**
```
backend/
├── api/ # API routes and endpoints
│ ├── v1/ # API version 1
│ │ ├── auth.py # Authentication endpoints
│ │ ├── habits.py # Habit management endpoints
│ │ ├── projects.py # Project management endpoints
│ │ ├── analytics.py # Analytics endpoints
│ │ └── ...
├── core/ # Core application components
│ ├── config.py # Application configuration
│ ├── security.py # Security utilities
│ ├── exceptions.py # Custom exceptions
│ └── dependencies.py # FastAPI dependencies
├── db/ # Database components
│ ├── base.py # Base database functionality
│ ├── session.py # Database session management
│ └── repositories/ # Repository implementations
├── models/ # SQLAlchemy models
├── schemas/ # Pydantic schemas
├── services/ # Business logic services
├── utils/ # Utility functions
├── workers/ # Background workers
└── main.py # Application entry point
```
### 2. Frontend (React + Vite)
The frontend is built with React and Vite for a fast, modern web experience with responsive design and component-based architecture.
**Key Design Patterns:**
- **Component Composition**: UI built from reusable components
- **Custom Hooks**: Encapsulating reusable logic
- **Context API**: State management for shared state
- **Suspense & Error Boundaries**: For loading states and error handling
- **React Query**: For data fetching, caching, and synchronization
**Code Structure:**
```
frontend/
├── public/ # Static assets
├── src/
│ ├── components/ # Reusable UI components
│ │ ├── ui/ # Basic UI components (Button, Card, etc.)
│ │ ├── habits/ # Habit-related components
│ │ ├── analytics/ # Analytics components
│ │ └── ...
│ ├── hooks/ # Custom React hooks
│ ├── contexts/ # React context providers
│ ├── pages/ # Page components
│ ├── services/ # API service functions
│ ├── utils/ # Utility functions
│ ├── types/ # TypeScript type definitions
│ ├── App.jsx # Main App component
│ └── main.jsx # Application entry point
├── index.html # HTML template
└── vite.config.js # Vite configuration
```
### 3. Mobile App (React Native / Expo)
The mobile app uses React Native with Expo for cross-platform (iOS/Android) development with a focus on offline-first and sync capabilities.
**Key Features:**
- **Offline-First**: Local SQLite database
- **Background Sync**: Push/pull with conflict resolution
- **Deep Linking**: For OIDC authentication
- **Secure Storage**: For sensitive data (tokens)
- **Push Notifications**: For reminders and updates
**Code Structure:**
```
mobile/
├── app/ # Expo Router screens
├── assets/ # App assets (images, fonts)
├── components/ # Reusable components
├── hooks/ # Custom hooks
├── services/ # API and local services
├── store/ # State management
├── utils/ # Utility functions
├── App.tsx # Main App component
└── app.json # Expo configuration
```
### 4. Data Models
#### Core Entities
- **User**: Authentication and profile information
- **Habit**: Recurring actions to track
- **Project**: Grouping of related habits
- **HabitLog**: Record of habit completions
- **Achievement**: Gamification rewards
#### Entity Relationships
```
User 1──* Project
├───1──* Habit
│ │
│ │
│ └───1──* HabitLog
└───1──* Achievement
└───1──* Integration
└───1──* IntegrationItem
```
### 5. Integration System
The integration system connects with external services like Todoist, GitHub, and Google Calendar using a pluggable adapter pattern.
**Key Components:**
- **Provider Interface**: Common interface for all integrations
- **Adapter Pattern**: Specific implementations for each provider
- **OAuth Flow**: Secure token handling and refresh
- **Webhook Receivers**: For real-time updates
- **Background Sync**: Periodic syncing with rate limiting and backoff
### 6. Gamification Engine
The gamification engine motivates users through RPG-like progression mechanics.
**Key Features:**
- **XP System**: Points for completing habits
- **Leveling**: Progression based on accumulated XP
- **Achievements**: Special rewards for milestones
- **Streaks**: Consecutive completion tracking
- **Leaderboards**: Optional social comparison
**Implementation:**
```python
class GamificationService:
async def award_xp(self, user_id: int, amount: int, source: str) -> dict:
"""Award XP to a user and handle level ups and achievements."""
async def check_achievements(self, user_id: int, action: str, metadata: dict) -> list:
"""Check if an action triggers any achievements."""
async def update_streak(self, user_id: int, habit_id: int) -> dict:
"""Update streak counters for a habit."""
```
## Architectural Decisions
### Database Choice: PostgreSQL (Production) / SQLite (Development)
**Rationale**:
- **PostgreSQL**: Robust, ACID-compliant, supports complex queries and indexes
- **SQLite**: Simple setup for development and testing
- **SQLAlchemy**: ORM abstraction allows for easy switching between databases
### Authentication: JWT + OAuth2/OIDC
**Rationale**:
- **JWT**: Stateless authentication with low overhead
- **OAuth2/OIDC**: Secure delegation, no password storage, multi-provider support
- **PKCE**: Enhanced security for mobile and SPA clients
### Background Processing: Redis + RQ
**Rationale**:
- **Redis**: Fast, reliable queue with persistence options
- **RQ**: Simple Python interface with good monitoring
- **Worker Resilience**: Retries, backoff, and concurrency management
### Caching Strategy: Multi-level
**Rationale**:
- **Browser Cache**: Static assets with appropriate cache headers
- **Redis Cache**: API responses and computation results
- **Memory Cache**: Frequent lookups (e.g., user permissions)
### API Versioning
**Rationale**:
- **URL-based Versioning**: Clear, explicit API versions (e.g., `/api/v1/`)
- **Backwards Compatibility**: Maintain older versions during transitions
- **API Deprecation Policy**: Clear communication about deprecated endpoints
## Performance Considerations
### 1. Database Optimization
- **Indexes**: Strategic indexes on frequently queried fields
- **Connection Pooling**: Reuse database connections
- **Query Optimization**: Minimize N+1 queries using proper joins
- **Pagination**: For large result sets
### 2. Caching Strategy
- **Cache Headers**: HTTP caching for static assets
- **API Response Caching**: Cache common API responses
- **Computed Values**: Cache expensive calculations
### 3. Frontend Performance
- **Code Splitting**: Load only needed code
- **Tree Shaking**: Eliminate unused code
- **Lazy Loading**: Defer loading of non-critical components
- **Image Optimization**: Proper formats and sizes
## Security Architecture
### 1. Authentication & Authorization
- **JWT**: Secure, short-lived tokens
- **Refresh Tokens**: For session persistence
- **RBAC**: Role-based access control
- **2FA**: Additional security layer
### 2. Data Protection
- **HTTPS**: All traffic encrypted
- **Encrypted Storage**: Sensitive data encrypted at rest
- **Input Validation**: Prevent injection attacks
- **Output Encoding**: Prevent XSS
### 3. API Security
- **Rate Limiting**: Prevent abuse
- **CORS**: Restrict origins
- **CSRF Protection**: Prevent cross-site request forgery
- **Security Headers**: CSP, HSTS, etc.
## Observability & Monitoring
### 1. Metrics
- **Application Metrics**: Request rates, error rates, response times
- **Business Metrics**: User activity, habit completions, achievements
- **System Metrics**: CPU, memory, disk usage
### 2. Logging
- **Structured Logging**: JSON format for machine parsing
- **Log Levels**: Error, warning, info, debug
- **Context Enrichment**: User ID, request ID, etc.
### 3. Alerting
- **SLO-based Alerts**: Alert on service level objective violations
- **Error Rate Thresholds**: Alert on elevated error rates
- **Custom Business Alerts**: Unusual patterns in user behavior
## Future Architecture Considerations
### 1. Microservices Evolution
As the system grows, consider splitting into true microservices:
- **Auth Service**: Handle authentication and authorization
- **Habit Service**: Core habit tracking functionality
- **Integration Service**: Manage external integrations
- **Gamification Service**: Handle XP, levels, and achievements
### 2. Event-Driven Architecture
Introduce event sourcing and CQRS for complex domains:
- **Event Bus**: Publish domain events
- **Event Sourcing**: Store state changes as events
- **CQRS**: Separate read and write models
### 3. Serverless Components
For appropriate workloads:
- **API Lambdas**: Serverless API endpoints
- **Event Processors**: Serverless event handlers
- **Scheduled Tasks**: Serverless cron jobs
## Plugin System Design (Planned)
The planned plugin system will allow extending LifeRPG with custom functionality:
### 1. Plugin Architecture
- **WASM-based Sandbox**: Secure execution environment
- **Plugin Manifest**: Metadata, permissions, and dependencies
- **Lifecycle Hooks**: Initialize, execute, and clean up
- **Versioning**: Plugin and API version compatibility
### 2. Extension Points
- **Custom Visualizations**: Add new charts and views
- **Integration Adapters**: Connect to additional services
- **Habit Templates**: Predefined habit configurations
- **Achievement Rules**: Custom achievement conditions
### 3. Security Model
- **Permission System**: Granular permissions for plugins
- **Resource Limits**: Memory, CPU, and network constraints
- **Approval Process**: Optional plugin verification
## Conclusion
The LifeRPG architecture is designed for scalability, maintainability, and security while providing a rich user experience. This guide serves as a living document that will evolve with the project.
---
## Appendix: Technology Stack
### Backend
- **Language**: Python 3.10+
- **Framework**: FastAPI
- **ORM**: SQLAlchemy
- **Migration**: Alembic
- **Authentication**: JWT, OAuth2/OIDC
- **Background Jobs**: Redis + RQ
- **Testing**: Pytest
### Frontend
- **Framework**: React 18+
- **Build Tool**: Vite
- **Styling**: TailwindCSS
- **State Management**: React Context + React Query
- **UI Components**: Custom component library
- **Charts**: Recharts
- **Testing**: Vitest + React Testing Library
### Mobile
- **Framework**: React Native / Expo
- **Navigation**: React Navigation
- **Local Storage**: Expo SQLite
- **Authentication**: react-native-app-auth
- **Secure Storage**: expo-secure-store
- **Background Tasks**: expo-background-fetch
### Infrastructure
- **Database**: PostgreSQL (production), SQLite (development)
- **Caching**: Redis
- **Observability**: Prometheus, Grafana, Loki
- **CI/CD**: GitHub Actions
- **Containerization**: Docker
### Development Tools
- **Linting**: ESLint, Flake8
- **Formatting**: Prettier, Black
- **Documentation**: OpenAPI, MkDocs
- **Dependency Management**: Poetry (Python), npm (JS/TS)
+93
View File
@@ -0,0 +1,93 @@
# LifeRPG Plugin System Implementation
This document details the implementation of the WebAssembly-based plugin system for LifeRPG.
## Overview
The LifeRPG plugin system enables users and developers to extend the functionality of the application through WebAssembly (WASM) plugins. These plugins run in a secure sandbox environment with controlled access to application resources.
## Components Implemented
### Backend Components
1. **Plugin Registry and Management**
- `/workspaces/LifeRPG/modern/backend/plugins.py`: Core plugin system backend with database models, API endpoints, and plugin management logic
- Database models for storing plugin metadata
- API endpoints for plugin CRUD operations
2. **Plugin API Integration**
- Added plugin system initialization to both `app.py` and `demo_app.py`
- Defined permission system for controlled API access
### Frontend Components
1. **Plugin Manager**
- `/workspaces/LifeRPG/modern/frontend/src/plugins/PluginManager.tsx`: React hook for managing plugins on the frontend
- Logic for loading and executing WASM plugins
- Plugin lifecycle management
2. **Plugin Admin UI**
- `/workspaces/LifeRPG/modern/frontend/src/plugins/PluginAdmin.tsx`: User interface for managing plugins
- Installation, enabling/disabling, and uninstallation of plugins
### Plugin SDK
1. **AssemblyScript SDK**
- `/workspaces/LifeRPG/modern/plugin-sdk/`: SDK for plugin developers
- Type definitions and API wrappers for AssemblyScript
- Documentation and examples
2. **Example Plugins**
- `/workspaces/LifeRPG/modern/plugin-examples/pomodoro/`: Example Pomodoro timer plugin
- Demonstrates dashboard widget integration
## Implementation Details
### Plugin Lifecycle
1. **Registration**: Plugins are uploaded through the API with metadata and WASM binary
2. **Validation**: Plugins are validated for compatibility and security
3. **Storage**: Plugin metadata is stored in the database, binaries on the filesystem
4. **Loading**: Active plugins are loaded by the frontend
5. **Execution**: Plugins run in a WASM sandbox with limited capabilities
6. **Unloading**: Plugins can be disabled or uninstalled
### Security Measures
1. **Sandboxing**: WASM provides memory isolation and controlled execution
2. **Permission System**: Plugins must request specific permissions
3. **Resource Limits**: Memory, CPU, and storage usage is limited
4. **Controlled API**: Plugins can only access functionality through the provided API
## Extension Points
The implemented system provides several extension points for plugins:
1. **Dashboard Widgets**: Add custom widgets to the dashboard
2. **Settings Pages**: Add custom settings pages
3. **Menu Items**: Add custom menu entries
4. **Data Processing**: Process data before/after CRUD operations (future)
5. **Custom Reports**: Add custom reports and analytics (future)
## Testing
The implemented plugin system can be tested by:
1. Building and installing the example Pomodoro plugin
2. Verifying that the plugin appears in the Plugin Admin UI
3. Enabling the plugin and checking that its dashboard widget appears
4. Testing the Pomodoro timer functionality
## Future Improvements
1. **Event System**: Implement a proper event system for plugins to react to application events
2. **TypeScript/JavaScript Support**: Add direct support for TypeScript plugins without requiring AssemblyScript
3. **Plugin Marketplace**: Create a central repository for sharing and discovering plugins
4. **Versioning**: Implement more robust version compatibility checking
5. **Migration System**: Allow plugins to migrate their data between versions
## Conclusion
The implemented plugin system provides a secure and flexible way to extend LifeRPG's functionality. The WASM-based approach ensures security while allowing plugins to be written in various languages that compile to WebAssembly.
This implementation completes Milestone 7's plugin system task and provides a foundation for future community contributions to LifeRPG.
+483
View File
@@ -0,0 +1,483 @@
# LifeRPG Plugin System
This document outlines the design and implementation of the LifeRPG plugin system using WebAssembly (WASM) for secure sandboxing.
## Overview
The LifeRPG plugin system enables users and developers to extend the functionality of the application without modifying the core codebase. Plugins run in a secure sandbox environment with controlled access to application resources.
## Design Goals
1. **Security**: Plugins must run in a secure sandbox with explicit permissions
2. **Performance**: Minimal overhead for plugin execution
3. **Simplicity**: Easy to develop and deploy plugins
4. **Portability**: Plugins should work across all platforms (web, mobile, desktop)
5. **Versioning**: Support for plugin versioning and compatibility checking
## Architecture
### High-Level Architecture
```
┌───────────────────────────────────────────────────────────────┐
│ LifeRPG Core │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────┐ │
│ │ Plugin Manager │ │ Plugin Registry │ │ Core API │ │
│ └────────┬────────┘ └───────┬─────────┘ └──────┬──────┘ │
│ │ │ │ │
└───────────┼────────────────────┼────────────────────┼─────────┘
│ │ │
▼ ▼ ▼
┌───────────────────────────────────────────────────────────────┐
│ Plugin Interface │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────┐ │
│ │ Host Functions │ │ Extension Points│ │ Plugin API │ │
│ └─────────────────┘ └─────────────────┘ └─────────────┘ │
│ │
└───────────────────────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌───────────────────────────────────────────────────────────────┐
│ Plugin Sandbox │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────┐ │
│ │ WASM Runtime │ │ Resource Limits │ │ Plugin Code │ │
│ └─────────────────┘ └─────────────────┘ └─────────────┘ │
│ │
└───────────────────────────────────────────────────────────────┘
```
### Key Components
#### 1. Plugin Manager
The Plugin Manager is responsible for:
- Loading and unloading plugins
- Managing plugin lifecycle
- Enforcing permissions and resource limits
- Handling plugin errors and crashes
```typescript
class PluginManager {
// Load a plugin from a WASM binary
async loadPlugin(pluginId: string, wasmBinary: ArrayBuffer): Promise<Plugin>;
// Unload a plugin
async unloadPlugin(pluginId: string): Promise<void>;
// Get a list of loaded plugins
getLoadedPlugins(): Plugin[];
// Enable/disable a plugin
setPluginEnabled(pluginId: string, enabled: boolean): void;
}
```
#### 2. Plugin Registry
The Plugin Registry manages:
- Plugin metadata storage
- Version compatibility checking
- Plugin discovery and marketplace
- User plugin preferences
```typescript
class PluginRegistry {
// Register a new plugin
async registerPlugin(metadata: PluginMetadata, wasmBinary: ArrayBuffer): Promise<string>;
// Update an existing plugin
async updatePlugin(pluginId: string, metadata: PluginMetadata, wasmBinary: ArrayBuffer): Promise<void>;
// Get plugin metadata
getPluginMetadata(pluginId: string): PluginMetadata;
// List available plugins
listAvailablePlugins(filters?: PluginFilters): PluginMetadata[];
// Check if a plugin is compatible with the current app version
isPluginCompatible(pluginId: string): boolean;
}
```
#### 3. Plugin Interface
The Plugin Interface defines:
- Host functions available to plugins
- Extension points where plugins can integrate
- Standard plugin API
```typescript
interface PluginInterface {
// Core APIs available to plugins
core: {
// Data access APIs
data: {
getHabits(): Promise<Habit[]>;
getProjects(): Promise<Project[]>;
// ...etc
};
// UI integration
ui: {
registerView(viewId: string, component: PluginView): void;
registerMenuItem(menuId: string, item: MenuItem): void;
// ...etc
};
// Events
events: {
on(event: string, callback: Function): void;
emit(event: string, data: any): void;
// ...etc
};
};
// Host environment information
environment: {
appVersion: string;
platform: 'web' | 'mobile' | 'desktop';
capabilities: string[];
};
// Utilities
utils: {
logger: Logger;
storage: PluginStorage;
http: HttpClient;
};
}
```
#### 4. WASM Sandbox
The WASM Sandbox provides:
- Secure execution environment
- Memory and CPU limits
- Network access controls
- Storage quotas
```typescript
class WasmSandbox {
// Create a new sandbox with specified limits
constructor(options: SandboxOptions);
// Load WASM binary into the sandbox
async loadWasmModule(binary: ArrayBuffer): Promise<WasmModule>;
// Execute a function in the sandbox
async callFunction(functionName: string, ...args: any[]): Promise<any>;
// Set resource limits
setResourceLimits(limits: ResourceLimits): void;
// Check resource usage
getResourceUsage(): ResourceUsage;
// Terminate sandbox (for runaway plugins)
terminate(): void;
}
```
## Plugin Development
### Plugin Structure
A plugin consists of:
1. WASM binary (compiled from various languages)
2. Manifest file (metadata, permissions, extension points)
3. Optional assets (images, styles, etc.)
```json
// plugin.json manifest example
{
"id": "com.example.myplugin",
"name": "My Custom Plugin",
"version": "1.0.0",
"author": "Example Developer",
"description": "A custom plugin for LifeRPG",
"homepage": "https://example.com/myplugin",
"targetApiVersion": "1.0",
"minAppVersion": "2.0.0",
"permissions": [
"habits:read",
"projects:read",
"ui:dashboard",
"storage:plugin"
],
"extensionPoints": [
"dashboard.widget",
"habit.actions",
"reports.custom"
],
"entryPoint": "initialize",
"resourceLimits": {
"memory": "16MB",
"storage": "5MB",
"cpu": "moderate"
}
}
```
### Supported Languages
Plugins can be developed in any language that compiles to WebAssembly:
1. **TypeScript/JavaScript** (via AssemblyScript)
2. **Rust** (native WASM support)
3. **C/C++** (via Emscripten)
4. **Go** (with WASM target)
The recommended language is TypeScript with AssemblyScript for ease of development and type safety.
### Development Workflow
1. **Setup**: Use the LifeRPG Plugin SDK
```bash
npm install @liferpg/plugin-sdk
```
2. **Develop**: Create your plugin using the plugin template
```typescript
// plugin.ts
import { LifeRPG, PluginContext } from '@liferpg/plugin-sdk';
export function initialize(context: PluginContext): void {
// Register a dashboard widget
context.ui.registerDashboardWidget({
id: 'my-custom-widget',
title: 'My Widget',
size: 'medium',
render: () => {
// Return widget HTML/components
return `<div>My Custom Widget</div>`;
}
});
// Listen for events
context.events.on('habit.completed', (habit) => {
context.logger.info(`Habit completed: ${habit.title}`);
});
}
```
3. **Build**: Compile to WASM
```bash
npm run build
```
4. **Test**: Use the plugin development server
```bash
npm run dev
```
5. **Package**: Create a plugin package
```bash
npm run package
```
6. **Publish**: Submit to the LifeRPG plugin marketplace or distribute directly
## Extension Points
The plugin system offers various extension points where plugins can integrate with the application:
### UI Extension Points
1. **Dashboard Widgets**: Add custom widgets to the dashboard
2. **Habit Views**: Custom views for habits
3. **Project Views**: Custom views for projects
4. **Reports**: Custom reporting and analytics
5. **Settings Pages**: Add custom settings pages
6. **Navigation Items**: Add items to navigation menus
### Data Extension Points
1. **Custom Fields**: Add custom fields to habits, projects, etc.
2. **Data Validators**: Add custom validation rules
3. **Data Processors**: Process data before/after CRUD operations
4. **Exporters/Importers**: Custom data export/import formats
### Logic Extension Points
1. **Achievement Rules**: Define custom achievement conditions
2. **Habit Completion Rules**: Custom rules for habit completion
3. **Scoring Algorithms**: Custom XP calculation
4. **Notification Triggers**: Custom notification conditions
## Security Model
### Permission System
Plugins must request permissions for the resources they need to access:
```
habits:read - Read habit data
habits:write - Create/update habits
projects:read - Read project data
projects:write - Create/update projects
ui:dashboard - Add dashboard widgets
ui:settings - Add settings pages
storage:plugin - Use plugin storage
network:same-origin - Make network requests to same origin
network:external - Make network requests to external domains
```
Permissions are shown to users during plugin installation and updates.
### Sandbox Restrictions
- **Memory**: Limited heap size
- **CPU**: Execution time limits
- **Network**: Controlled via permissions
- **Storage**: Quota-based plugin storage
- **DOM**: No direct DOM access (must use provided APIs)
### Validation and Review
- **Automatic Validation**: Static analysis for security issues
- **Manual Review**: Optional review process for marketplace plugins
- **User Ratings**: Community reviews and ratings
- **Revocation**: Ability to revoke plugins with security issues
## Implementation Plan
### Phase 1: Core Infrastructure
1. Implement basic WASM sandbox
2. Create plugin manager and registry
3. Define plugin interface and host functions
4. Build plugin packaging tools
### Phase 2: Basic Extension Points
1. Implement dashboard widget extension point
2. Add settings page extension point
3. Create custom reporting extension point
4. Build plugin marketplace UI
### Phase 3: Advanced Features
1. Add more extension points
2. Implement comprehensive permission system
3. Add resource monitoring and limits
4. Create plugin developer documentation and examples
## Example Plugins
### 1. Pomodoro Timer
A plugin that adds a Pomodoro timer widget to the dashboard and integrates with habit tracking.
```typescript
// pomodoro-plugin.ts
export function initialize(context: PluginContext): void {
// Add dashboard widget
context.ui.registerDashboardWidget({
id: 'pomodoro-timer',
title: 'Pomodoro Timer',
size: 'medium',
render: () => {
return renderPomodoroTimer();
}
});
// Add settings page
context.ui.registerSettingsPage({
id: 'pomodoro-settings',
title: 'Pomodoro Settings',
render: () => {
return renderPomodoroSettings();
}
});
// When timer completes, offer to mark related habit as complete
context.events.on('pomodoro.complete', async () => {
const habits = await context.data.getHabits({ today: true });
// Show completion dialog
});
}
```
### 2. GitHub Integration
A plugin that connects with GitHub to track coding-related habits and progress.
```typescript
// github-plugin.ts
export function initialize(context: PluginContext): void {
// Add GitHub connection settings
context.ui.registerSettingsPage({
id: 'github-settings',
title: 'GitHub Connection',
render: () => {
return renderGitHubSettings();
}
});
// Add GitHub stats widget
context.ui.registerDashboardWidget({
id: 'github-stats',
title: 'GitHub Activity',
size: 'large',
render: async () => {
const stats = await fetchGitHubStats();
return renderGitHubStatsWidget(stats);
}
});
// Sync GitHub activity daily
context.scheduler.scheduleDaily('github-sync', async () => {
await syncGitHubActivity();
});
}
```
### 3. Custom Data Visualizer
A plugin that provides advanced data visualization for habit tracking.
```typescript
// data-viz-plugin.ts
export function initialize(context: PluginContext): void {
// Register custom report
context.ui.registerReport({
id: 'advanced-visualization',
title: 'Advanced Analytics',
render: async () => {
const habitData = await context.data.getHabitLogs({
timeRange: { from: '30d' }
});
return renderAdvancedVisualization(habitData);
}
});
// Add visualization widget to dashboard
context.ui.registerDashboardWidget({
id: 'viz-summary',
title: 'Progress Visualization',
size: 'large',
render: async () => {
return renderVisualizationSummary();
}
});
}
```
## Conclusion
The LifeRPG plugin system provides a powerful yet secure way to extend the application's functionality. By using WebAssembly for sandboxing, we can offer both security and performance while supporting a wide range of programming languages for plugin development.
This design allows for a rich ecosystem of plugins that can enhance the LifeRPG experience without compromising on security or stability.
---
## Appendix: WebAssembly Resources
- [WebAssembly Official Site](https://webassembly.org/)
- [AssemblyScript](https://www.assemblyscript.org/)
- [Rust and WebAssembly](https://rustwasm.github.io/docs/book/)
- [Emscripten](https://emscripten.org/)
- [WASI: WebAssembly System Interface](https://wasi.dev/)
+431
View File
@@ -0,0 +1,431 @@
# LifeRPG Security Guide
This document outlines the security measures implemented in LifeRPG, vulnerability reporting procedures, and best practices for secure deployment.
## Table of Contents
1. [Security Model](#security-model)
2. [Authentication & Authorization](#authentication--authorization)
3. [Data Protection](#data-protection)
4. [API Security](#api-security)
5. [Dependency Security](#dependency-security)
6. [Plugin Security](#plugin-security)
7. [Vulnerability Reporting](#vulnerability-reporting)
8. [Security Testing](#security-testing)
9. [Deployment Security](#deployment-security)
10. [Compliance & Privacy](#compliance--privacy)
## Security Model
LifeRPG implements a defense-in-depth security model with multiple layers of protection:
### Security Principles
- **Zero Trust**: All requests are authenticated and authorized regardless of source
- **Principle of Least Privilege**: Components only have access to what they need
- **Defense in Depth**: Multiple security controls at different layers
- **Secure by Default**: Security features enabled by default
- **Privacy by Design**: Data minimization and protection built-in
### Threat Model
Key threats addressed:
1. **Unauthorized Access**: Prevented through robust authentication and authorization
2. **Data Exposure**: Mitigated through encryption and access controls
3. **Injection Attacks**: Prevented through input validation and parameterized queries
4. **Cross-Site Scripting (XSS)**: Mitigated through content security policy and output encoding
5. **Cross-Site Request Forgery (CSRF)**: Prevented through anti-CSRF tokens
6. **Denial of Service**: Mitigated through rate limiting and resource controls
7. **Supply Chain Attacks**: Addressed through dependency scanning and SBOM
8. **Plugin Vulnerabilities**: Contained through sandboxing and permission controls
## Authentication & Authorization
### Authentication Methods
LifeRPG supports multiple secure authentication methods:
1. **OAuth2/OIDC**: Integration with identity providers using PKCE
- Google, GitHub, Microsoft, etc.
- Authorization code flow with PKCE for SPAs and mobile
- Optional audience and issuer validation
- RP-initiated logout support
2. **Two-Factor Authentication (2FA)**
- TOTP (Time-based One-Time Password)
- Recovery codes for backup access
- Session management with primary/alt sessions
3. **API Tokens**
- Fine-grained permissions
- Expiring tokens with rotation
- Token revocation support
### Token Security
- **JWT Security**: Short-lived tokens with proper signing
- **Secure Storage**: Tokens stored securely (HTTPOnly, Secure cookies)
- **Token Validation**: Thorough validation of token claims
- **Refresh Token Rotation**: One-time use refresh tokens
### Authorization
- **Role-Based Access Control (RBAC)**: User roles with specific permissions
- **Attribute-Based Access Control (ABAC)**: Fine-grained permissions based on attributes
- **Resource Ownership**: Users can only access their own data
- **Permission Checks**: Consistent permission validation throughout the application
Code example:
```python
# API endpoint with permission check
@router.get("/habits/{habit_id}", response_model=HabitRead)
async def get_habit(
habit_id: int,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
habit = await habit_service.get_habit(db, habit_id)
if not habit:
raise HTTPException(status_code=404, detail="Habit not found")
# Permission check
if habit.user_id != current_user.id and not current_user.has_role("admin"):
raise HTTPException(status_code=403, detail="Not authorized")
return habit
```
## Data Protection
### Data at Rest
- **Database Encryption**: Sensitive fields encrypted in database
- **Secure Storage**: Secure storage options for sensitive user data
- **Encryption Keys**: Proper key management and rotation
### Data in Transit
- **TLS/HTTPS**: All communications encrypted with TLS 1.2+
- **HSTS**: HTTP Strict Transport Security enabled
- **Certificate Management**: Proper certificate validation and pinning
### Data Classification
Data is classified into sensitivity levels with appropriate controls:
1. **Public Data**: Non-sensitive, publicly accessible information
2. **User Data**: Personal data requiring authentication
3. **Sensitive Data**: Requiring additional protection (e.g., OAuth tokens)
4. **System Data**: Configuration and security settings
### Data Minimization
- **Purpose Limitation**: Data collected only for specific purposes
- **Storage Limitation**: Data retained only as long as necessary
- **Data Anonymization**: Personal data anonymized where possible
## API Security
### Input Validation
- **Schema Validation**: All inputs validated against Pydantic schemas
- **Type Checking**: Strong typing throughout the application
- **Sanitization**: Input sanitization for special contexts (e.g., HTML)
```python
# Input validation with Pydantic
class HabitCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
description: Optional[str] = Field(None, max_length=1000)
frequency: str = Field(..., pattern="^(daily|weekly|monthly|custom)$")
xp_reward: int = Field(..., ge=1, le=100)
@validator('title')
def title_must_not_contain_html(cls, v):
if re.search(r'<[^>]*>', v):
raise ValueError('Title must not contain HTML tags')
return v
```
### Request Limiting
- **Rate Limiting**: Per-user and per-IP rate limits
- **Concurrent Request Limiting**: Prevent resource exhaustion
- **Request Size Limiting**: Maximum body size enforced
```python
# Rate limiting middleware
app.add_middleware(
RateLimitMiddleware,
rate=30, # requests
period=60, # seconds
storage=redis_storage,
exclude_endpoints=["/health", "/metrics"],
)
```
### Security Headers
- **Content-Security-Policy (CSP)**: Restricts sources of executable scripts
- **X-Content-Type-Options**: Prevents MIME type sniffing
- **X-Frame-Options**: Prevents clickjacking
- **Referrer-Policy**: Controls referrer information
- **Permissions-Policy**: Restricts browser features
```python
# Security headers middleware
app.add_middleware(
SecurityHeadersMiddleware,
csp="default-src 'self'; script-src 'self'; connect-src 'self';",
hsts=True,
frame_options="DENY",
content_type_options=True,
referrer_policy="same-origin",
permissions_policy="camera=(), microphone=(), geolocation=()",
)
```
### CSRF Protection
- **Double Submit Cookie**: CSRF token validation
- **Same-Site Cookies**: Cookies with SameSite=Lax/Strict
- **Origin Checking**: Validate Origin/Referer headers
## Dependency Security
### Software Bill of Materials (SBOM)
LifeRPG maintains a comprehensive SBOM that:
- Lists all direct and transitive dependencies
- Includes version information and licenses
- Is updated with each release
- Is available in both CycloneDX and SPDX formats
### Dependency Scanning
- **Automated Scanning**: Dependencies scanned for vulnerabilities
- **Regular Updates**: Dependencies kept up-to-date
- **Version Pinning**: Explicit version pinning for all dependencies
- **License Compliance**: Dependency licenses tracked and reviewed
Tools used:
- GitHub Dependabot
- OWASP Dependency Check
- Snyk
### Supply Chain Security
- **Verified Sources**: Dependencies from verified sources
- **Integrity Verification**: Package hashes verified
- **Reproducible Builds**: Deterministic build process
- **Secure CI/CD**: Pipeline security with proper secret management
## Plugin Security
### Sandbox Containment
Plugins run in a WebAssembly sandbox with:
- **Memory Isolation**: Protected memory space
- **CPU Limits**: Execution time and resource limits
- **I/O Restrictions**: Limited access to system resources
- **Network Controls**: Restricted network access
### Permission System
Plugins operate under a strict permission model:
- **Explicit Permissions**: Must request specific permissions
- **User Approval**: Permissions displayed and approved by users
- **Runtime Enforcement**: Permissions enforced during execution
- **Revocation**: Permissions can be revoked at any time
### Plugin Vetting
- **Automated Analysis**: Static and dynamic analysis of plugins
- **Code Review**: Optional review process for marketplace plugins
- **Reputation System**: User ratings and reviews
- **Revocation Mechanism**: Ability to disable malicious plugins
## Vulnerability Reporting
### Responsible Disclosure
We encourage responsible disclosure of security vulnerabilities:
1. **Reporting Channel**: Email security@liferpg.example.com or use our HackerOne page
2. **Encryption**: Use our PGP key for sensitive reports
3. **Response Timeline**: Initial response within 48 hours
4. **Disclosure Policy**: Coordinated disclosure after fixes
5. **Recognition**: Hall of Fame for security researchers
### Bug Bounty Program
LifeRPG offers a bug bounty program with:
- **Scope**: Defined in-scope and out-of-scope targets
- **Rewards**: Based on severity and impact
- **Rules of Engagement**: Clear testing guidelines
- **Safe Harbor**: Protection for good-faith security research
## Security Testing
### Automated Testing
- **SAST (Static Application Security Testing)**: Analyzes code for security issues
- Tools: Bandit, ESLint security plugins, CodeQL
- **DAST (Dynamic Application Security Testing)**: Tests running application
- Tools: OWASP ZAP, Burp Suite
- **Dependency Scanning**: Checks dependencies for vulnerabilities
- Tools: Dependabot, Snyk, OWASP Dependency Check
- **Container Scanning**: Analyzes container images
- Tools: Trivy, Clair
### Manual Testing
- **Penetration Testing**: Regular penetration tests
- **Code Reviews**: Security-focused code reviews
- **Threat Modeling**: Systematic analysis of threats
- **Red Team Exercises**: Simulated attacks to test defenses
### CI/CD Integration
Security testing is integrated into CI/CD pipeline:
```yaml
# Example GitHub Actions workflow
name: Security Checks
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run SAST scan
uses: github/codeql-action/analyze@v2
- name: Run dependency scan
uses: snyk/actions/python@master
- name: Run container scan
uses: aquasecurity/trivy-action@master
with:
image-ref: 'liferpg/api:latest'
- name: Run DAST scan
uses: zaproxy/action-full-scan@v0.3.0
with:
target: 'http://localhost:8080'
```
## Deployment Security
### Secure Configuration
- **Environment Variables**: Sensitive configuration in environment variables
- **Secrets Management**: Secrets stored in vault systems
- **Configuration Validation**: Validation of security settings
- **Default Security**: Secure defaults with explicit opt-out
### Infrastructure Security
- **Container Security**: Minimal base images, non-root users
- **Network Security**: Network segmentation and firewalls
- **Cloud Security**: Follow cloud provider security best practices
- **Access Controls**: Least privilege for infrastructure access
### Monitoring & Logging
- **Security Monitoring**: Detection of unusual patterns
- **Centralized Logging**: Security-relevant events logged
- **Audit Trail**: Actions tracked for accountability
- **Alerting**: Automatic alerts for security events
### Incident Response
- **Response Plan**: Documented incident response procedure
- **Roles & Responsibilities**: Clear ownership during incidents
- **Communication Plan**: Internal and external communication
- **Post-Incident Analysis**: Learning from security incidents
## Compliance & Privacy
### Data Protection
- **GDPR Compliance**: European data protection regulations
- **CCPA Compliance**: California Consumer Privacy Act
- **Data Subject Rights**: Access, rectification, erasure
- **Data Processing Records**: Documentation of data processing
### Privacy Features
- **Privacy Policy**: Clear and comprehensive policy
- **Data Export**: User data export functionality
- **Data Deletion**: Complete account deletion option
- **Cookie Controls**: Minimal and controllable cookie usage
### Audit & Compliance
- **Security Audits**: Regular security assessments
- **Compliance Checks**: Verification of regulatory compliance
- **Documentation**: Comprehensive security documentation
- **Training**: Security awareness training for contributors
---
## Security Checklist
Use this checklist to verify LifeRPG's security implementation:
### Authentication & Authorization
- [ ] OAuth2/OIDC properly implemented with PKCE
- [ ] 2FA with TOTP available
- [ ] JWT tokens properly signed and validated
- [ ] Role-based access control implemented
- [ ] Resource ownership checks in place
### Data Protection
- [ ] Sensitive data encrypted in database
- [ ] TLS 1.2+ enforced for all connections
- [ ] HTTPS-only cookies
- [ ] Clear data retention policies
### API Security
- [ ] Input validation on all endpoints
- [ ] Rate limiting implemented
- [ ] Security headers configured
- [ ] CSRF protection in place
- [ ] Request size limits enforced
### Dependency Security
- [ ] SBOM generated and maintained
- [ ] Dependency scanning in CI/CD
- [ ] Regular dependency updates
- [ ] License compliance verified
### Plugin Security
- [ ] WASM sandbox implemented
- [ ] Plugin permissions system working
- [ ] Resource limits enforced
- [ ] Plugin vetting process documented
### Deployment
- [ ] Secure configuration guide available
- [ ] Container security measures implemented
- [ ] Monitoring and logging in place
- [ ] Incident response plan documented
### Compliance
- [ ] Privacy policy up-to-date
- [ ] Data subject rights implemented
- [ ] Compliance documentation available
- [ ] Security training materials created
+348
View File
@@ -0,0 +1,348 @@
# LifeRPG User Guide
Welcome to LifeRPG! This guide will help you get started with turning your life into an RPG where you level up by building better habits.
## Table of Contents
1. [Getting Started](#getting-started)
2. [Creating Your First Habit](#creating-your-first-habit)
3. [The Gamification System](#the-gamification-system)
4. [Analytics and Insights](#analytics-and-insights)
5. [Plugin System](#plugin-system)
6. [Advanced Features](#advanced-features)
7. [Troubleshooting](#troubleshooting)
## Getting Started
### Creating Your Account
1. **Navigate to LifeRPG**: Open your web browser and go to `http://localhost:5173`
2. **Register**: Click the "Register" button and fill in your details:
- Email address
- Password (minimum 8 characters)
- Display name (how you'll appear in leaderboards)
3. **Login**: After registration, you'll be automatically logged in
### Dashboard Overview
Your main dashboard contains several sections:
- **Overview Tab**: Summary of your progress, gamification stats, and leaderboard
- **Habits Tab**: Manage your daily habits and routines
- **Analytics Tab**: View detailed charts and insights about your progress
- **Leaderboard Tab**: See how you rank against other users
- **Plugins Tab**: Manage and install plugins to extend functionality
- **Settings Tab**: Configure your preferences and account settings
- **Admin Tab**: (Admin users only) System administration tools
## Creating Your First Habit
### Step 1: Navigate to Habits
Click on the "Habits" tab in your dashboard navigation.
### Step 2: Add a New Habit
1. Click the "Add New Habit" button
2. Fill in the habit details:
- **Title**: Give your habit a clear, motivating name (e.g., "Morning Exercise")
- **Description**: Add details about what this habit involves
- **Category**: Choose from categories like Health, Learning, Productivity, etc.
- **Target Frequency**: Select how often you want to do this habit:
- Daily: Every day
- Weekly: A certain number of times per week
- Custom: Set your own schedule
### Step 3: Start Tracking
Once created, your habit will appear in your habits list. You can:
- **Complete Today**: Click the checkmark to mark it as done for today
- **View Streak**: See how many consecutive days you've completed it
- **Edit**: Modify the habit details if needed
- **Delete**: Remove the habit (be careful - this can't be undone!)
### Example Habits to Get Started
Here are some simple habits to help you begin:
1. **Drink 8 Glasses of Water** (Health)
2. **Read for 20 Minutes** (Learning)
3. **Write in Journal** (Personal Development)
4. **Take a 10-Minute Walk** (Health)
5. **Practice Gratitude** (Mindfulness)
## The Gamification System
LifeRPG makes habit building fun by turning it into a game!
### Experience Points (XP)
- **Earn XP**: Complete habits to earn experience points
- **Different Values**: Different habits may give different XP amounts
- **Consistency Bonus**: Maintaining streaks can earn bonus XP
### Levels
- **Level Up**: Accumulate XP to advance to higher levels
- **Visual Progress**: See your progress toward the next level
- **Prestige**: Higher levels show your commitment to self-improvement
### Achievements
Unlock achievements by hitting milestones:
- **First Steps**: Create your first habit
- **Streak Master**: Complete a habit 5 days in a row
- **Habit Hero**: Complete 100 habits total
- **Consistency King**: Maintain 3 active streaks
- **Explorer**: Try habits in 5 different categories
### Streaks
- **Daily Streaks**: Track consecutive days of habit completion
- **Motivation**: Streaks provide powerful motivation to maintain consistency
- **Recovery**: Missing a day breaks your streak, but you can always start again
### Leaderboard
- **Global Ranking**: See how you compare to other LifeRPG users
- **Friendly Competition**: Use rankings as motivation, not pressure
- **Privacy**: Only your display name and stats are shown
## Analytics and Insights
### Habit Heatmap
The heatmap shows your daily habit completion patterns:
- **Green Squares**: Days with high completion rates
- **Light Squares**: Days with some completions
- **Empty Squares**: Days with no completions
- **Patterns**: Identify trends and areas for improvement
### Trends and Charts
- **Completion Rate**: Track your overall habit completion percentage over time
- **Category Analysis**: See which categories you're strongest in
- **Weekly/Monthly Views**: Zoom in or out to see different time periods
- **Goal Tracking**: Monitor progress toward personal goals
### Personal Insights
- **Best Days**: Identify which days of the week you're most successful
- **Difficulty Analysis**: See which habits are challenging and which are easy
- **Time Patterns**: Understand your natural rhythms and energy levels
## Plugin System
### What Are Plugins?
Plugins are extensions that add new features to LifeRPG:
- **Custom Widgets**: Add new dashboard components
- **Data Visualizations**: Create unique charts and displays
- **Integrations**: Connect with other apps and services
- **Automation**: Set up automatic actions based on your habits
### Installing Plugins
1. **Navigate to Plugins Tab**: Click "Plugins" in your dashboard
2. **Browse Available**: See plugins that are available for installation
3. **Review Permissions**: Check what access each plugin requests
4. **Install**: Click "Install" and wait for the plugin to load
5. **Configure**: Adjust plugin settings as needed
### Managing Plugins
- **Enable/Disable**: Turn plugins on or off without uninstalling
- **Update**: Keep plugins current with the latest versions
- **Uninstall**: Remove plugins you no longer need
- **Security**: Only install plugins from trusted sources
### Popular Plugin Types
- **Pomodoro Timer**: Time management and focus tracking
- **Habit Reminders**: Custom notification systems
- **Data Exporters**: Backup your data to external services
- **Social Features**: Share progress with friends
- **Mood Tracking**: Monitor emotional patterns alongside habits
## Advanced Features
### Data Export and Backup
- **Regular Backups**: Export your data regularly to avoid loss
- **Format Options**: Download in JSON, CSV, or other formats
- **Privacy**: Your data always remains under your control
### Telemetry and Privacy
- **Opt-in Telemetry**: Choose whether to share anonymous usage data
- **Privacy First**: Personal data is never shared without permission
- **Transparency**: See exactly what data is collected and why
### Integrations
- **Calendar Sync**: Connect with Google Calendar, Outlook
- **Fitness Trackers**: Import data from fitness devices
- **Note Taking**: Link with apps like Notion, Obsidian
- **Social Media**: Share achievements (optional)
### Customization
- **Themes**: Customize the appearance of your dashboard
- **Notifications**: Set up reminders that work for your schedule
- **Goals**: Set personal targets and milestones
- **Categories**: Create custom habit categories
## Tips for Success
### Starting Small
- **Begin with 1-3 habits**: Don't overwhelm yourself
- **Make them easy**: Start with habits you can do in 2-5 minutes
- **Be consistent**: Daily small actions beat occasional big efforts
### Building Momentum
- **Stack habits**: Link new habits to existing routines
- **Use triggers**: Set up environmental cues for your habits
- **Track immediately**: Log completions as soon as you finish
### Staying Motivated
- **Celebrate wins**: Acknowledge every achievement, no matter how small
- **Learn from setbacks**: Missing days is normal - focus on getting back on track
- **Connect with others**: Use the leaderboard for healthy motivation
- **Review regularly**: Check your analytics to see your progress
### Common Pitfalls to Avoid
- **Being too ambitious**: Start small and build up gradually
- **All-or-nothing thinking**: Partial completion is better than none
- **Comparing to others**: Focus on your own journey and progress
- **Perfectionism**: Aim for consistency, not perfection
## Troubleshooting
### Common Issues
#### I Can't Log In
1. **Check your credentials**: Ensure email and password are correct
2. **Password reset**: Use the "Forgot Password" link if available
3. **Clear browser cache**: Try refreshing or clearing your browser data
4. **Check caps lock**: Passwords are case-sensitive
#### My Habits Aren't Saving
1. **Check internet connection**: Ensure you're online
2. **Refresh the page**: Sometimes a simple refresh helps
3. **Try again later**: The server might be temporarily unavailable
#### Plugins Won't Load
1. **Check permissions**: Ensure the plugin has necessary permissions
2. **Disable and re-enable**: Try toggling the plugin off and on
3. **Check for updates**: Make sure you have the latest version
4. **Contact support**: Report persistent plugin issues
#### Data Seems Wrong
1. **Check timezone settings**: Ensure your timezone is set correctly
2. **Verify dates**: Make sure you're looking at the right time period
3. **Refresh analytics**: Some data may take time to update
### Getting Help
#### In-App Help
- **Tooltips**: Hover over UI elements for quick explanations
- **Help Icons**: Look for "?" icons throughout the interface
- **Settings**: Check the settings page for configuration options
#### Community Support
- **GitHub Issues**: Report bugs and request features
- **Community Discord**: Chat with other users and get help
- **Documentation**: Check the full documentation for detailed guides
#### Contacting Support
If you continue to have issues:
1. **Gather information**: Note what you were doing when the problem occurred
2. **Check browser console**: Look for error messages (F12 in most browsers)
3. **Take screenshots**: Visual information helps diagnose problems
4. **Be specific**: Describe exactly what you expected vs. what happened
## Best Practices
### Data Management
- **Regular exports**: Back up your data monthly
- **Review habits**: Remove or modify habits that no longer serve you
- **Clean up**: Archive completed projects and old habits
### Privacy and Security
- **Strong passwords**: Use unique, complex passwords
- **Regular reviews**: Check which plugins have access to your data
- **Logout**: Always log out on shared computers
### Goal Setting
- **SMART goals**: Make goals Specific, Measurable, Achievable, Relevant, Time-bound
- **Regular review**: Adjust goals as your life changes
- **Celebrate milestones**: Acknowledge progress along the way
## What's Next?
### Advanced Features Coming Soon
- **Team challenges**: Compete with friends and family
- **Advanced analytics**: More detailed insights and predictions
- **AI recommendations**: Personalized habit suggestions
- **Mobile app**: Native iOS and Android applications
### Getting Involved
- **Beta testing**: Try new features before they're released
- **Community contributions**: Share your own plugins and templates
- **Feedback**: Help shape the future of LifeRPG
### Continuous Improvement
LifeRPG is constantly evolving. Check back regularly for:
- **New features**: Enhanced functionality and capabilities
- **Plugin updates**: Improved extensions and new options
- **Community content**: User-generated templates and resources
---
## Quick Reference
### Keyboard Shortcuts
- `Ctrl + N`: Create new habit
- `Ctrl + S`: Save current changes
- `Ctrl + D`: Go to dashboard
- `Space`: Mark habit as complete (when focused)
### Common Actions
- **Complete habit**: Click the checkmark next to any habit
- **View analytics**: Click the "Analytics" tab
- **Install plugin**: Go to Plugins tab → Browse → Install
- **Export data**: Settings → Data Export → Download
### Support Resources
- **Documentation**: `/docs` folder in the project
- **API Reference**: `/docs/API_DOCUMENTATION.md`
- **GitHub**: https://github.com/TLimoges33/LifeRPG
- **Issues**: https://github.com/TLimoges33/LifeRPG/issues
Remember: Building better habits is a journey, not a destination. Be patient with yourself, celebrate small wins, and keep moving forward. LifeRPG is here to make that journey more engaging and rewarding!