15 KiB
VitFit V2 — Architecture
Guiding Principles
- Lean stack — The server has 2 CPU / 4 GB RAM. No unnecessary processes.
- Modular — Each feature is a drop-in module. Core framework is untouched when adding features.
- Safari-first — All frontend decisions are validated against Safari on iPadOS.
- 24h session stability — Long-running JS must not leak memory or drift. Server-authoritative state where possible.
- 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
helmetadded for security headersexpress-rate-limiton/loginexpress-validatororzodfor 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
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.
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:
// 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:
{
"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).
// 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, notsetInterval - 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
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.jscore 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: nonewhen 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
- Create
modules/<feature>/withroutes.js,model.js, and amigrations/subfolder - Register the module in
app.jswith one line:app.use('/feature', require('./modules/feature/routes')) - Add the frontend page(s) to
public/ - Add a nav link to
public/js/core.jsnav config array - 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-tokenendpoint 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.sqliteis 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
WorkoutItemjoin table while the old 4-slot columns are kept temporarily for backward reads during transition
Security Checklist
helmet()middleware on all routesexpress-rate-limiton/login(10 req/15 min)- Input validation on every POST/PUT route (
zodorexpress-validator) - JWT secret from env, app refuses to start without it
- MIME type validation on file uploads (not just extension)
- File size limit on video uploads (configurable via env)
- Upload rejected with HTTP 507 when available disk < 2×
STORAGE_WARN_BYTES - Video files served through authenticated
/videos/stream/:filenameroute, 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)
.envin.gitignore
Dependency Plan
Keep from V1:
express,sequelize,sqlite3,bcryptjs,jsonwebtoken,multer,cors,dotenv
Add:
socket.io— real-time timer synchelmet— security headersexpress-rate-limit— login brute force protectionzod— schema validation (lighter than express-validator, works in browser too for future iOS)pino— structured logging (replace rawconsole.log; lighter than winston)sequelize-cli— migration managementcheck-disk-space— cross-platform disk stats for storage monitoring endpoint
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)