Files
vitfit-r2/V2/planning/ARCHITECTURE.md
T
2026-06-11 10:52:07 -04:00

471 lines
20 KiB
Markdown

# 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 <video> element)
```
This is critical: **Safari's `<video>` element requires Range request support** to seek within a video. The route must respond to `Range` headers with a `206 Partial Content` response. A plain `fs.createReadStream` pipe without Range handling will break video playback in Safari.
Implementation sketch:
```js
// modules/videos/routes.js
router.get('/stream/:filename', authenticateToken, (req, res) => {
const filePath = path.join(UPLOADS_DIR, req.params.filename);
const stat = fs.statSync(filePath);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const [start, end] = range.replace(/bytes=/, '').split('-').map(Number);
const chunkEnd = end || Math.min(start + 1024 * 1024, fileSize - 1);
res.writeHead(206, {
'Content-Range': `bytes ${start}-${chunkEnd}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkEnd - start + 1,
'Content-Type': 'video/mp4',
});
fs.createReadStream(filePath, { start, end: chunkEnd }).pipe(res);
} else {
res.writeHead(200, { 'Content-Length': fileSize, 'Content-Type': 'video/mp4' });
fs.createReadStream(filePath).pipe(res);
}
});
```
`UPLOADS_DIR` is set from `.env`: `UPLOADS_DIR=/home/ubuntu/site/uploads`
---
### Storage Monitoring
A new admin-only feature that shows disk usage in the admin panel.
**API endpoint:** `GET /admin/storage` (requires `authenticateToken` + `authenticateAdmin`)
Response shape:
```json
{
"disk": {
"total": 53687091200,
"used": 21474836480,
"available": 32212254720,
"usedPercent": 40
},
"uploads": {
"size": 4831838208,
"fileCount": 47
},
"warning": false
}
```
`warning: true` when available disk space drops below `STORAGE_WARN_BYTES` (env var, default 5 GB).
**Implementation:** Use the `check-disk-space` npm package for cross-platform disk stats. For uploads folder size, use a recursive `fs` walk summing `stat.size` (fast enough for < 1000 files; cache the result for 60 seconds to avoid hammering the FS on every page load).
```js
// core/storage.js
const checkDiskSpace = require('check-disk-space').default;
const UPLOADS_DIR = process.env.UPLOADS_DIR;
const WARN_BYTES = parseInt(process.env.STORAGE_WARN_BYTES || String(5 * 1024 ** 3));
let uploadsCache = null;
let uploadsCacheTime = 0;
async function getUploadsSize() {
if (Date.now() - uploadsCacheTime < 60_000) return uploadsCache;
let total = 0, count = 0;
for (const f of fs.readdirSync(UPLOADS_DIR)) {
try { const s = fs.statSync(path.join(UPLOADS_DIR, f)); total += s.size; count++; } catch {}
}
uploadsCache = { size: total, fileCount: count };
uploadsCacheTime = Date.now();
return uploadsCache;
}
async function getStorageInfo() {
const [disk, uploads] = await Promise.all([checkDiskSpace(UPLOADS_DIR), getUploadsSize()]);
return { disk, uploads, warning: disk.free < WARN_BYTES };
}
```
**Upload guard:** Before accepting a new video upload, multer's `fileFilter` checks available space. If `disk.free < WARN_BYTES * 2` (double the warning threshold as the upload hard limit), reject with HTTP 507 (Insufficient Storage).
**Frontend display (admin panel):**
- Progress bar: used / total, color-coded (green → yellow → red as disk fills)
- Three stats: Total, Used, Available (human-readable: GB/MB)
- Uploads folder: size + file count
- Auto-refreshes every 5 minutes (not on every render)
- Warning banner appears when `warning: true`
---
### Real-time: Socket.io
V1 timers are purely client-side — the server has no awareness of timer state. This works but is fragile over a 24h session.
**V2 approach:**
- Timer state lives on the server (in memory, per active session)
- Client connects via Socket.io and receives tick events
- If the iPad briefly disconnects/reconnects, it re-syncs to server time
- Server-side timer uses `process.hrtime()` for drift-free intervals, not `setInterval`
- Room-based: each active timer run is a room; admin can see status from management UI
**Why not polling?** Polling every second from a 24h-running browser is noisy and wasteful. Socket.io with auto-reconnect is cleaner and more reliable.
### Process Management: PM2
```bash
pm2 start app.js --name vitfit
pm2 startup # auto-restart on server reboot
pm2 save
```
PM2 handles:
- Auto-restart on crash
- Log rotation
- Memory limit restart (e.g., `--max-memory-restart 512M`)
### Reverse Proxy: Nginx + HTTPS
Nginx sits in front of Node:
- Terminates TLS (Let's Encrypt / Certbot)
- Proxies to `localhost:3000`
- Serves static files directly (faster than Node for assets)
- Buffers WebSocket upgrades for Socket.io
**This is required.** Safari on iPad will not allow persistent WebSocket connections or full-screen AirPlay over HTTP on a local network in some iPadOS versions.
---
## Frontend
### Approach: Vanilla JS + CSS Modules (no heavy framework)
The app is display-oriented, not a complex SPA. A full framework (React, Vue) adds build complexity and memory overhead for marginal benefit on this hardware profile.
**V2 approach:**
- Each page is still an HTML file, but styles move to a shared `styles/` folder
- A single `app.js` core handles: auth token management, nav drawer, shared fetch wrapper
- Feature modules add their own `<script>` bundles — no bundler required for basic features
- CSS custom properties (variables) for theming — one place to change colors/fonts
**If complexity grows:** Switch to Vite + vanilla JS or Svelte (lightweight, compiles to minimal JS). Avoid React for this use case.
### Two Distinct UI Modes
This is the most important structural change from V1.
**Control Mode (coach on iPad)**
- Standard management UI: create workouts, manage videos, start timers
- Touch-optimized
- Normal nav drawer, forms, admin controls
**Display Mode (gym-facing, cast to TV)**
- Triggered when a workout or timer is "launched" for display
- Full-screen layout, no navigation chrome
- Large text, high contrast, readable at 10+ feet
- Minimal DOM updates (reduces jitter on AirPlay stream)
- No cursor (CSS `cursor: none` when idle)
- Designed for 16:9 aspect ratio (TV)
The iPad shows Display Mode. Coach interactions (start/stop/next) are touch targets on the edges of the display — invisible to the TV audience but accessible to the coach.
---
## Module System
### Structure
On the server, the deployed structure maps to `/home/ubuntu/site/`:
```
/home/ubuntu/site/ (= V2/site/ in this repo)
├── app.js # Core: Express init, middleware, module loader
├── .env # Secrets + config (not in repo)
├── package.json
├── core/
│ ├── auth.js # JWT middleware
│ ├── db.js # Sequelize instance + migration runner
│ ├── socket.js # Socket.io setup
│ ├── storage.js # Disk/uploads storage helpers
│ └── logger.js # Structured logger (pino)
├── modules/
│ ├── users/ # User management feature
│ │ ├── routes.js
│ │ ├── model.js
│ │ └── migrations/
│ ├── videos/ # Video upload + library + streaming
│ │ ├── routes.js # Includes /stream/:filename with Range support
│ │ ├── model.js
│ │ └── migrations/
│ ├── workouts/ # Video workouts
│ │ ├── routes.js
│ │ ├── model.js
│ │ └── migrations/
│ ├── timers/ # Interval timers
│ │ ├── routes.js
│ │ ├── model.js
│ │ ├── timer-engine.js # Server-side timer state machine
│ │ └── migrations/
│ ├── crossfit/ # CrossFit workouts
│ │ ├── routes.js
│ │ ├── model.js
│ │ └── migrations/
│ └── admin/ # Admin panel: users, storage, logo
│ └── routes.js # Includes GET /admin/storage
├── public/ # Static frontend (served by Express or Nginx)
│ ├── styles/
│ │ ├── base.css # Reset, CSS variables, typography
│ │ ├── layout.css # Nav, drawer, page shell
│ │ └── display.css # TV display mode styles
│ ├── js/
│ │ ├── core.js # Token management, fetch wrapper, nav
│ │ └── socket-client.js
│ └── [feature pages]/ # HTML pages per feature
└── uploads/ # ← VIDEO FILES LIVE HERE, never inside public/
└── [timestamped video files] # Existing V1 files preserved in place
```
**Critical:** `uploads/` is a sibling of `public/`, not inside it. Express does NOT serve this directory statically. All video access goes through `GET /videos/stream/:filename` which enforces JWT auth and handles Range requests.
### How to Add a Feature
1. Create `modules/<feature>/` with `routes.js`, `model.js`, and a `migrations/` subfolder
2. Register the module in `app.js` with one line: `app.use('/feature', require('./modules/feature/routes'))`
3. Add the frontend page(s) to `public/`
4. Add a nav link to `public/js/core.js` nav config array
5. Run the migration
Nothing else changes. Removing a feature reverses these steps — no orphaned code.
---
## Authentication
### Changes from V1
| Concern | V1 | V2 |
|---------|----|----|
| Token expiry | 7 days | 7 days (unchanged — 24h sessions need this) |
| Secret source | `process.env.JWT_SECRET \|\| 'hardcoded'` | `process.env.JWT_SECRET` — fail to start if missing |
| Registration | Open endpoint | Admin-only user creation |
| Token storage | localStorage | localStorage (unchanged — httpOnly cookies would be better but Safari has restrictions with cross-context; localStorage is acceptable for this closed network use case) |
| Password reset | Admin UI | Admin UI (unchanged) |
### Session Stability for 24h iPad
- Token TTL stays at 7 days — no mid-day expiry
- A `/refresh-token` endpoint is added: before each fetch, if token is within 1 hour of expiry, silently refresh in the background
- If token is somehow invalid (server restart with new secret, etc.), the app shows a "Session expired — tap to re-login" overlay rather than breaking silently
---
## Data Migration (V1 → V2)
See `MIGRATION_PLAN.md` for the full script approach.
Summary:
- V1 `database.sqlite` is copied as the starting point
- Migration scripts add any new columns/tables without dropping existing data
- The V1 table structure maps cleanly to V2 models (no breaking schema changes planned at this stage)
- If the workout model is expanded (e.g., more than 4 video slots), a migration adds a new `WorkoutItem` join table while the old 4-slot columns are kept temporarily for backward reads during transition
---
## Security Checklist
- [ ] `helmet()` middleware on all routes (including explicit CSP — see CSP strategy below)
- [ ] `express-rate-limit` on `/login` AND `/auth/device-login` (10 req/15 min per IP)
- [ ] Per-username login lockout in auth service (10 failures/15 min, process-memory counter)
- [ ] `express.json({ limit: '64kb' })` — explicit body size cap to prevent large-payload DoS
- [ ] Input validation on every POST/PUT route (`zod` schemas in `core/schemas/`)
- [ ] Zod password validation: minimum 8, maximum 128 characters on all password fields
- [ ] JWT secret from env, app refuses to start without it
- [ ] `jwt.verify` called with `{ algorithms: ['HS256'] }` — prevents algorithm confusion attack
- [ ] `passwordChangedAt` timestamp updated on every password change/reset; checked in `authenticateToken` against `token.iat` to invalidate pre-change tokens
- [ ] MIME type validation on file uploads via magic bytes (first 12 bytes only, never full file in memory)
- [ ] File extension derived from detected MIME type — original uploaded filename extension discarded
- [ ] Multer temp file cleaned up in `finally` block regardless of validation outcome
- [ ] File size limit on video uploads (configurable via `UPLOAD_MAX_BYTES` env)
- [ ] Upload rejected with HTTP 507 when available disk < `STORAGE_WARN_BYTES`
- [ ] Video files served through authenticated `/videos/stream/:filename` route, never static
- [ ] Range request (seek) support in video streaming route (required for Safari)
- [ ] Nginx enforces HTTPS, redirects HTTP
- [ ] Admin-only registration (no open `/register`)
- [ ] Database queries use Sequelize parameterized queries (already true in V1, maintain)
- [ ] No sensitive data in logs (token values, passwords, `passwordChangedAt`)
- [ ] `.env` in `.gitignore`; `.env` permissions set to `600` on server
- [ ] Path traversal check on video streaming route (`path.basename` + resolved path prefix check)
- [ ] Socket.io `timer:join` verifies engine `orgId` matches requesting user's `organizationId`
- [ ] Branding color inputs validated as valid hex codes; contrast ratio ≥ 4.5:1 (WCAG AA) before saving
- [ ] Content Security Policy headers set (see CSP strategy below)
### Content Security Policy (CSP) Strategy
Applied via `helmet.contentSecurityPolicy()` in `app.js`, overriding helmet's default.
**Constraints:**
- Pages use inline event handlers that can't be removed easily (e.g., timer display countdown DOM updates)
- Socket.io client script is self-hosted (`/socket.io/socket.io.js`)
- Videos stream from the same origin (`/api/v1/videos/stream/...`)
- No external CDN dependencies in production — all JS/CSS is local
**Policy:**
```js
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // needed for inline JS on display pages
styleSrc: ["'self'", "'unsafe-inline'"], // needed for CSS custom property overrides
imgSrc: ["'self'", "data:"], // branding logo (self) + SVG inline (data:)
mediaSrc: ["'self'"], // video streaming from same origin
connectSrc: ["'self'", "wss:"], // Socket.io WebSocket upgrade
fontSrc: ["'self'"],
frameSrc: ["'none'"],
objectSrc: ["'none'"],
baseUri: ["'none'"],
formAction: ["'none'"],
}
})
```
**Notes:**
- `'unsafe-inline'` for scripts is a known concession. It is acceptable here because:
(a) the deployment is a closed gym app, not a public web service;
(b) all other vectors (external script loading, framing, object embeds) are locked down;
(c) removing it would require a full nonce-based refactor of the frontend pages.
- `wss:` in `connectSrc` allows the Socket.io WebSocket connection over TLS.
- Revisit `'unsafe-inline'` in a future refactor that moves display-page scripts to module files.
---
## Dependency Plan
Keep from V1:
- `express`, `sequelize`, `sqlite3`, `bcryptjs`, `jsonwebtoken`, `multer`, `cors`, `dotenv`
Add:
- `socket.io` — real-time timer sync
- `helmet` — security headers
- `express-rate-limit` — login brute force protection
- `zod` — schema validation (lighter than express-validator, works in browser too for future iOS)
- `pino` — structured logging (replace raw `console.log`; lighter than winston)
- `sequelize-cli` — migration management
- `check-disk-space` — cross-platform disk stats for storage monitoring endpoint
- `file-type` — magic-byte MIME validation for uploaded videos (detects disguised files)
- `luxon` — timezone-aware date handling for "today's workouts" and calendar queries
Remove:
- `body-parser` — built into Express 4.16+ (`express.json()`)
- `node-schedule` — not used in V1; not needed in V2 (Socket.io timer replaces it)