15 KiB
VitFit V2 — File Structure
Every file in the deployed application with its purpose and primary exports.
Root
/home/ubuntu/site/
├── app.js
├── .env
├── package.json
├── openapi.yaml
├── CHANGELOG.md
├── scripts/
├── core/
├── modules/
├── public/
├── tests/
└── uploads/
CHANGELOG.md
Human-readable release notes for the gym owner/operator. Not a git log — describes user-visible changes in plain language. Template per release:
## [1.x.x] — YYYY-MM-DD
### What's new
- ...
### Fixed
- ...
### Notes for update
- Run `npm install` if listed
- Run `node_modules/.bin/sequelize db:migrate` if listed
app.js — Main Entry Point
Boots the application. Does not export anything — side effect only.
Responsibilities:
- Load
.env - Initialize pino logger
- Run database migrations via
core/db.js - Create Express app, apply global middleware
- Auto-load all modules from
modules/*/routes.js - Attach Socket.io via
core/socket.js - Register the global error handler
- Start HTTP server on
PORT - Signal PM2 ready (
process.send('ready'))
Global middleware stack (in order):
helmet()— security headers (including CSP — see ARCHITECTURE.md)cors()— CORS (restrict origin in production viaCORS_ORIGINenv)express.json({ limit: '64kb' })— JSON body parser with explicit size cap; prevents DoS via large payloadsexpress.static('public')— serve frontend HTML/JS/CSSauthRateLimiterapplied to bothPOST /api/v1/auth/loginANDPOST /api/v1/auth/device-login— 10 req/15 min per IP
Static HTML security model: HTML files are served publicly — no server-side auth gate
on the HTML delivery itself. Auth is enforced on every API call: core.js runs on every
page load, checks localStorage for a valid JWT, and redirects to / if missing or expired.
This is the standard SPA/MPA pattern: the server trusts the client to request only data the
user is authorized for, and the API enforces that boundary. Sensitive data (workouts, videos,
client records) is never embedded in static HTML.
Multer disk storage: All file upload routes use multer({ dest: process.env.UPLOAD_TEMP_DIR }).
UPLOAD_TEMP_DIR defaults to /tmp/vitfit-uploads. The service reads magic bytes from the temp
file path (not file.buffer) and then moves the file to UPLOADS_DIR. memoryStorage() is
never used — loading a 500 MB video into memory on a 4 GB server would be unsafe.
.env — Environment Variables
PORT=3000
JWT_SECRET=<long random string>
DB_PATH=/home/ubuntu/site/database.sqlite
UPLOADS_DIR=/home/ubuntu/site/uploads
UPLOAD_TEMP_DIR=/tmp/vitfit-uploads # multer disk storage temp dir
BACKUP_UPLOADS_DEST=/mnt/backup/uploads
CORS_ORIGIN=https://yourdomain.com
UPLOAD_MAX_BYTES=524288000 # 500 MB
STORAGE_WARN_BYTES=5368709120 # 5 GB
NODE_ENV=production
scripts/
scripts/
├── setup.js First-run bootstrap: create org, branding, owner, sysadmin
├── support-bundle.js Print diagnostic info for support (redacted of PII)
├── backup.sh SQLite backup script (called by cron)
└── backup-uploads.sh Weekly rsync of uploads/ to off-server backup location
scripts/setup.js
Interactive CLI. Reads .env, connects to DB, refuses to run if any Organization exists.
Creates: Organization, Branding (defaults), Owner user, SystemAdmin user in one transaction.
Exits with code 1 on any error.
scripts/support-bundle.js
Non-interactive. Prints JSON/text summary to stdout: app version, Node version, migration status, DB size, uploads size, disk available, org count, user counts, PM2 status, last 5 error log lines (redacted). Safe to share.
scripts/backup.sh
Called by cron. Runs sqlite3 $DB_PATH ".backup '$BACKUP_PATH'".
Cleans backups older than 14 days in the backup directory.
scripts/backup-uploads.sh
Called by weekly cron. Runs rsync -av --checksum $UPLOADS_DIR/ $BACKUP_UPLOADS_DEST/.
BACKUP_UPLOADS_DEST is a separate directory or mount (configure in .env).
Logs output to /var/log/vitfit-uploads-backup.log. Does not delete from source.
core/
core/
├── db.js Sequelize instance, PRAGMA config, model registry, migration runner
├── auth.js Middleware: authenticateToken, authenticateRole, requireFeature
├── audit.js Audit log helper: log()
├── storage.js Disk stats, upload size cache, upload guard middleware
├── socket.js Socket.io server init and io accessor
├── logger.js Pino logger instance (exported as singleton)
├── errors.js AppError class and global Express error handler
├── respond.js Response helper functions: ok, created, collection, err
└── schemas/
├── auth.js Zod schemas for /auth/* request bodies
├── users.js Zod schemas for /users/* request bodies
├── org.js Zod schemas for /org/* request bodies
├── videos.js Zod schemas for /videos/* request bodies
├── workouts.js Zod schemas for /workouts/* request bodies
├── timers.js Zod schemas for /timers/* request bodies
├── crossfit.js Zod schemas for /crossfit-workouts/* request bodies
└── clients.js Zod schemas for /clients/* request bodies
core/schemas/ — All Zod validation schemas. Each route imports its schema and runs
schema.safeParse(req.body), throwing AppError('VALIDATION_FAILED', ...) if invalid.
Centralizing schemas here keeps routes thin and makes schemas testable in isolation.
core/db.js
Exports: { sequelize, models, initDb, runMigrations }
initDb() — Creates Sequelize instance pointed at DB_PATH. Applies PRAGMAs.
runMigrations() — Programmatically runs sequelize-cli pending migrations.
models — Object keyed by model name containing all Sequelize model classes.
core/auth.js
Exports: { authenticateToken, authenticateRole, requireFeature }
Middleware functions used as route-level Express middleware.
core/audit.js
Exports: { log }
log(req, action, entityType, entityId, details) — Inserts one AuditLog row.
Does not throw; errors are caught and logged via pino (audit failure must not break the request).
core/storage.js
Exports: { getStorageInfo, checkUploadAllowed }
getStorageInfo() — Returns { disk, uploads, warning }. Disk result cached 60 seconds.
checkUploadAllowed — Express middleware. Calls getStorageInfo(), returns 507 if warning.
core/socket.js
Exports: { init, getIo }
init(httpServer) — Attaches Socket.io. Registers connection/disconnect handlers.
getIo() — Returns the io singleton. Used by timer-engine.js.
core/logger.js
Exports: pino logger instance with level set from LOG_LEVEL env (default 'info').
core/errors.js
Exports: { AppError, errorHandler }
AppError — extends Error. Fields: code, message, status, field.
errorHandler — Express (err, req, res, next) middleware. Converts AppError to standard
response shape. Logs 5xx errors via pino.
core/respond.js
Exports: { ok, created, collection, err }
Thin wrappers that produce the standard response envelopes from API_STANDARDS.md.
modules/
Each module is a self-contained feature unit. Structure:
modules/<name>/
├── routes.js Express Router. Composes middleware + service calls.
├── service.js Business logic. DB queries + validation + audit calls.
└── model.js Sequelize model definition(s).
Some modules have an additional file:
timers/timer-engine.js— in-memory timer state machine
modules/
├── auth/
│ ├── routes.js
│ ├── service.js
│ └── model.js (DeviceToken)
├── users/
│ ├── routes.js
│ ├── service.js
│ └── model.js (User)
├── org/
│ ├── routes.js
│ ├── service.js
│ └── model.js (Organization, Branding)
├── videos/
│ ├── routes.js
│ ├── service.js
│ └── model.js (Video, Category)
├── workouts/
│ ├── routes.js
│ ├── service.js
│ └── model.js (Workout)
├── timers/
│ ├── routes.js
│ ├── service.js
│ ├── timer-engine.js (TimerEngine class)
│ └── model.js (Timer)
├── crossfit/
│ ├── routes.js
│ ├── service.js
│ └── model.js (CrossfitWorkout)
├── clients/
│ ├── routes.js
│ ├── service.js
│ └── model.js (CoachClientLink, ClientWorkout, CalendarSession)
├── audit/
│ ├── routes.js (read-only: GET /audit-logs, GET /audit-logs/export)
│ └── model.js (AuditLog — writes via core/audit.js only)
└── sysadmin/
└── routes.js (cross-org views, health, org management)
public/
All files in public/ are served as static files by Express or Nginx.
uploads/ is NOT inside public/ — it is a sibling directory.
public/
├── manifest.json PWA manifest
├── sw.js Service worker (cache app shell)
├── styles/
│ ├── base.css Reset, CSS custom properties (:root vars), typography
│ ├── layout.css Banner, nav drawer, page shell grid
│ ├── components.css Buttons, forms, cards, tables, badges, overlays
│ └── display.css TV display mode (full-screen, no chrome, large type)
├── js/
│ ├── core.js Auth bootstrap, fetch wrapper, nav drawer, branding loader
│ ├── socket-client.js Socket.io client with auto-reconnect wrapper
│ ├── display.js Display mode controller (workout / crossfit views)
│ └── timer-display.js Timer countdown UI, phase state, local-fallback mode
├── icons/
│ ├── icon-180.png Apple touch icon
│ ├── icon-192.png PWA maskable icon
│ └── icon-512.png PWA splash icon
├── index.html Login page
├── dashboard.html Home (Owner/Coach)
├── videos.html Video library browse/manage
├── upload-video.html Upload video form
├── categories.html Manage video categories
├── workouts.html Group workout list
├── create-workout.html Create/edit group workout
├── workout-view.html Single workout detail
├── workout-display.html Full-screen TV display — group workout
├── timers.html Timer list
├── create-timer.html Create/edit timer config
├── timer-display.html Full-screen TV display — timer running
├── crossfit.html CrossFit workout list
├── create-crossfit.html Create CrossFit workout
├── crossfit-display.html Full-screen TV display — CrossFit workout
├── clients.html Client roster (Coach/Owner)
├── client-profile.html Individual client detail, workouts, sessions
├── calendar.html Coach calendar view
├── my-workouts.html Client: own assigned workouts
├── my-schedule.html Client: own upcoming sessions
├── profile.html Own profile / change password
├── settings.html Owner: users, branding, storage, device tokens
├── audit-log.html Owner: audit log viewer
└── sysadmin.html SystemAdmin panel
public/js/core.js
Loaded on every page. Provides:
Auth— token read/write, device token refresh, session expired overlayApi— fetch wrapper that injects Authorization header, handles 401, retries after token refreshNav— drawer open/close, mark active link, role-based link visibilityBranding— fetches/api/v1/org/brandingon load, applies CSS custom properties to:rootPage.init(rolesAllowed)— called by every page; redirects to/if not logged in or wrong role
public/js/socket-client.js
Exports SocketClient class:
- Wraps
io()with reconnect event handling - Emits
client:readywhen connected - Exposes
on(event, handler)andemit(event, data)proxies - On reconnect: calls a registered
onReconnectcallback so pages can re-sync state
public/js/display.js
Used by workout-display.html and crossfit-display.html.
- Renders workout/CrossFit data in full-screen TV layout
- Applies branding colors from CSS custom properties
- Keeps a constant low-opacity pulse animation to prevent AirPlay freeze
- Shows offline overlay when server unreachable (content remains visible underneath)
public/js/timer-display.js
Used by timer-display.html.
- Connects to Socket.io and joins the timer room
- Handles
timer:tick,timer:phase-change,timer:completeevents - Falls back to local countdown using received
endTimeif Socket.io disconnects localFallback(endTime)— runsDate.now()diff per animationFrame, no drift- Manages phase colors by reading CSS custom properties from branding
uploads/
uploads/
└── <timestamp>_<random>.<ext> Video files — never served statically
Filenames are generated as Date.now() + '_' + crypto.randomBytes(8).toString('hex') + ext
to prevent name collisions and enumeration.
Files in this directory are accessed only through GET /api/v1/videos/stream/:filename,
which enforces JWT auth and handles HTTP Range requests.
tests/
See TESTING.md for the full test plan, case lists, and helper API.
tests/
├── helpers/
│ ├── db.js In-memory SQLite setup/teardown; runs migrations before each suite
│ ├── auth.js makeJwt(), authHeader() — no DB needed
│ ├── factories.js seedOrg(), seedUser(), seedVideo(), seedTimer() — minimal DB seeds
│ └── socket.js Create real Socket.io server + test client bound to random port
├── unit/
│ ├── timer-engine.test.js TimerEngine state machine (mocked io)
│ ├── validate-mime.test.js Magic-byte validation reads from file, not buffer
│ ├── storage.test.js 60s cache, checkUploadAllowed 507 behavior
│ ├── contrast.test.js Branding WCAG contrast ratio pass/fail
│ └── respond.test.js ok/created/collection/err envelope shapes
├── integration/
│ ├── migrations.test.js All 13 migrations run in order against :memory:
│ ├── auth.test.js
│ ├── users.test.js
│ ├── videos.test.js
│ ├── workouts.test.js
│ ├── timers.test.js
│ ├── crossfit.test.js
│ ├── clients.test.js
│ ├── audit.test.js
│ └── org.test.js
├── socket/
│ └── timer-engine.socket.test.js
└── e2e/
└── display-burn-in.test.js Manual only (npm run test:burnin); Playwright/WebKit