# Implementation Plan This document breaks down the MVP implementation into small, incremental tasks. Each task should be independently reviewable and testable. ## Review Process After completing each task: 1. Claude implements the feature 2. Run tests (if applicable) 3. Manually verify the feature works 4. **You commit the changes** (not Claude) 5. **Claude confirms you made the commit before proceeding** 6. Move to next task **Important:** You are responsible for making all git commits. Claude will remind you to commit after each task and verify the commit was made before continuing to the next task. ## Phase 1: Project Setup & Foundation ### Project Structure Note Backend (Rust) and frontend (TypeScript with Deno) coexist at repo root: - Root level: `Cargo.toml`, `deno.json`, configs - `src/` - Rust backend source code - `client/` - TypeScript frontend source code This allows managing both from repo root without cd'ing between directories. **Tooling:** - Backend: `cargo run`, `cargo test`, etc. - Frontend: `deno task dev`, `deno task build`, `deno task lint`, `deno fmt` --- ### Task 1.1: Backend Project Initialization **Goal:** Create basic Rust project structure at repo root **Steps:** - [ ] Initialize Cargo project at root: `cargo init --name parco-molo` - [ ] Add initial dependencies to `Cargo.toml`: - axum - tokio (with "full" feature) - tower - serde (with "derive") - serde_json - [ ] Create basic `src/main.rs` with "hello world" axum server - [ ] Verify: `cargo run` starts server on localhost:8080 - [ ] Verify: `curl http://localhost:8080/health` returns 200 OK **Deliverable:** Basic Rust server that responds to health check --- ### Task 1.2: Frontend Project Initialization **Goal:** Create basic TypeScript project structure at repo root using Deno **Steps:** - [ ] Create `deno.json` at root for Deno configuration - [ ] Create `client/` directory for frontend source - [ ] Configure `deno.json` with: - Tasks for dev, build, lint, format - Import map for dependencies - TypeScript compiler options - [ ] Add dependencies via npm specifiers or URLs: - Vite (via npm: for dev server and bundling) - Biome (for linting and formatting) - [ ] Create `biome.json` at root with linting/formatting rules - [ ] Create `client/src/main.ts` with simple console.log - [ ] Create `client/index.html` that loads main.ts - [ ] Add tasks to `deno.json`: `"dev"`, `"build"`, `"lint"`, `"fmt"` - [ ] Verify: `deno task dev` starts dev server from root - [ ] Verify: Browser shows console.log output **Deliverable:** Basic TypeScript project using Deno that builds and runs, managed from repo root **Note:** Using Vite instead of rsbuild as it has better Deno integration. Deno's native TypeScript support eliminates need for separate TypeScript compiler. --- ### Task 1.3: Environment Configuration **Goal:** Set up environment variables and configuration with excellent error messages **Steps:** - [ ] Create `src/config.rs` for configuration loading - [ ] Define `Config` struct with fields: - `database_path: String` - `storage_path: String` - `bind_address: String` - `jwt_secret: String` - [ ] Implement configuration loading using `std::env::var()` directly (no dotenvy) - [ ] For each missing required variable, provide detailed error: - Variable name - Why it's needed - Example value - Where to set it (systemd, shell, docker, etc.) - [ ] Implement default path logic (FHS-compliant vs XDG) for optional paths - [ ] Verify: Server loads config from environment variables - [ ] Verify: Missing `JWT_SECRET` shows: "JWT_SECRET environment variable is required for signing authentication tokens. Generate one with: openssl rand -base64 32. Set it in your environment or systemd service file." - [ ] Verify: Shows helpful error for each missing required variable - [ ] Verify: Uses smart defaults for DATABASE_PATH and STORAGE_PATH **Deliverable:** Configuration system with rock-solid error messages, no .env auto-loading **Note:** Environment variables must be explicitly set by the deployer. This ensures clarity about configuration and avoids hidden .env files in production. --- ### Task 1.4: Structured Logging Setup **Goal:** Add tracing/logging infrastructure **Steps:** - [ ] Add dependencies: `tracing`, `tracing-subscriber` - [ ] Set up logging in `main.rs` with appropriate level filtering - [ ] Add request tracing middleware to axum - [ ] Test logging at different levels (debug, info, warn, error) - [ ] Verify: Logs show timestamps and structured data - [ ] Verify: HTTP requests are logged with method, path, status **Deliverable:** Structured logging throughout application --- ## Phase 2: Database & User Management ### Task 2.1: SQLite Database Setup **Goal:** Initialize database with sqlx **Steps:** - [ ] Add dependencies: `sqlx` (with "sqlite", "runtime-tokio", "migrate") - [ ] Create `migrations/` directory at root - [ ] Create initial migration: `sqlx migrate add init` - [ ] Define `users` table schema in migration: - `id TEXT PRIMARY KEY` (UUID as string) - `email TEXT UNIQUE NOT NULL` - `password_hash TEXT NOT NULL` - `display_name TEXT NOT NULL` - `created_at TEXT NOT NULL` (ISO8601 timestamp) - [ ] Run migration: `sqlx migrate run` - [ ] Create `src/db.rs` with connection pool setup - [ ] Verify: Database file created at configured path - [ ] Verify: Can connect to database and query tables **Deliverable:** Database with users table and migration system --- ### Task 2.2: User Model & Repository **Goal:** Create user data structures and database access **Steps:** - [ ] Create `src/models/user.rs` - [ ] Define `User` struct matching database schema - [ ] Add `uuid` and `chrono` dependencies - [ ] Create `src/repositories/user.rs` - [ ] Implement functions: - `create_user(pool, email, password_hash, display_name) -> Result` - `find_user_by_email(pool, email) -> Result>` - `find_user_by_id(pool, id) -> Result>` - [ ] Write compile-time checked queries with `sqlx::query_as!` - [ ] Verify: Can create user in database - [ ] Verify: Can query user by email and id **Deliverable:** User model with database operations --- ### Task 2.3: Password Hashing **Goal:** Secure password storage with argon2 **Steps:** - [ ] Add dependency: `argon2` crate - [ ] Create `src/auth/password.rs` - [ ] Implement `hash_password(password: &str) -> Result` - [ ] Implement `verify_password(password: &str, hash: &str) -> Result` - [ ] Write unit tests for password hashing and verification - [ ] Verify: Hashed passwords are different for same input (salt) - [ ] Verify: Valid password verifies successfully - [ ] Verify: Invalid password fails verification **Deliverable:** Secure password hashing and verification --- ### Task 2.4: JWT Token Generation **Goal:** Create and validate JWT tokens **Steps:** - [ ] Add dependency: `jsonwebtoken` - [ ] Create `src/auth/jwt.rs` - [ ] Define `Claims` struct with user_id and expiration - [ ] Implement `generate_access_token(user_id: &str) -> Result` (15 min expiry) - [ ] Implement `generate_refresh_token(user_id: &str) -> Result` (7 day expiry) - [ ] Implement `validate_token(token: &str) -> Result` - [ ] Write unit tests for token generation and validation - [ ] Verify: Generated tokens can be decoded - [ ] Verify: Expired tokens fail validation - [ ] Verify: Invalid tokens fail validation **Deliverable:** JWT token system with access and refresh tokens --- ### Task 2.5: Registration Endpoint **Goal:** POST /api/auth/register endpoint **Steps:** - [ ] Create `src/handlers/auth.rs` - [ ] Define `RegisterRequest` struct (email, password, display_name) - [ ] Add validation: email format, password min length, display_name length - [ ] Implement `register_handler` function: - Validate input - Check if email already exists - Hash password - Create user in database - Generate tokens - Return tokens + user info - [ ] Add route to axum router: `POST /api/auth/register` - [ ] Verify with curl: Can register new user - [ ] Verify: Returns 400 for invalid input - [ ] Verify: Returns 409 for duplicate email - [ ] Verify: Returns access_token and refresh_token **Deliverable:** Working registration endpoint --- ### Task 2.6: Login Endpoint **Goal:** POST /api/auth/login endpoint **Steps:** - [ ] Define `LoginRequest` struct (email, password) - [ ] Implement `login_handler` function: - Find user by email - Verify password - Generate tokens - Return tokens + user info - [ ] Add route: `POST /api/auth/login` - [ ] Verify with curl: Can login with valid credentials - [ ] Verify: Returns 401 for invalid email - [ ] Verify: Returns 401 for wrong password - [ ] Verify: Returns access_token and refresh_token **Deliverable:** Working login endpoint --- ### Task 2.7: Auth Middleware **Goal:** Protect routes with JWT validation **Steps:** - [ ] Create `src/middleware/auth.rs` - [ ] Implement auth middleware that: - Extracts token from Authorization header - Validates token - Adds user_id to request extensions - [ ] Create helper function to get current user from request - [ ] Create test endpoint: `GET /api/auth/me` (returns current user info) - [ ] Add middleware to router - [ ] Verify: Protected route requires valid token - [ ] Verify: Returns 401 for missing token - [ ] Verify: Returns 401 for invalid token - [ ] Verify: Can access user info in protected routes **Deliverable:** JWT authentication middleware --- ## Phase 3: Frontend Authentication ### Task 3.1: TypeScript API Client Foundation **Goal:** Create type-safe API client **Steps:** - [ ] Create `client/src/api.ts` - [ ] Create `client/src/types.ts` - [ ] Define TypeScript interfaces matching Rust types: - `User` interface - `LoginRequest` interface - `RegisterRequest` interface - `AuthResponse` interface (tokens + user) - [ ] Implement `ApiClient` class with base URL and fetch wrapper - [ ] Add error handling for different status codes - [ ] Implement methods: - `register(email, password, displayName)` - `login(email, password)` - [ ] Verify: Can call API from TypeScript with type checking **Deliverable:** Type-safe API client --- ### Task 3.2: Token Storage **Goal:** Store and manage JWT tokens **Steps:** - [ ] Create `client/src/auth.ts` - [ ] Implement token storage using localStorage: - `saveTokens(accessToken, refreshToken)` - `getAccessToken()` - `getRefreshToken()` - `clearTokens()` - [ ] Add token to API client requests (Authorization header) - [ ] Implement `isAuthenticated()` check - [ ] Verify: Tokens persist across page reloads - [ ] Verify: Can access protected endpoints with token **Deliverable:** Client-side token management --- ### Task 3.3: Registration Form (Web Component) **Goal:** Create registration UI **Steps:** - [ ] Create `client/src/components/register-form.ts` - [ ] Define `RegisterForm` Web Component extending HTMLElement - [ ] Add form HTML in `connectedCallback`: - Email input - Password input - Display name input - Submit button - [ ] Add form validation - [ ] Handle form submit: - Call API client register method - Save tokens on success - Show error message on failure - Redirect to home on success - [ ] Add styles (scoped with Shadow DOM) - [ ] Register component: `customElements.define('register-form', RegisterForm)` - [ ] Add to `index.html` for testing - [ ] Verify: Can register new user through UI - [ ] Verify: Shows validation errors - [ ] Verify: Shows API errors **Deliverable:** Working registration form component --- ### Task 3.4: Login Form (Web Component) **Goal:** Create login UI **Steps:** - [ ] Create `client/src/components/login-form.ts` - [ ] Define `LoginForm` Web Component - [ ] Add form HTML: - Email input - Password input - Submit button - Link to registration - [ ] Handle form submit: - Call API client login method - Save tokens on success - Redirect to home on success - [ ] Add styles - [ ] Register component - [ ] Add to `index.html` for testing - [ ] Verify: Can login through UI - [ ] Verify: Shows error for invalid credentials - [ ] Verify: Redirects after successful login **Deliverable:** Working login form component --- ### Task 3.5: Simple Routing **Goal:** Basic client-side navigation **Steps:** - [ ] Create `client/src/router.ts` - [ ] Implement simple hash-based routing: - `#/` - home/video feed - `#/login` - login page - `#/register` - registration page - `#/upload` - upload page - [ ] Implement `navigateTo(path)` function - [ ] Add route guard: redirect to login if not authenticated - [ ] Update components to use router for navigation - [ ] Verify: Can navigate between pages - [ ] Verify: Protected routes redirect to login - [ ] Verify: After login, redirects to intended page **Deliverable:** Basic client-side routing --- ## Phase 4: Video Upload Backend ### Task 4.1: Video Storage Setup **Goal:** Configure video file storage **Steps:** - [ ] Create storage directory structure on startup: - `$STORAGE_PATH/originals/` - `$STORAGE_PATH/variants/` - `$STORAGE_PATH/thumbs/` - [ ] Create `src/storage.rs` with helper functions - [ ] Implement `ensure_storage_dirs() -> Result<()>` - [ ] Implement `get_video_storage_path(video_id: &str) -> PathBuf` - [ ] Call on startup - [ ] Verify: Directories created on first run - [ ] Verify: Handles errors gracefully (permissions, etc.) **Deliverable:** Storage directory management --- ### Task 4.2: Video Database Schema **Goal:** Create video tables **Steps:** - [ ] Create migration: `sqlx migrate add videos` - [ ] Define `videos` table: - `id TEXT PRIMARY KEY` (UUID) - `uploader_id TEXT NOT NULL` (foreign key to users) - `group_id TEXT` (NULL for now, will add groups later) - `title TEXT` - `description TEXT` - `duration_secs REAL NOT NULL` - `upload_date TEXT NOT NULL` - `original_path TEXT NOT NULL` - `thumbnail_path TEXT` - `processing_status TEXT NOT NULL` (pending/processing/complete/failed) - [ ] Define `video_variants` table: - `id TEXT PRIMARY KEY` - `video_id TEXT NOT NULL` (foreign key to videos) - `quality TEXT NOT NULL` (high/medium/low) - `max_dimension INTEGER NOT NULL` - `path TEXT NOT NULL` - `bitrate_kbps INTEGER NOT NULL` - [ ] Run migration - [ ] Verify: Tables created successfully **Deliverable:** Video database schema --- ### Task 4.3: Video Model & Repository **Goal:** Video data structures and queries **Steps:** - [ ] Create `src/models/video.rs` - [ ] Define `Video` struct - [ ] Define `VideoVariant` struct - [ ] Define `ProcessingStatus` enum - [ ] Create `src/repositories/video.rs` - [ ] Implement functions: - `create_video(pool, video) -> Result