# VitFit V2 — Architecture ## Guiding Principles 1. **Lean stack** — The server has 2 CPU / 4 GB RAM. No unnecessary processes. 2. **Modular** — Each feature is a drop-in module. Core framework is untouched when adding features. 3. **Safari-first** — All frontend decisions are validated against Safari on iPadOS. 4. **24h session stability** — Long-running JS must not leak memory or drift. Server-authoritative state where possible. 5. **API-clean** — REST responses are consistent now so a future iOS app requires no backend changes. --- ## Server Environment | Item | Value | |------|-------| | OS | Ubuntu 24.04.1 LTS | | Access | PuTTY (SSH), WinSCP (SFTP) — no other access method | | App root | `/home/ubuntu/site/` | | Frontend pages | `/home/ubuntu/site/public/` | | Video uploads | `/home/ubuntu/site/uploads/` (outside public, **do not move**) | | Process manager | PM2 | | Reverse proxy | Nginx | The `uploads/` directory is **outside** the `public/` static tree intentionally. All video files are served through an authenticated Express route, never as bare static files. This means gym videos are not publicly accessible without a valid JWT — a security improvement over V1. --- ## Backend ### Framework: Express.js (keep) No reason to change. Lightweight, well-understood, sufficient for the load. **Changes from V1:** - Routes split into module files, not one monolithic `app.js` - Middleware organized: auth, validation, error handling, logging — each in own file - `helmet` added for security headers - `express-rate-limit` on `/login` - `express-validator` or `zod` for request body validation on all routes ### Database: SQLite + Sequelize (keep, add migrations) SQLite is appropriate for a single-gym install with < 10 concurrent users. Do not over-engineer. **Changes from V1:** - Replace `sync({ alter: true })` with proper Sequelize migrations (`sequelize-cli`) - Every schema change ships as a numbered migration file - V1 → V2 migration script handles the initial data carry-over - DB file location configurable via `.env` **SQLite configuration required at startup** (`core/db.js`): ```js // Enable WAL mode and set busy timeout immediately after opening const sequelize = new Sequelize({ dialect: 'sqlite', storage: process.env.DB_PATH }); sequelize.query('PRAGMA journal_mode = WAL;'); // concurrent reads while writing sequelize.query('PRAGMA busy_timeout = 5000;'); // wait up to 5s on lock instead of failing sequelize.query('PRAGMA foreign_keys = ON;'); // enforce FK constraints (SQLite default: OFF) ``` Without WAL mode, a video upload (disk write + DB write + audit log write in sequence) can cause brief read locks that make other requests timeout. WAL eliminates this for the read-heavy display pages. ### Video File Serving V1 stored uploads in `public/uploads/` and served them as static files — no auth required to access the video files if you knew the URL. V2 changes this. **Allowed Video Formats** Only these formats are accepted on upload: | Format | MIME Type | Notes | |--------|-----------|-------| | MP4 (H.264) | `video/mp4` | Primary format — universally supported by Safari | | MOV | `video/quicktime` | Common from iPhone/iPad recordings | | M4V | `video/x-m4v` | iTunes/Apple format, Safari-native | WebM, AVI, MKV, WMV are rejected — Safari does not support them. The upload endpoint validates MIME type by reading the file's magic bytes (first 12 bytes), not just the `Content-Type` header or file extension. Use the `file-type` npm package for this. **Size Limit:** Configurable via `UPLOAD_MAX_BYTES` env var (default: 500 MB). Set in multer `limits.fileSize`. **Duration:** Not validated at upload time (requires transcoding pipeline, out of scope). Coaches are responsible for keeping videos at a reasonable length. **Path Traversal Protection** The streaming route must never allow `../` sequences in the filename parameter to escape the uploads directory: ```js router.get('/stream/:filename', authenticateToken, (req, res) => { // Sanitize: strip any path components, allow only the bare filename const safeName = path.basename(req.params.filename); if (safeName !== req.params.filename) { return res.status(400).json({ error: { code: 'NOT_FOUND', message: 'Invalid filename.' } }); } const filePath = path.join(process.env.UPLOADS_DIR, safeName); // Verify the resolved path is still inside UPLOADS_DIR if (!filePath.startsWith(path.resolve(process.env.UPLOADS_DIR) + path.sep)) { return res.status(400).json({ error: { code: 'NOT_FOUND', message: 'Invalid filename.' } }); } // ... range request handling }); ``` **V2 approach: authenticated streaming route** ``` GET /uploads/:filename → authenticateToken middleware → pipes file from /home/ubuntu/site/uploads/:filename → sets correct Content-Type based on mime type stored in DB → supports Range header for video seeking (required by Safari's