Phase 3 planning
This commit is contained in:
@@ -0,0 +1,214 @@
|
||||
# VitFit V2 - Additional Considerations
|
||||
|
||||
This document captures planning items that are not fully covered elsewhere, or that deserve an explicit decision before implementation starts.
|
||||
|
||||
## Operational Readiness
|
||||
|
||||
### Backups and Restore Drills
|
||||
|
||||
The migration plan covers the V1 backup, but V2 also needs an ongoing backup strategy.
|
||||
|
||||
Consider documenting:
|
||||
- Automatic SQLite backups on a schedule.
|
||||
- Backup retention period.
|
||||
- Whether uploads are backed up with the database.
|
||||
- How database rows and video files stay consistent after restore.
|
||||
- A tested restore procedure, not just backup creation.
|
||||
|
||||
### Multi-Instance Update Process
|
||||
|
||||
V2 is intentionally multi-instance, which means every customer install eventually needs patching.
|
||||
|
||||
Consider documenting:
|
||||
- Version numbering and release notes.
|
||||
- A standard update checklist per customer.
|
||||
- Whether migrations can be dry-run or prechecked.
|
||||
- Maintenance window expectations.
|
||||
- Rollback strategy after a migration has already changed the database.
|
||||
- How urgent security patches are pushed across all installs.
|
||||
|
||||
### Monitoring and Alerts
|
||||
|
||||
The docs include a `/health` endpoint and storage monitoring UI, but not an alert path.
|
||||
|
||||
Consider documenting:
|
||||
- PM2 log rotation and disk limits.
|
||||
- External uptime checks.
|
||||
- Alerting when disk space is low, the process is down, or HTTPS renewal fails.
|
||||
- Where operational logs live and how long they are retained.
|
||||
|
||||
## Security and Privacy
|
||||
|
||||
### First-Run Bootstrap
|
||||
|
||||
Open registration is correctly out of scope, but the first Owner/SystemAdmin creation flow needs a safe path.
|
||||
|
||||
Consider documenting:
|
||||
- One-time setup command or seed script.
|
||||
- How default credentials are avoided.
|
||||
- How the first Organization, Owner, Branding, and SystemAdmin records are created.
|
||||
- How setup mode is disabled after first run.
|
||||
|
||||
### Device Security Policy
|
||||
|
||||
Device tokens support the iPad kiosk use case, but the physical device workflow should be explicit.
|
||||
|
||||
Consider documenting:
|
||||
- Lost/stolen iPad response.
|
||||
- Required iPad passcode, auto-lock, Guided Access, and Apple ID ownership.
|
||||
- Whether kiosk tokens are limited to specific roles.
|
||||
- How Owners identify and revoke old devices.
|
||||
- Whether device tokens should rotate on use.
|
||||
|
||||
### Privacy, Consent, and Data Export
|
||||
|
||||
Client features introduce personal fitness and scheduling data. This may not be regulated medical data, but it still needs basic privacy handling.
|
||||
|
||||
Consider documenting:
|
||||
- What client data is collected and why.
|
||||
- Owner/client data export process.
|
||||
- Client deactivation vs deletion.
|
||||
- Retention policy for inactive clients.
|
||||
- Whether audit logs intentionally retain user identifiers forever.
|
||||
|
||||
### API and Error Standards
|
||||
|
||||
The docs call for clean REST APIs, but implementation will be easier if response conventions are defined early.
|
||||
|
||||
Consider documenting:
|
||||
- API versioning, such as `/api/v1`.
|
||||
- Standard error response shape.
|
||||
- Pagination response shape.
|
||||
- Date/time serialization format.
|
||||
- Whether an OpenAPI document will be maintained.
|
||||
|
||||
## Data and Domain Rules
|
||||
|
||||
### Time Zones and Daylight Saving Time
|
||||
|
||||
Workouts and calendar sessions are date-sensitive, and gyms operate in local time.
|
||||
|
||||
Consider documenting:
|
||||
- Organization time zone field.
|
||||
- Whether dates are stored as UTC instants or local calendar dates.
|
||||
- How "today's workouts" are calculated.
|
||||
- Daylight saving behavior for recurring or scheduled sessions.
|
||||
|
||||
### Soft Deletes and Data Lifecycle
|
||||
|
||||
The data model uses `isActive` for users, while other objects still look hard-deletable.
|
||||
|
||||
Consider documenting:
|
||||
- Which entities are soft deleted.
|
||||
- Whether videos, workouts, timers, categories, and client workouts can be restored.
|
||||
- How deleted videos affect historical workouts and audit logs.
|
||||
- Whether Owners can permanently purge data.
|
||||
|
||||
### Permission Edge Cases
|
||||
|
||||
The permission matrix is strong, but a few edge cases should be specified.
|
||||
|
||||
Consider documenting:
|
||||
- Preventing the last Owner from being deactivated or demoted.
|
||||
- Whether an Owner can change their own role.
|
||||
- Whether Coaches can delete content created by another Coach.
|
||||
- Whether Coaches can self-assign clients by default.
|
||||
- What happens when a Client changes Coaches.
|
||||
|
||||
### SQLite Concurrency
|
||||
|
||||
SQLite is reasonable for this scale, but a few high-write moments can still create lock contention.
|
||||
|
||||
Consider documenting:
|
||||
- SQLite busy timeout settings.
|
||||
- WAL mode.
|
||||
- Transaction boundaries for upload + DB write + audit log.
|
||||
- Behavior when two admins edit or delete the same record at the same time.
|
||||
|
||||
## Media and Display
|
||||
|
||||
### Video Compatibility
|
||||
|
||||
The streaming route handles authenticated Range requests, but upload compatibility should also be defined.
|
||||
|
||||
Consider documenting:
|
||||
- Allowed video formats and codecs for iPad Safari.
|
||||
- Maximum upload size and duration.
|
||||
- Whether unsupported files are rejected or transcoding is introduced later.
|
||||
- How MIME type is verified beyond browser-provided metadata.
|
||||
- Path traversal protections for streaming filenames.
|
||||
|
||||
### Offline and Degraded Modes
|
||||
|
||||
The app shell may be cached, but most features depend on the server and network.
|
||||
|
||||
Consider documenting:
|
||||
- What the iPad displays if the server is unreachable.
|
||||
- Whether the last loaded workout can remain visible.
|
||||
- Whether timers can continue locally if Socket.io disconnects.
|
||||
- What happens if AirPlay drops during an active timer.
|
||||
- Manual recovery steps for staff.
|
||||
|
||||
### Physical Device Test Matrix
|
||||
|
||||
The docs are Safari-first, but the deployment depends on specific real hardware behavior.
|
||||
|
||||
Consider documenting:
|
||||
- Supported iPad models and iPadOS versions.
|
||||
- Supported TV/AirPlay setup.
|
||||
- Landscape/portrait lock expectations.
|
||||
- 24-hour burn-in test checklist.
|
||||
- Video seek/playback test checklist.
|
||||
|
||||
### Accessibility and Color Safety
|
||||
|
||||
Display mode has strong contrast goals, but branded colors can undermine readability.
|
||||
|
||||
Consider documenting:
|
||||
- Contrast validation for custom branding.
|
||||
- Colorblind-safe timer states.
|
||||
- Reduced-motion option if display animations are distracting.
|
||||
- Minimum touch target sizes for coach controls.
|
||||
|
||||
## Product and Support
|
||||
|
||||
### Support and Diagnostics
|
||||
|
||||
For resold installs, support will need a repeatable way to inspect problems.
|
||||
|
||||
Consider documenting:
|
||||
- Support bundle export, such as app version, config summary, recent logs, storage stats, and DB migration status.
|
||||
- Redaction rules for tokens, passwords, client notes, and personal data.
|
||||
- Whether SystemAdmin support access is enabled by default or requires Owner approval.
|
||||
|
||||
### Licensing and Instance Ownership
|
||||
|
||||
Billing is out of scope for V2, but resale still benefits from basic license metadata.
|
||||
|
||||
Consider documenting:
|
||||
- License key or customer identifier.
|
||||
- Instance owner contact.
|
||||
- Support expiration or renewal date.
|
||||
- What happens when an organization is suspended.
|
||||
|
||||
### Client Portal Future Hooks
|
||||
|
||||
The data model anticipates clients, but the surrounding product flows are not fully defined yet.
|
||||
|
||||
Consider documenting:
|
||||
- Client invitation flow.
|
||||
- Password reset flow.
|
||||
- Whether clients need email addresses before Phase 2.
|
||||
- Progress tracking, notes visibility, and client feedback.
|
||||
- Calendar conflict detection and recurring sessions.
|
||||
|
||||
## Documentation Hygiene
|
||||
|
||||
### Encoding Cleanup
|
||||
|
||||
Some Markdown output appears with mojibake characters in PowerShell, such as smart punctuation and icons rendering incorrectly.
|
||||
|
||||
Consider documenting or enforcing:
|
||||
- UTF-8 encoding for planning docs.
|
||||
- Plain ASCII diagrams where possible.
|
||||
- Editor settings so future docs render consistently in terminals, GitHub, and deployment notes.
|
||||
@@ -0,0 +1,235 @@
|
||||
# VitFit V2 — API Standards
|
||||
|
||||
These conventions apply to every endpoint in V2. Define them once here so they do not need to be decided route-by-route during implementation.
|
||||
|
||||
---
|
||||
|
||||
## Versioning
|
||||
|
||||
All API routes are prefixed `/api/v1/`.
|
||||
|
||||
```
|
||||
POST /api/v1/auth/login
|
||||
GET /api/v1/videos
|
||||
POST /api/v1/workouts
|
||||
GET /api/v1/admin/storage
|
||||
```
|
||||
|
||||
Static files, the health endpoint, and Socket.io are not versioned:
|
||||
```
|
||||
GET /health
|
||||
GET /public/* (static assets)
|
||||
/socket.io/* (Socket.io handshake)
|
||||
```
|
||||
|
||||
When a breaking API change is needed, a `/api/v2/` prefix is introduced and `/api/v1/` continues to work during a transition period. V2 of the API does not mean V3 of the app — version the API independently.
|
||||
|
||||
---
|
||||
|
||||
## Authentication Header
|
||||
|
||||
All protected endpoints expect:
|
||||
```
|
||||
Authorization: Bearer <jwt>
|
||||
```
|
||||
|
||||
Endpoints that do not require auth: `/api/v1/auth/login`, `/health`.
|
||||
|
||||
---
|
||||
|
||||
## Standard Response Shapes
|
||||
|
||||
### Success — Single Resource
|
||||
|
||||
```json
|
||||
{
|
||||
"data": { ...resource fields }
|
||||
}
|
||||
```
|
||||
|
||||
### Success — Collection
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [ ...items ],
|
||||
"meta": {
|
||||
"total": 142,
|
||||
"page": 1,
|
||||
"limit": 50,
|
||||
"totalPages": 3
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Error
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "VIDEO_NOT_FOUND",
|
||||
"message": "No video with that ID exists in your organization.",
|
||||
"field": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `code` — machine-readable, SCREAMING_SNAKE_CASE, stable across versions
|
||||
- `message` — human-readable, for display or logging
|
||||
- `field` — the specific input field that caused the error, or `null` if not field-specific
|
||||
|
||||
### Validation Error (multiple fields)
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "VALIDATION_FAILED",
|
||||
"message": "One or more fields are invalid.",
|
||||
"fields": [
|
||||
{ "field": "workoutDate", "message": "Must be a valid ISO 8601 date." },
|
||||
{ "field": "video1", "message": "Video ID does not exist in this organization." }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## HTTP Status Codes
|
||||
|
||||
| Situation | Code |
|
||||
|-----------|------|
|
||||
| Success, resource returned | 200 |
|
||||
| Success, resource created | 201 |
|
||||
| Success, no body | 204 |
|
||||
| Validation failed | 400 |
|
||||
| Not authenticated (no/expired token) | 401 |
|
||||
| Authenticated but not authorized (wrong role, wrong org) | 403 |
|
||||
| Resource not found | 404 |
|
||||
| Conflict (duplicate, constraint violation) | 409 |
|
||||
| Insufficient storage (upload blocked) | 507 |
|
||||
| Server error | 500 |
|
||||
|
||||
**Important:** 404 is used when a resource doesn't exist OR when a user is not authorized to know it exists. Never return 403 for a resource that belongs to a different org — use 404. This prevents enumeration attacks.
|
||||
|
||||
---
|
||||
|
||||
## Dates and Times
|
||||
|
||||
### Storage
|
||||
|
||||
All `DATETIME` columns are stored as **UTC** in SQLite. Sequelize handles the conversion when `type: DataTypes.DATE` is used.
|
||||
|
||||
### API Serialization
|
||||
|
||||
All date/time values in API responses and requests use **ISO 8601 with UTC offset**:
|
||||
|
||||
```
|
||||
"scheduledDate": "2025-07-15T09:00:00.000Z"
|
||||
```
|
||||
|
||||
Never return Unix timestamps (integers) — they are hard to read in logs and API explorers.
|
||||
|
||||
### Timezone-Aware Queries
|
||||
|
||||
Each Organization has a `timezone` field (IANA timezone string, e.g., `"America/New_York"`). The "today's workouts" query must use this timezone, not the server's local time.
|
||||
|
||||
```js
|
||||
// Correct approach
|
||||
const { DateTime } = require('luxon');
|
||||
const org = await Organization.findByPk(req.user.organizationId);
|
||||
const now = DateTime.now().setZone(org.timezone);
|
||||
const todayStart = now.startOf('day').toUTC().toJSDate();
|
||||
const todayEnd = now.endOf('day').toUTC().toJSDate();
|
||||
|
||||
const workouts = await Workout.findAll({
|
||||
where: {
|
||||
organizationId: req.user.organizationId,
|
||||
workoutDate: { [Op.between]: [todayStart, todayEnd] }
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**New dependency:** `luxon` — timezone-aware date handling. More reliable than `moment` (deprecated) or raw `Date` manipulation.
|
||||
|
||||
### Daylight Saving Time
|
||||
|
||||
Storing and querying in UTC avoids DST bugs entirely. The `timezone` field on Organization is only used at query-time to calculate the local "today" boundary. Events scheduled at 9:00 AM local time on a DST transition day will shift by 1 hour in UTC — this is correct and expected behavior for a gym schedule.
|
||||
|
||||
---
|
||||
|
||||
## Pagination
|
||||
|
||||
All collection endpoints support pagination via query parameters:
|
||||
|
||||
```
|
||||
GET /api/v1/workouts?page=2&limit=25
|
||||
```
|
||||
|
||||
- `page` — 1-indexed, default `1`
|
||||
- `limit` — results per page, default `50`, max `200`
|
||||
|
||||
Response always includes `meta` (see collection shape above). Never omit `meta` for collections, even if all results fit on one page — clients rely on `meta.total` to know there are no more pages.
|
||||
|
||||
---
|
||||
|
||||
## Error Codes (Catalog)
|
||||
|
||||
Defined upfront so frontend can handle specific errors without string-matching messages.
|
||||
|
||||
### Auth
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `AUTH_REQUIRED` | No token provided |
|
||||
| `AUTH_INVALID` | Token invalid or expired |
|
||||
| `AUTH_FORBIDDEN` | Valid token but insufficient role |
|
||||
| `AUTH_DEVICE_TOKEN_INVALID` | Device token not found, expired, or revoked |
|
||||
| `LOGIN_FAILED` | Bad username or password |
|
||||
|
||||
### Validation
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `VALIDATION_FAILED` | One or more fields failed validation (see `fields` array) |
|
||||
|
||||
### Resources
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `NOT_FOUND` | Resource does not exist (or you are not authorized to see it) |
|
||||
| `CONFLICT` | Duplicate value or constraint violation |
|
||||
| `UPLOAD_TYPE_INVALID` | File MIME type is not allowed |
|
||||
| `UPLOAD_SIZE_EXCEEDED` | File exceeds configured max size |
|
||||
| `STORAGE_INSUFFICIENT` | Server disk space too low to accept upload |
|
||||
|
||||
### Organization / Access
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `FEATURE_DISABLED` | Org does not have this feature enabled |
|
||||
| `LAST_OWNER_PROTECTED` | Cannot deactivate or demote the last Owner in the org |
|
||||
| `CANCELLATION_TOO_LATE` | Client attempting to cancel a session starting in < 24 hours |
|
||||
|
||||
---
|
||||
|
||||
## Request Body Content Type
|
||||
|
||||
All request bodies use `application/json` except file uploads, which use `multipart/form-data`.
|
||||
|
||||
The server rejects `application/x-www-form-urlencoded` with a 400. Do not support it — it reduces attack surface.
|
||||
|
||||
---
|
||||
|
||||
## OpenAPI
|
||||
|
||||
An OpenAPI 3.0 document (`openapi.yaml`) will be generated from the routes as V2 is built and committed to the repo. It is not required before implementation starts, but each module's routes should be documented in it as they are written.
|
||||
|
||||
The document is served at `/api/v1/openapi.yaml` (public, no auth). This allows easy API exploration during development and serves as integration documentation for the future iOS app.
|
||||
|
||||
---
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
| Type | Convention | Example |
|
||||
|------|------------|---------|
|
||||
| Route paths | kebab-case, plural nouns | `/api/v1/crossfit-workouts` |
|
||||
| JSON keys | camelCase | `workoutDate`, `fileSizeBytes` |
|
||||
| Query params | camelCase | `?page=1&orgId=3` |
|
||||
| Error codes | SCREAMING_SNAKE_CASE | `UPLOAD_TYPE_INVALID` |
|
||||
| Enum values in responses | PascalCase | `"status": "Scheduled"` |
|
||||
+108
-8
@@ -49,10 +49,59 @@ SQLite is appropriate for a single-gym install with < 10 concurrent users. Do no
|
||||
- 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**
|
||||
|
||||
```
|
||||
@@ -334,20 +383,69 @@ Summary:
|
||||
|
||||
## Security Checklist
|
||||
|
||||
- [ ] `helmet()` middleware on all routes
|
||||
- [ ] `express-rate-limit` on `/login` (10 req/15 min)
|
||||
- [ ] Input validation on every POST/PUT route (`zod` or `express-validator`)
|
||||
- [ ] `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
|
||||
- [ ] 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`
|
||||
- [ ] `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)
|
||||
- [ ] `.env` in `.gitignore`
|
||||
- [ ] 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.
|
||||
|
||||
---
|
||||
|
||||
@@ -364,6 +462,8 @@ Add:
|
||||
- `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()`)
|
||||
|
||||
@@ -32,12 +32,17 @@ Organizations
|
||||
├── id INTEGER PK
|
||||
├── name STRING NOT NULL "CrossFit Downtown"
|
||||
├── slug STRING UNIQUE "crossfit-downtown" (URL-safe, future subdomain use)
|
||||
├── timezone STRING DEFAULT 'UTC' IANA string e.g. "America/New_York"
|
||||
├── features TEXT (JSON array) ["client-management", "calendar"]
|
||||
├── isActive BOOLEAN DEFAULT true
|
||||
├── licenseOwner STRING contact name for the license holder
|
||||
├── licenseEmail STRING contact email for support
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
`timezone` is used server-side for any query that needs "today" relative to the gym's local time (e.g., "today's workouts"). All timestamps are still stored as UTC; this field only affects boundary calculations. See `API_STANDARDS.md` for the query pattern.
|
||||
|
||||
Notes:
|
||||
- `slug` is auto-generated from `name` on creation; can be edited by SystemAdmin
|
||||
- `features` controls which modules are accessible (see `PRODUCT_VISION.md`)
|
||||
@@ -346,3 +351,34 @@ Note: `organizationId` and `userId` on AuditLog are **not** FK-constrained (no `
|
||||
| (none) | AuditLogs | New |
|
||||
|
||||
All V1 data is preserved. New columns are nullable or have defaults so existing rows are valid without backfilling.
|
||||
|
||||
---
|
||||
|
||||
## Soft Delete Policy
|
||||
|
||||
Defines which entities use soft delete vs hard delete and what happens to related data.
|
||||
|
||||
| Entity | Delete Type | Reason |
|
||||
|--------|-------------|--------|
|
||||
| User | Soft (`isActive = false`) | Preserve audit trail, workout history, coach-client history |
|
||||
| Video | Hard delete + file removal | Files are large; no benefit to keeping orphaned video rows |
|
||||
| Category | Hard delete (guarded) | Blocked if any Video references it |
|
||||
| Workout (group) | Hard delete | Content, not records — no history value after removal |
|
||||
| Timer | Hard delete | Configuration only |
|
||||
| CrossfitWorkout | Hard delete | Content only |
|
||||
| ClientWorkout | Soft (`deletedAt` timestamp) | Part of a client's training history; coach may want to recover |
|
||||
| CalendarSession | Soft (`status = 'cancelled'`) | Already has a cancelled state; never truly deleted |
|
||||
| CoachClientLink | Soft (`isActive = false`) | Client history must remain readable after coach reassignment |
|
||||
| AuditLog | Never deleted | Immutable by design |
|
||||
|
||||
### Deleted Video + Historical Workout Integrity
|
||||
|
||||
When a Video is hard-deleted, group Workouts that reference it retain the FK values (now pointing to a deleted row). The API must handle this gracefully:
|
||||
|
||||
- `GET /api/v1/workouts` joins Videos with `LEFT JOIN` (not `INNER JOIN`) so workouts with deleted videos still appear
|
||||
- The frontend displays `[Video removed]` in place of missing video details
|
||||
- Workout functionality (display, audit history) is preserved even if the underlying video is gone
|
||||
|
||||
### Permanent Purge
|
||||
|
||||
Owners cannot permanently delete soft-deleted records through the UI. A SystemAdmin can purge via direct DB access if required (e.g., GDPR request). This is a manual operation and must be audit-logged externally (note in the customer file) since the log record cannot log its own deletion.
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
# VitFit V2 — Design System
|
||||
|
||||
## Overview
|
||||
|
||||
VitFit has two distinct UI modes that share a token foundation but diverge significantly in layout and scale.
|
||||
|
||||
| Mode | Audience | Key Concern |
|
||||
|------|----------|-------------|
|
||||
| **Management** | Coach / Owner on iPad | Touch-optimized admin, forms, navigation |
|
||||
| **Display** | Gym members via AirPlay TV | Readability at 10–20 feet, landscape, full-screen |
|
||||
|
||||
Both modes pull from the same CSS custom properties. Branding overrides only the properties listed under "Brandable Tokens." Display-mode properties are never overridden by org branding.
|
||||
|
||||
---
|
||||
|
||||
## CSS File Responsibilities
|
||||
|
||||
| File | Loaded by | Contents |
|
||||
|------|-----------|----------|
|
||||
| `base.css` | All pages | Reset, all CSS custom properties, typography helpers |
|
||||
| `layout.css` | Management pages | Shell: banner, nav drawer, main content area |
|
||||
| `components.css` | Management pages | Cards, buttons, forms, modals, toasts, badges |
|
||||
| `display.css` | Display pages only (replaces layout + components) | Full-screen display layouts, phase colors |
|
||||
|
||||
`display.css` is a **replacement**, not an addition. Display pages never load `layout.css` or `components.css`.
|
||||
|
||||
---
|
||||
|
||||
## CSS Custom Properties
|
||||
|
||||
All properties are declared on `:root` in `base.css`. Org branding applies overrides to `:root` via JavaScript on page load (see `Branding.apply()` in `core.js`).
|
||||
|
||||
### Brand Tokens (overridable per org)
|
||||
|
||||
```css
|
||||
:root {
|
||||
/* Identity */
|
||||
--brand-name: "VitFit"; /* used in JS only, not CSS */
|
||||
--color-primary: #00FF88; /* main accent: buttons, active states, highlights */
|
||||
--color-secondary: #4488FF; /* secondary accent: links, secondary actions */
|
||||
|
||||
/* Display phase colors — gym owner can customize these */
|
||||
--color-work: #00FF88; /* active work period */
|
||||
--color-rest: #4488FF; /* rest period */
|
||||
--color-move: #FF4444; /* transition / move to next station */
|
||||
--color-warning: #FFAA00; /* last 10 seconds of any phase */
|
||||
--color-complete: #FFFFFF; /* done state */
|
||||
--color-idle: #FFFFFF; /* waiting to start */
|
||||
}
|
||||
```
|
||||
|
||||
### Surface & Text Tokens (not overridable)
|
||||
|
||||
```css
|
||||
:root {
|
||||
/* Management mode surfaces */
|
||||
--surface-bg: #0f0f0f; /* page background */
|
||||
--surface-card: #1a1a1a; /* card / panel background */
|
||||
--surface-raised: #242424; /* elevated element (dropdown, modal) */
|
||||
--surface-border: #2e2e2e; /* dividers, input borders */
|
||||
--surface-hover: #2a2a2a; /* hover state on interactive surfaces */
|
||||
|
||||
/* Text */
|
||||
--text-primary: #f0f0f0; /* primary content */
|
||||
--text-secondary: #a0a0a0; /* labels, meta, timestamps */
|
||||
--text-muted: #606060; /* placeholder, disabled */
|
||||
--text-inverse: #0f0f0f; /* text on colored backgrounds */
|
||||
--text-on-primary: #0f0f0f; /* text on --color-primary backgrounds */
|
||||
|
||||
/* Semantic feedback */
|
||||
--color-success: #00FF88; /* success state — same as work by default */
|
||||
--color-danger: #FF4444; /* destructive actions, errors */
|
||||
--color-info: #4488FF; /* informational */
|
||||
--color-warning-ui: #FFAA00; /* warning banners in management UI */
|
||||
|
||||
/* Display mode — dark background, always fixed */
|
||||
--display-bg: #1a1a1a;
|
||||
--display-text: #ffffff;
|
||||
}
|
||||
```
|
||||
|
||||
### Spacing Scale
|
||||
|
||||
Base unit: 4px. All spacing values are multiples.
|
||||
|
||||
```css
|
||||
:root {
|
||||
--space-1: 4px;
|
||||
--space-2: 8px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 20px;
|
||||
--space-6: 24px;
|
||||
--space-8: 32px;
|
||||
--space-10: 40px;
|
||||
--space-12: 48px;
|
||||
--space-16: 64px;
|
||||
--space-20: 80px;
|
||||
--space-24: 96px;
|
||||
}
|
||||
```
|
||||
|
||||
### Border Radius
|
||||
|
||||
```css
|
||||
:root {
|
||||
--radius-sm: 6px; /* inputs, small badges */
|
||||
--radius-md: 10px; /* cards, buttons */
|
||||
--radius-lg: 16px; /* modals, bottom sheets */
|
||||
--radius-full: 9999px; /* pills, circular icons */
|
||||
}
|
||||
```
|
||||
|
||||
### Typography Scale — Management Mode
|
||||
|
||||
Font stack: `system-ui, -apple-system, "Segoe UI", sans-serif`
|
||||
|
||||
```css
|
||||
:root {
|
||||
--font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||
|
||||
--text-xs: 12px; /* badges, timestamps */
|
||||
--text-sm: 14px; /* secondary info, table cells */
|
||||
--text-base: 16px; /* body, form fields */
|
||||
--text-lg: 18px; /* card titles, section headers */
|
||||
--text-xl: 22px; /* page titles */
|
||||
--text-2xl: 28px; /* large headings */
|
||||
|
||||
--weight-normal: 400;
|
||||
--weight-medium: 500;
|
||||
--weight-semibold: 600;
|
||||
--weight-bold: 700;
|
||||
--weight-black: 900;
|
||||
|
||||
--line-height-tight: 1.2;
|
||||
--line-height-normal: 1.5;
|
||||
--line-height-loose: 1.75;
|
||||
}
|
||||
```
|
||||
|
||||
### Typography Scale — Display Mode
|
||||
|
||||
Sized for readability at 15 feet. These are minimums, not exact values.
|
||||
|
||||
```css
|
||||
/* In display.css */
|
||||
:root {
|
||||
--display-font-primary: 96px; /* main timer, main number */
|
||||
--display-font-secondary: 48px; /* lap count, set count, total time */
|
||||
--display-font-label: 32px; /* phase label, section headers */
|
||||
--display-font-body: 28px; /* workout item list, CrossFit items */
|
||||
}
|
||||
```
|
||||
|
||||
### Transitions
|
||||
|
||||
```css
|
||||
:root {
|
||||
--transition-fast: 100ms ease;
|
||||
--transition-base: 200ms ease;
|
||||
--transition-slow: 400ms ease;
|
||||
--transition-phase: 600ms ease; /* display mode phase color changes */
|
||||
}
|
||||
```
|
||||
|
||||
### Z-Index Scale
|
||||
|
||||
```css
|
||||
:root {
|
||||
--z-base: 1;
|
||||
--z-sticky: 10;
|
||||
--z-drawer: 100;
|
||||
--z-modal: 200;
|
||||
--z-overlay: 300; /* offline banner, session-expired overlay */
|
||||
--z-toast: 400;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Breakpoints
|
||||
|
||||
The app targets iPad in landscape as the primary viewport. Phone breakpoints are secondary.
|
||||
|
||||
```css
|
||||
/* Mobile-first — but iPad landscape is the primary target */
|
||||
/* xs: < 480px — phone portrait */
|
||||
/* sm: 480–767px — phone landscape */
|
||||
/* md: 768–1023px — iPad portrait */
|
||||
/* lg: 1024px+ — iPad landscape (primary target) */
|
||||
|
||||
@media (min-width: 768px) { /* md — iPad portrait */ }
|
||||
@media (min-width: 1024px) { /* lg — iPad landscape, primary layout */ }
|
||||
```
|
||||
|
||||
iPad landscape (1024×768 or 1194×834 depending on model) is the layout that determines form factor. Phone layouts exist for coaches checking the app on their phone but are not the primary experience.
|
||||
|
||||
---
|
||||
|
||||
## Management Shell Layout
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────┐
|
||||
│ BANNER (56px) [hamburger] [org name/logo]│
|
||||
├──────────────────────────────────────────┤
|
||||
│ │
|
||||
│ MAIN CONTENT AREA │
|
||||
│ max-width: 960px, centered, padding 24px│
|
||||
│ │
|
||||
│ │
|
||||
└──────────────────────────────────────────┘
|
||||
|
||||
NAV DRAWER (slides in from left, 280px wide)
|
||||
┌──────────┐
|
||||
│ [Logo] │
|
||||
│ [Org] │
|
||||
│──────────│
|
||||
│ Dashboard│
|
||||
│ Videos │
|
||||
│ Workouts │
|
||||
│ ... │
|
||||
│──────────│
|
||||
│ Profile │
|
||||
│ Log Out │
|
||||
└──────────┘
|
||||
```
|
||||
|
||||
**Banner:** 56px tall, `--surface-card` background, contains hamburger icon (left) and org name or logo (center or right). Sticky top.
|
||||
|
||||
**Drawer:** 280px wide, slides in with `transform: translateX(-280px)` → `translateX(0)`. Scrim overlay behind drawer (`--z-drawer`). Tap scrim or swipe left to close.
|
||||
|
||||
**Main content:** `padding: var(--space-6)` on all sides. `max-width: 960px` centered with `margin: 0 auto`. Prevents over-wide layouts on larger iPads.
|
||||
|
||||
---
|
||||
|
||||
## Component Patterns
|
||||
|
||||
### Buttons
|
||||
|
||||
Three variants:
|
||||
|
||||
```
|
||||
[Primary] — filled, --color-primary bg, --text-on-primary text
|
||||
[Secondary] — filled, --surface-raised bg, --text-primary text
|
||||
[Danger] — filled, --color-danger bg, white text
|
||||
[Ghost] — no background, --color-primary text, transparent border
|
||||
```
|
||||
|
||||
Size: minimum 44px height for touch targets (Apple HIG requirement).
|
||||
|
||||
```css
|
||||
.btn {
|
||||
height: 44px;
|
||||
padding: 0 var(--space-5);
|
||||
border-radius: var(--radius-md);
|
||||
font-size: var(--text-base);
|
||||
font-weight: var(--weight-semibold);
|
||||
cursor: pointer;
|
||||
transition: opacity var(--transition-fast);
|
||||
}
|
||||
.btn:active { opacity: 0.75; }
|
||||
.btn-primary { background: var(--color-primary); color: var(--text-on-primary); }
|
||||
.btn-secondary { background: var(--surface-raised); color: var(--text-primary); }
|
||||
.btn-danger { background: var(--color-danger); color: #fff; }
|
||||
.btn-ghost { background: transparent; color: var(--color-primary); }
|
||||
.btn-sm { height: 36px; padding: 0 var(--space-4); font-size: var(--text-sm); }
|
||||
.btn-lg { height: 52px; padding: 0 var(--space-6); font-size: var(--text-lg); }
|
||||
```
|
||||
|
||||
### Cards
|
||||
|
||||
```css
|
||||
.card {
|
||||
background: var(--surface-card);
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--surface-border);
|
||||
padding: var(--space-5);
|
||||
}
|
||||
.card-header {
|
||||
font-size: var(--text-lg);
|
||||
font-weight: var(--weight-semibold);
|
||||
color: var(--text-primary);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
.card-meta {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
```
|
||||
|
||||
### Form Fields
|
||||
|
||||
```css
|
||||
.form-field { margin-bottom: var(--space-5); }
|
||||
.form-label {
|
||||
display: block;
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--weight-medium);
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: var(--space-2);
|
||||
}
|
||||
.form-input,
|
||||
.form-select,
|
||||
.form-textarea {
|
||||
width: 100%;
|
||||
height: 44px; /* min touch target */
|
||||
padding: 0 var(--space-4);
|
||||
background: var(--surface-raised);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-primary);
|
||||
font-size: var(--text-base);
|
||||
}
|
||||
.form-textarea { height: auto; padding: var(--space-3) var(--space-4); }
|
||||
.form-input:focus,
|
||||
.form-select:focus,
|
||||
.form-textarea:focus {
|
||||
border-color: var(--color-primary);
|
||||
outline: none;
|
||||
}
|
||||
.form-error {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-danger);
|
||||
margin-top: var(--space-2);
|
||||
}
|
||||
```
|
||||
|
||||
### Badges
|
||||
|
||||
Small status indicators. Always short (1–2 words).
|
||||
|
||||
```css
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 2px var(--space-2);
|
||||
border-radius: var(--radius-full);
|
||||
font-size: var(--text-xs);
|
||||
font-weight: var(--weight-semibold);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.badge-success { background: color-mix(in srgb, var(--color-success) 15%, transparent);
|
||||
color: var(--color-success); }
|
||||
.badge-danger { background: color-mix(in srgb, var(--color-danger) 15%, transparent);
|
||||
color: var(--color-danger); }
|
||||
.badge-info { background: color-mix(in srgb, var(--color-info) 15%, transparent);
|
||||
color: var(--color-info); }
|
||||
.badge-neutral { background: var(--surface-raised); color: var(--text-secondary); }
|
||||
```
|
||||
|
||||
### Modal
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Modal Title [×] │ header, --surface-raised bg
|
||||
├─────────────────────────────────────┤
|
||||
│ Body content area │ padding 24px
|
||||
│ │
|
||||
├─────────────────────────────────────┤
|
||||
│ [Cancel] [Confirm] │ footer, right-aligned actions
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- Max width: 480px, centered horizontally
|
||||
- Fixed position, `--z-modal`
|
||||
- Scrim behind modal: `rgba(0,0,0,0.7)`, `--z-modal - 1`
|
||||
- On iPad: appears as a floating card, not a bottom sheet
|
||||
- Trap focus within modal while open (accessibility)
|
||||
|
||||
### Toast Notifications
|
||||
|
||||
Non-blocking feedback. Appear at bottom-center, auto-dismiss after 3 seconds.
|
||||
|
||||
```
|
||||
[ ✓ Workout saved successfully ] success
|
||||
[ ! Category has videos attached ] warning
|
||||
[ ✗ Upload failed: file too large ] error
|
||||
```
|
||||
|
||||
- Position: fixed, bottom-center, `--z-toast`
|
||||
- Width: max 360px
|
||||
- Stack if multiple: newest on top
|
||||
- Dismiss on tap or after 3s
|
||||
|
||||
### Progress Bar
|
||||
|
||||
Used for disk usage and upload progress.
|
||||
|
||||
```css
|
||||
.progress-bar {
|
||||
height: 8px;
|
||||
background: var(--surface-border);
|
||||
border-radius: var(--radius-full);
|
||||
overflow: hidden;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
border-radius: var(--radius-full);
|
||||
background: var(--color-primary);
|
||||
transition: width var(--transition-slow);
|
||||
}
|
||||
.progress-fill.warning { background: var(--color-warning-ui); }
|
||||
.progress-fill.danger { background: var(--color-danger); }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Display Mode
|
||||
|
||||
### Structure
|
||||
|
||||
Display pages are full-screen with no nav, no banner, and no scrolling. The entire page is one viewport.
|
||||
|
||||
```css
|
||||
/* display.css */
|
||||
body {
|
||||
background: var(--display-bg);
|
||||
color: var(--display-text);
|
||||
font-family: var(--font-family);
|
||||
width: 100vw;
|
||||
height: 100dvh; /* dvh: respects Safari dynamic toolbar */
|
||||
overflow: hidden;
|
||||
cursor: none; /* no visible cursor during display */
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
```
|
||||
|
||||
### Phase Color Application
|
||||
|
||||
Phase color is applied to text elements, not the background. Background stays `--display-bg` always.
|
||||
|
||||
```
|
||||
Work → primary text color = var(--color-work) [#00FF88 green]
|
||||
Rest → primary text color = var(--color-rest) [#4488FF blue]
|
||||
Move → primary text color = var(--color-move) [#FF4444 red]
|
||||
Idle → primary text color = var(--color-idle) [#FFFFFF white]
|
||||
Warning (last 10s) → override to var(--color-warning) [#FFAA00 amber]
|
||||
```
|
||||
|
||||
Color transitions use `transition: color var(--transition-phase)` — not background-color transitions, which can cause perceived flicker on the TV.
|
||||
|
||||
### Timer Display Layout
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────┐ 100dvh
|
||||
│ WORK LAP 1/2 SET 1/3 5ex │ 48px status bar
|
||||
│ │
|
||||
│ │
|
||||
│ 00:28 │ 96px+ timer (center)
|
||||
│ │
|
||||
│ BICEP CURLS │ 32px exercise name
|
||||
│ │
|
||||
│ Total 14:32 │ 28px total time (bottom-left)
|
||||
│ │
|
||||
│[←touch] [touch→] │ invisible 80px edge zones
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Coach touch zones (invisible, not shown on TV):
|
||||
- Left 80px strip: previous / stop
|
||||
- Right 80px strip: next
|
||||
- These are `position: absolute` overlays with `opacity: 0`
|
||||
|
||||
### Workout Display Layout
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ UPPER BODY BLAST June 11 │ status bar
|
||||
│ │
|
||||
│ Slot 1: Bench Press 10 reps │
|
||||
│ Slot 2: Dumbbell Fly 12 reps │
|
||||
│ Slot 3: Tricep Pushdown 8 reps │
|
||||
│ Slot 4: — │
|
||||
│ │
|
||||
│ [touch: close] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### CrossFit Display Layout
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ HERO WOD — MURPH June 11 │
|
||||
│ │
|
||||
│ 1. 1 mile run │
|
||||
│ 2. 100 pull-ups │
|
||||
│ 3. 200 push-ups │
|
||||
│ 4. 300 air squats │
|
||||
│ 5. 1 mile run │
|
||||
│ │
|
||||
│ [touch: close] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### AirPlay Keep-Alive Animation
|
||||
|
||||
Prevent AirPlay stream freeze with a constant imperceptible animation:
|
||||
|
||||
```css
|
||||
@keyframes keepAlive {
|
||||
0%, 100% { opacity: 0.995; }
|
||||
50% { opacity: 1.0; }
|
||||
}
|
||||
.keep-alive {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
animation: keepAlive 4s ease-in-out infinite;
|
||||
}
|
||||
```
|
||||
|
||||
`Display.startKeepAlive()` adds this element to the body on every display page load.
|
||||
|
||||
### Offline / Reconnecting Banners
|
||||
|
||||
```
|
||||
[ ⟳ Reconnecting... ] — top-center, semi-transparent, does not block content
|
||||
[ ⬡ Offline — running locally ] — corner indicator, very small, timer continues
|
||||
```
|
||||
|
||||
These are `position: fixed; z-index: var(--z-overlay)` with `pointer-events: none`.
|
||||
|
||||
---
|
||||
|
||||
## Icon Strategy
|
||||
|
||||
No icon library dependency. Use:
|
||||
- Unicode symbols for simple cases (✓ ✕ ⟳ ←)
|
||||
- Inline SVG (< 5 elements) for icons that need custom sizing/color
|
||||
- `currentColor` on SVG paths so icons inherit text color
|
||||
|
||||
No icon fonts. No external CDN icon packages.
|
||||
|
||||
---
|
||||
|
||||
## Dark Mode
|
||||
|
||||
The app is **always dark**. No light mode. The `prefers-color-scheme` media query is ignored. This is intentional: gym environments have mixed lighting, and the dark + high-contrast display theme works in all conditions.
|
||||
|
||||
---
|
||||
|
||||
## Branding Application
|
||||
|
||||
When `Branding.apply()` runs on page load, it sets these properties on `:root`:
|
||||
|
||||
```js
|
||||
// Brandable properties only — never overrides surface/text tokens
|
||||
document.documentElement.style.setProperty('--color-primary', brand.primaryColor);
|
||||
document.documentElement.style.setProperty('--color-secondary', brand.secondaryColor);
|
||||
document.documentElement.style.setProperty('--color-work', brand.workColor);
|
||||
document.documentElement.style.setProperty('--color-rest', brand.restColor);
|
||||
document.documentElement.style.setProperty('--color-move', brand.moveColor);
|
||||
document.documentElement.style.setProperty('--color-warning', brand.warningColor);
|
||||
```
|
||||
|
||||
Branding color inputs in the Owner settings panel are validated for minimum contrast ratio (4.5:1 against `--display-bg`) before saving. Colors that fail contrast are rejected with an inline warning.
|
||||
|
||||
---
|
||||
|
||||
## Accessibility Notes
|
||||
|
||||
- All touch targets: minimum 44×44px (Apple HIG)
|
||||
- Focus visible: `:focus-visible` outline uses `--color-primary`, 2px offset
|
||||
- Display mode: WCAG AA is the floor, aim for 7:1+ given viewing distance
|
||||
- Reduced motion: `@media (prefers-reduced-motion: reduce)` — collapse all transitions to 0ms except keep-alive animation (functional, not decorative)
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
transition-duration: 0ms !important;
|
||||
animation-duration: 0ms !important;
|
||||
}
|
||||
.keep-alive { animation: none; } /* keep-alive uses opacity jitter — acceptable to suppress */
|
||||
}
|
||||
```
|
||||
|
||||
Note: if `.keep-alive` is suppressed by reduced motion, add an alternative keep-alive mechanism (e.g., a `Date.now()` update on a hidden `<span>` every 10s — DOM text change keeps AirPlay active without animation).
|
||||
@@ -147,6 +147,59 @@ The iPad browser runs for 24h without refresh. This creates several failure mode
|
||||
|
||||
---
|
||||
|
||||
## Offline and Degraded Modes
|
||||
|
||||
The server is a single VPS with no redundancy. Network drops, crashes, and reboots will happen. The iPad must degrade gracefully so the gym can continue operating.
|
||||
|
||||
### State Categories
|
||||
|
||||
| State | Detection | What the iPad Shows |
|
||||
|-------|-----------|---------------------|
|
||||
| **Fully online** | Socket.io connected, API responding | Normal display |
|
||||
| **Socket disconnected, API reachable** | Socket.io disconnect event | Soft warning banner, last displayed content remains, reconnecting silently |
|
||||
| **Server unreachable** | Socket.io fails + fetch fails | "Connection lost" overlay on display; last workout content stays visible underneath |
|
||||
| **Server back online** | Socket.io reconnects | Overlay dismissed, state re-synced, no page reload required |
|
||||
|
||||
### What Stays Visible Offline
|
||||
|
||||
When the server becomes unreachable:
|
||||
- The currently-displayed workout or CrossFit list stays on screen (DOM is not cleared)
|
||||
- The TV audience continues to see workout content — the gym does not go dark
|
||||
- The "Connection lost" overlay is semi-transparent and positioned at the top edge, not obscuring the main content
|
||||
- Running timers: see below
|
||||
|
||||
### Timers During Server Disconnect
|
||||
|
||||
If a timer is running and Socket.io disconnects:
|
||||
- The client has the `endTime` timestamp it received from the server
|
||||
- The client continues the countdown locally using `Date.now()` — no server ticks needed
|
||||
- A small "Offline - running locally" indicator appears in a corner of the display
|
||||
- When reconnected, the client syncs back to the server's authoritative state
|
||||
- If the server restarted and the timer session no longer exists server-side, the local timer continues until it reaches zero, then stops normally
|
||||
|
||||
This means a running timer survives a brief server restart (PM2 restart < 30 seconds) without any visible interruption.
|
||||
|
||||
### AirPlay Drop During Active Timer
|
||||
|
||||
If the AirPlay connection itself drops (TV loses signal from iPad):
|
||||
- The iPad continues running normally — this is a display problem, not an app problem
|
||||
- The timer keeps running on the iPad
|
||||
- To reconnect: coach taps the AirPlay icon on the iPad and reconnects to the TV
|
||||
- No app restart needed; the display resumes from current state
|
||||
|
||||
### Manual Recovery Steps (for staff)
|
||||
|
||||
If the app is in an unrecoverable state on the iPad (e.g., after a very long network outage):
|
||||
|
||||
1. Tap the VitFit icon in the dock to bring it to focus
|
||||
2. If showing a broken state, pull down the refresh gesture (if visible) or close and reopen the PWA from home screen
|
||||
3. The PWA re-loads from the service worker cache (fast) and re-authenticates via device token (automatic)
|
||||
4. No coach login required; device token handles re-auth silently
|
||||
|
||||
This is the **only scenario** where a page reload is intentional. All other reconnections are handled automatically.
|
||||
|
||||
---
|
||||
|
||||
## Safari-Specific Quirks
|
||||
|
||||
| Issue | Impact | Mitigation |
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
# VitFit V2 — Operations
|
||||
|
||||
## First-Run Bootstrap
|
||||
|
||||
New deployments have no users and no open `/register`. The first Owner and SystemAdmin are created through a one-time setup script that runs before the server starts for the first time.
|
||||
|
||||
### Setup Script
|
||||
|
||||
```bash
|
||||
# On the server (via PuTTY), after deploying files and .env:
|
||||
node scripts/setup.js
|
||||
```
|
||||
|
||||
The script:
|
||||
1. Checks that the database is accessible
|
||||
2. Checks that no Organizations exist yet — if one does, it exits with an error (setup already done)
|
||||
3. Prompts for:
|
||||
- Organization name
|
||||
- Owner username
|
||||
- Owner password (typed twice; never echoed to terminal; bcrypt-hashed before storage)
|
||||
- SystemAdmin username
|
||||
- SystemAdmin password
|
||||
4. Creates the Organization, Branding (defaults), Owner user, and SystemAdmin user in a single transaction
|
||||
5. Prints a confirmation and exits
|
||||
|
||||
```js
|
||||
// scripts/setup.js
|
||||
const readline = require('readline');
|
||||
const { sequelize, Organization, User, Branding } = require('../core/db');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
async function run() {
|
||||
const orgCount = await Organization.count();
|
||||
if (orgCount > 0) {
|
||||
console.error('Setup already complete. Use the Owner panel to manage users.');
|
||||
process.exit(1);
|
||||
}
|
||||
// ... prompt and create
|
||||
}
|
||||
run();
|
||||
```
|
||||
|
||||
### After First Run
|
||||
|
||||
- The script is not deleted — but it refuses to run if any Organization exists
|
||||
- Confirm the Owner can log in at `https://yourdomain.com/` before going live
|
||||
- The SystemAdmin account should use a strong, unique password stored in a password manager — it is not used day-to-day
|
||||
|
||||
---
|
||||
|
||||
## Backup Strategy
|
||||
|
||||
### What to Back Up
|
||||
|
||||
| Item | Location | Criticality |
|
||||
|------|----------|-------------|
|
||||
| SQLite database | `/home/ubuntu/site/database.sqlite` | Critical — all data |
|
||||
| Video files | `/home/ubuntu/site/uploads/` | High — cannot be re-uploaded cheaply |
|
||||
| `.env` file | `/home/ubuntu/site/.env` | Critical — secrets, config |
|
||||
|
||||
### Automated SQLite Backup
|
||||
|
||||
SQLite's `.backup` command produces a consistent snapshot even while the database is open. A cron job runs this daily:
|
||||
|
||||
```bash
|
||||
# Add via: crontab -e
|
||||
# Runs daily at 3:00 AM
|
||||
0 3 * * * sqlite3 /home/ubuntu/site/database.sqlite ".backup '/home/ubuntu/backups/db_$(date +\%Y-\%m-\%d).sqlite'" >> /home/ubuntu/backups/backup.log 2>&1
|
||||
```
|
||||
|
||||
Backup directory: `/home/ubuntu/backups/`
|
||||
|
||||
**Retention:** Keep 14 daily backups. A cleanup line in the same cron entry:
|
||||
```bash
|
||||
0 3 * * * sqlite3 /home/ubuntu/site/database.sqlite ".backup '/home/ubuntu/backups/db_$(date +\%Y-\%m-\%d).sqlite'" && find /home/ubuntu/backups -name "db_*.sqlite" -mtime +14 -delete >> /home/ubuntu/backups/backup.log 2>&1
|
||||
```
|
||||
|
||||
### Video File Backup
|
||||
|
||||
Video files change infrequently (new uploads only). A weekly rsync to a secondary location:
|
||||
|
||||
```bash
|
||||
# Weekly on Sunday at 4:00 AM
|
||||
0 4 * * 0 rsync -a --delete /home/ubuntu/site/uploads/ /home/ubuntu/backups/uploads/ >> /home/ubuntu/backups/backup.log 2>&1
|
||||
```
|
||||
|
||||
If an offsite backup is required, WinSCP can be used manually to pull `/home/ubuntu/backups/` to a local machine. Automated offsite backup (e.g., S3) is a future enhancement.
|
||||
|
||||
### Restore Procedure
|
||||
|
||||
**Database restore:**
|
||||
```bash
|
||||
# Stop the app
|
||||
pm2 stop vitfit
|
||||
|
||||
# Replace the database (use the desired backup date)
|
||||
cp /home/ubuntu/site/database.sqlite /home/ubuntu/site/database.sqlite.pre-restore
|
||||
cp /home/ubuntu/backups/db_2025-06-10.sqlite /home/ubuntu/site/database.sqlite
|
||||
|
||||
# Restart
|
||||
pm2 start vitfit
|
||||
pm2 logs vitfit --lines 20 # verify clean start
|
||||
```
|
||||
|
||||
**Consistency note:** If restoring a database backup from day X, video files from after day X still exist on disk but their DB rows are gone — the videos will be orphaned (files exist, no DB record). This is benign; they will not appear in the UI. The converse (DB rows pointing to deleted files) cannot happen because deletes remove both.
|
||||
|
||||
**Video restore:** Copy files back from `/home/ubuntu/backups/uploads/` via WinSCP. Then re-run the sync to `uploads/`.
|
||||
|
||||
---
|
||||
|
||||
## Update / Patch Process
|
||||
|
||||
For multi-instance deployments, each customer's server must be updated separately.
|
||||
|
||||
### Routine Update Checklist (via PuTTY + WinSCP)
|
||||
|
||||
```
|
||||
1. [ ] Read the release notes — identify whether migrations run, whether .env changes are needed
|
||||
2. [ ] SSH in, take a DB backup manually:
|
||||
sqlite3 /home/ubuntu/site/database.sqlite ".backup '/home/ubuntu/backups/db_pre-update.sqlite'"
|
||||
3. [ ] WinSCP: transfer updated files (app.js, core/, modules/, public/)
|
||||
Do NOT overwrite: .env, database.sqlite, uploads/
|
||||
4. [ ] SSH: npm install (only if package.json changed)
|
||||
5. [ ] SSH: npx sequelize-cli db:migrate (only if new migrations exist; idempotent if not)
|
||||
6. [ ] SSH: pm2 restart vitfit
|
||||
7. [ ] SSH: pm2 logs vitfit --lines 30 (verify clean start)
|
||||
8. [ ] Test: log in, run a timer, check the admin panel
|
||||
9. [ ] [ ] Mark update as complete in the customer log
|
||||
```
|
||||
|
||||
### Version Numbering
|
||||
|
||||
Files released under `MAJOR.MINOR.PATCH`:
|
||||
- PATCH — bug fixes, no migration, no .env changes
|
||||
- MINOR — new features, may include migrations, .env additions documented
|
||||
- MAJOR — breaking changes, significant migrations, manual steps required
|
||||
|
||||
Version is stored in `package.json` and displayed in the SystemAdmin panel and health endpoint response.
|
||||
|
||||
### Urgent Security Patches
|
||||
|
||||
For critical vulnerabilities:
|
||||
1. Prepare the patch and test locally
|
||||
2. Notify the customer of a maintenance window (even if short)
|
||||
3. Follow the standard checklist — do not skip the DB backup step even under time pressure
|
||||
4. Document the patch in the customer's history
|
||||
|
||||
---
|
||||
|
||||
## Monitoring and Alerts
|
||||
|
||||
### PM2 Log Management
|
||||
|
||||
PM2 writes logs to `~/.pm2/logs/`. Without rotation, these grow unbounded.
|
||||
|
||||
Enable PM2 log rotation:
|
||||
```bash
|
||||
pm2 install pm2-logrotate
|
||||
pm2 set pm2-logrotate:max_size 20M
|
||||
pm2 set pm2-logrotate:retain 7
|
||||
pm2 set pm2-logrotate:compress true
|
||||
```
|
||||
|
||||
### Health Endpoint
|
||||
|
||||
`GET /health` returns:
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"uptime": 86423,
|
||||
"db": "ok",
|
||||
"diskAvailableGB": 28.4,
|
||||
"diskWarnActive": false
|
||||
}
|
||||
```
|
||||
|
||||
If the database is unreachable or disk is in warning state, `status` returns `"degraded"` (HTTP 200 still — avoids false positives from monitors that check only status codes).
|
||||
|
||||
### External Uptime Monitoring
|
||||
|
||||
Use a free uptime monitor (UptimeRobot, BetterStack free tier, or similar) pointed at `https://yourdomain.com/health`. Alert channel: email or SMS to the operator.
|
||||
|
||||
This requires no server-side work — just register the URL in the external service. Set check interval to 5 minutes.
|
||||
|
||||
### Disk Space Alert
|
||||
|
||||
The storage monitoring feature (`/admin/storage`) already flags when disk is below `STORAGE_WARN_BYTES`. For automated alerting without a user looking at the panel:
|
||||
|
||||
A PM2 cron job script can check disk space and write an alert to the app log:
|
||||
```bash
|
||||
# Check disk and log warning (runs every hour via cron)
|
||||
0 * * * * df /home/ubuntu/site/uploads/ | awk 'NR==2 {if ($5+0 > 85) print "DISK ALERT: " $5 " used on uploads partition"}' >> /home/ubuntu/site/app.log
|
||||
```
|
||||
|
||||
The uptime monitor will surface this if you configure it to scan the health endpoint for `"diskWarnActive": true`.
|
||||
|
||||
### Let's Encrypt Certificate Renewal
|
||||
|
||||
Certbot auto-renews via a systemd timer (Ubuntu 24.04 default). Verify it is active:
|
||||
```bash
|
||||
systemctl status certbot.timer
|
||||
```
|
||||
|
||||
If renewal fails, the cert expires in 90 days and the site goes HTTPS-broken — which breaks the PWA and AirPlay. Set the uptime monitor to also check the cert expiry date, or use the Certbot renewal hook to log failures to `app.log`.
|
||||
|
||||
---
|
||||
|
||||
## Support Diagnostics
|
||||
|
||||
When investigating a problem on a customer's instance, collect a support bundle:
|
||||
|
||||
```bash
|
||||
# Run on the server via PuTTY
|
||||
node scripts/support-bundle.js
|
||||
```
|
||||
|
||||
The script outputs (to stdout, safe to copy from PuTTY):
|
||||
```
|
||||
VitFit Support Bundle — 2025-06-11 14:32:01 UTC
|
||||
Version: 1.2.0
|
||||
Node: v20.11.0
|
||||
DB migrations: up to date (last: 005-add-video-mime-type)
|
||||
DB size: 14.2 MB
|
||||
Uploads size: 3.8 GB (47 files)
|
||||
Disk available: 28.1 GB
|
||||
Org count: 1
|
||||
User count: 4 (1 Owner, 2 Coach, 1 Client)
|
||||
PM2 status: online (uptime 12d 4h)
|
||||
Recent errors: [last 5 error-level log lines, redacted of PII]
|
||||
```
|
||||
|
||||
What the script does NOT include: passwords, JWT secrets, client personal data, video filenames, session notes. These are explicitly excluded in the generation script.
|
||||
|
||||
Redaction rules in `scripts/support-bundle.js`:
|
||||
- Strip any log line containing `password`, `token`, `secret`, `email`
|
||||
- Truncate any string > 100 chars in the error lines to prevent leaking session data
|
||||
|
||||
---
|
||||
|
||||
## Device Security Policy
|
||||
|
||||
### iPad Kiosk Security
|
||||
|
||||
The iPad running VitFit display is a shared device that is never turned off. Physical security is the gym owner's responsibility, but the following configuration is recommended:
|
||||
|
||||
| Setting | Recommendation |
|
||||
|---------|---------------|
|
||||
| iPad Passcode | 6-digit minimum, required for screen access |
|
||||
| Auto-Lock | 15 minutes (AirPlay keeps screen active via mirroring, so lock only triggers if AirPlay drops) |
|
||||
| Guided Access | Enable for the VitFit PWA to prevent staff accidentally navigating away or accessing iPad settings |
|
||||
| Apple ID | Registered to the gym owner (not a personal Apple ID) |
|
||||
| Find My | Enabled — required for remote wipe if stolen |
|
||||
|
||||
### Lost or Stolen iPad Response
|
||||
|
||||
1. Log in to the Owner panel from any device
|
||||
2. Navigate to Settings → Devices
|
||||
3. Revoke the device token for the lost iPad — this invalidates its silent auto-login
|
||||
4. Use Find My (icloud.com) to locate or remote-wipe the device
|
||||
5. The JWT on the stolen iPad expires within 7 days regardless; the device token revocation is immediate
|
||||
|
||||
### Device Token Rotation
|
||||
|
||||
Kiosk device tokens rotate on use: each time a device token is used to silently re-authenticate, the old token is invalidated and a new one is issued. This means a captured token can only be replayed before the iPad uses it next (typically within hours). Token rotation is automatic and transparent to the user.
|
||||
|
||||
Personal (non-kiosk) device tokens do not rotate — they are used less frequently and rely on the 30-day expiry instead.
|
||||
|
||||
### Kiosk Tokens Are Owner/Coach Only
|
||||
|
||||
Device tokens can only be created for accounts with role `Owner` or `Coach`. Client accounts cannot create device tokens — clients log in manually each session on their own devices.
|
||||
@@ -8,13 +8,17 @@ This folder contains all planning documentation for the V2 redesign.
|
||||
|----------|---------------|
|
||||
| [PRODUCT_VISION.md](PRODUCT_VISION.md) | Resale strategy, multi-instance vs SaaS decision, branding, feature tiers, roadmap phases |
|
||||
| [REQUIREMENTS.md](REQUIREMENTS.md) | What V2 must do — functional features, stability, security, and platform constraints |
|
||||
| [ROLES_AND_PERMISSIONS.md](ROLES_AND_PERMISSIONS.md) | Full role hierarchy (SystemAdmin/Owner/Coach/Client), permission matrix, UI nav by role |
|
||||
| [DATA_MODEL.md](DATA_MODEL.md) | All database entities with fields — Organizations, Users, DeviceTokens, ClientWorkouts, CalendarSessions, AuditLogs, Branding |
|
||||
| [ARCHITECTURE.md](ARCHITECTURE.md) | How to build it — stack decisions, module system, real-time strategy, storage monitoring, video streaming |
|
||||
| [ROLES_AND_PERMISSIONS.md](ROLES_AND_PERMISSIONS.md) | Full role hierarchy (SystemAdmin/Owner/Coach/Client), permission matrix, edge cases (last owner, cross-coach, client reassignment) |
|
||||
| [DATA_MODEL.md](DATA_MODEL.md) | All database entities with fields — Organizations, Users, DeviceTokens, ClientWorkouts, CalendarSessions, AuditLogs, Branding; soft delete policy |
|
||||
| [ARCHITECTURE.md](ARCHITECTURE.md) | Stack, module system, real-time, storage monitoring, video streaming, SQLite WAL config, video format constraints, path traversal protection |
|
||||
| [AUDIT_LOGS.md](AUDIT_LOGS.md) | What gets logged, event catalog, implementation pattern, API, frontend viewer |
|
||||
| [DISPLAY_DESIGN.md](DISPLAY_DESIGN.md) | iPad + Safari + AirPlay + TV specifics — PWA config, 24h session stability, typography, Safari quirks |
|
||||
| [API_STANDARDS.md](API_STANDARDS.md) | Versioning (/api/v1), error shape, pagination, date/timezone conventions, error code catalog, naming rules |
|
||||
| [DISPLAY_DESIGN.md](DISPLAY_DESIGN.md) | iPad + Safari + AirPlay + TV specifics — PWA config, 24h session stability, offline/degraded mode, typography, Safari quirks |
|
||||
| [OPERATIONS.md](OPERATIONS.md) | First-run bootstrap, backup strategy, update/patch process, monitoring, device security, support diagnostics |
|
||||
| [MIGRATION_PLAN.md](MIGRATION_PLAN.md) | How to move V1 data to V2 without loss — Sequelize migration strategy, rollback plan |
|
||||
|
||||
> [ADDITIONAL_CONSIDERATIONS.md](ADDITIONAL_CONSIDERATIONS.md) — gap analysis doc; all actionable items resolved into the documents above.
|
||||
|
||||
## Key Decisions at a Glance
|
||||
|
||||
### Product
|
||||
|
||||
@@ -232,6 +232,68 @@ Frontend hides UI elements based on role (stored in the decoded JWT payload). Bu
|
||||
|
||||
---
|
||||
|
||||
## Permission Edge Cases
|
||||
|
||||
These specific scenarios must be explicitly handled in code — they are not covered by the general permission matrix.
|
||||
|
||||
### Last Owner Protection
|
||||
|
||||
An organization must always have at least one active Owner.
|
||||
|
||||
- **Attempting to deactivate the last Owner:** Blocked. Returns `LAST_OWNER_PROTECTED` error.
|
||||
- **Attempting to demote the last Owner to Coach or Client:** Blocked. Returns `LAST_OWNER_PROTECTED` error.
|
||||
- This check applies regardless of who is making the request — even SystemAdmin cannot remove the last Owner without first creating a replacement.
|
||||
- Implementation: before any role change or deactivation of an Owner, count active Owners in the org. If count is 1 and the target is that Owner, reject.
|
||||
|
||||
### Owners Cannot Change Their Own Role
|
||||
|
||||
An Owner cannot demote themselves. They must have another Owner or SystemAdmin do it. This prevents accidental self-lockout.
|
||||
|
||||
### Coaches and Cross-Coach Content
|
||||
|
||||
Coaches can edit and delete content they created (workouts, timers, CrossFit workouts). For content created by another Coach in the same org:
|
||||
|
||||
- **Edit:** Not allowed. Returns 403.
|
||||
- **Delete:** Not allowed. Returns 403.
|
||||
- **Exception:** Owners can edit and delete any content in their org regardless of who created it.
|
||||
- The `createdByUserId` column on content tables enables this check.
|
||||
|
||||
Coaches can view all group workouts/timers/CrossFit workouts in their org — visibility is org-wide, but modification rights are creator-only (or Owner).
|
||||
|
||||
### Coach Self-Assignment of Clients
|
||||
|
||||
Whether a Coach can self-assign a client (without Owner action) is an org-level setting:
|
||||
|
||||
```
|
||||
Organizations.settings (JSON):
|
||||
{ "allowCoachSelfAssign": true } // default: false
|
||||
```
|
||||
|
||||
When `false`, only Owners (and SystemAdmins) can create CoachClientLinks. When `true`, a Coach can assign themselves to an unassigned Client.
|
||||
|
||||
A Coach can never assign a client to another Coach — that is always an Owner action.
|
||||
|
||||
### Client Reassignment
|
||||
|
||||
When a Client moves from one Coach to another:
|
||||
|
||||
1. The old CoachClientLink is deactivated (`isActive = false`) — not deleted
|
||||
2. A new CoachClientLink is created
|
||||
3. Historical ClientWorkouts retain their original `coachId` — they are not re-attributed
|
||||
4. The Client can still view their full historical workout list regardless of coach changes
|
||||
5. The new Coach can only see ClientWorkouts they created, plus all CalendarSessions going forward — not the previous Coach's private notes
|
||||
|
||||
This is logged as `coach.client.unassign` + `coach.client.assign` in the audit log.
|
||||
|
||||
### Deactivated Users
|
||||
|
||||
- Deactivated users cannot log in (401 on auth attempt)
|
||||
- Their audit log entries, created workouts, and client history are preserved
|
||||
- If a deactivated Coach had active clients, those clients become "unassigned" — they still exist and can be reassigned by an Owner
|
||||
- Deactivated users do not appear in user lists for regular roles (Owner sees them with a "Deactivated" filter)
|
||||
|
||||
---
|
||||
|
||||
## Mapping V1 Roles → V2 Roles
|
||||
|
||||
| V1 Role | V2 Role | Notes |
|
||||
|
||||
@@ -0,0 +1,982 @@
|
||||
# VitFit V2 — API Routes
|
||||
|
||||
All routes prefixed `/api/v1/`. Auth header: `Authorization: Bearer <jwt>`.
|
||||
Response envelopes: see `API_STANDARDS.md`. Dates: ISO 8601 UTC strings.
|
||||
|
||||
Legend: `[T]` = requires authenticateToken `[O]` = Owner+ `[SA]` = SystemAdmin only `[F:x]` = requires feature flag
|
||||
|
||||
---
|
||||
|
||||
## Auth — /api/v1/auth
|
||||
|
||||
### POST /api/v1/auth/login
|
||||
No auth required.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"username": "coach1",
|
||||
"password": "secret",
|
||||
"rememberDevice": true,
|
||||
"deviceName": "Gym iPad",
|
||||
"deviceType": "kiosk"
|
||||
}
|
||||
```
|
||||
`rememberDevice`, `deviceName`, `deviceType` are optional (default: no device token).
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"jwt": "eyJ...",
|
||||
"deviceToken": "a3f9...",
|
||||
"user": { "id": 1, "username": "coach1", "role": "Coach", "firstName": "Jason", "organizationId": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
`deviceToken` only present when `rememberDevice: true`. Store in localStorage as `deviceToken`.
|
||||
|
||||
Errors: `LOGIN_FAILED` (401), rate-limited after 10 attempts/15 min (429).
|
||||
|
||||
Two independent rate limits apply:
|
||||
- **Per-IP** — `express-rate-limit` middleware, 10 req/15 min per source IP.
|
||||
- **Per-username** — tracked in process memory by auth service. 10 failed attempts for the
|
||||
same `username` string within 15 minutes triggers immediate `LOGIN_FAILED` regardless of IP.
|
||||
Resets automatically on success or after 15 minutes. Prevents targeted account brute-force
|
||||
from rotating IPs.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/auth/device-login
|
||||
No auth required. Used on page load to silently re-authenticate.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{ "deviceToken": "a3f9..." }
|
||||
```
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"jwt": "eyJ...",
|
||||
"deviceToken": "b7e2...",
|
||||
"user": { "id": 1, "username": "coach1", "role": "Coach", "organizationId": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
Old token is invalidated. New token replaces it in localStorage.
|
||||
|
||||
Errors: `AUTH_DEVICE_TOKEN_INVALID` (401).
|
||||
|
||||
Rate limited: same 10 req/15 min per-IP limiter as `/auth/login`. The token search space
|
||||
(32-byte random = 2²⁵⁶) makes brute force computationally infeasible; rate limiting prevents
|
||||
server load abuse and probing.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/auth/refresh-token
|
||||
`[T]`
|
||||
|
||||
No request body. Called by `core.js` when token is within 1 hour of expiry.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{ "data": { "jwt": "eyJ..." } }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/auth/logout
|
||||
`[T]`
|
||||
|
||||
No request body. Logs audit event. JWT invalidation is client-side (delete from localStorage).
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## Users — /api/v1/users
|
||||
|
||||
### GET /api/v1/users
|
||||
`[T]` `[O]`
|
||||
|
||||
Query: `?role=Coach&isActive=true&page=1&limit=50`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 2, "username": "jsmith", "email": "j@gym.com", "firstName": "John", "lastName": "Smith",
|
||||
"role": "Coach", "isActive": true, "lastLoginAt": "2025-06-10T14:22:00.000Z" }
|
||||
],
|
||||
"meta": { "total": 4, "page": 1, "limit": 50, "totalPages": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/users
|
||||
`[T]` `[O]`
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"username": "newcoach",
|
||||
"email": "coach@gym.com",
|
||||
"firstName": "Mike",
|
||||
"lastName": "Jones",
|
||||
"password": "initialPass123",
|
||||
"role": "Coach"
|
||||
}
|
||||
```
|
||||
`email`, `firstName`, `lastName` optional. `role` must be `Owner`, `Coach`, or `Client`.
|
||||
|
||||
Response 201: `{ "data": { ...user } }`
|
||||
|
||||
Errors: `CONFLICT` (409 duplicate username), `VALIDATION_FAILED` (400).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/users/:id
|
||||
`[T]` `[O]`
|
||||
|
||||
Response 200: `{ "data": { ...user, deviceTokens: [ { id, deviceName, deviceType, lastUsedAt, expiresAt } ] } }`
|
||||
|
||||
Errors: `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/users/:id
|
||||
`[T]` Own profile only (any role) OR `[O]` for any user in org.
|
||||
|
||||
Request (any subset):
|
||||
```json
|
||||
{ "firstName": "Jason", "lastName": "A", "email": "new@email.com" }
|
||||
```
|
||||
|
||||
Response 200: `{ "data": { ...updatedUser } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/users/:id
|
||||
`[T]` `[O]`
|
||||
|
||||
Soft deactivate. Not a true delete.
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `LAST_OWNER_PROTECTED` (400), `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
### PUT /api/v1/users/:id/role
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "role": "Owner" }`
|
||||
|
||||
Response 200: `{ "data": { ...user } }`
|
||||
|
||||
Errors: `LAST_OWNER_PROTECTED` (400), `AUTH_FORBIDDEN` (403 if Owner tries to self-change).
|
||||
|
||||
---
|
||||
|
||||
### PUT /api/v1/users/:id/password
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "newPassword": "newPass456" }`
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/users/:id/devices
|
||||
`[T]` Own devices (any role) OR `[O]` for any user in org.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 3, "deviceName": "Gym iPad", "deviceType": "kiosk",
|
||||
"lastUsedAt": "2025-06-11T08:00:00.000Z", "expiresAt": "2025-09-09T08:00:00.000Z" }
|
||||
]
|
||||
}
|
||||
```
|
||||
Token hash is never returned.
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/users/:id/devices/:tokenId
|
||||
`[T]` Own devices (any role) OR `[O]`.
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## Organization — /api/v1/org
|
||||
|
||||
### GET /api/v1/org
|
||||
`[T]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 1, "name": "CrossFit Downtown", "slug": "crossfit-downtown",
|
||||
"timezone": "America/New_York", "features": ["client-management", "calendar"],
|
||||
"licenseOwner": "Jason A", "licenseEmail": "jason@gym.com"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/org
|
||||
`[T]` `[O]`
|
||||
|
||||
Request (any subset): `{ "name": "CrossFit Uptown", "timezone": "America/Chicago" }`
|
||||
|
||||
Response 200: `{ "data": { ...org } }`
|
||||
|
||||
Errors: `VALIDATION_FAILED` (400 invalid timezone).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/org/branding
|
||||
`[T]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"appName": "CrossFit Downtown",
|
||||
"logoPath": "/api/v1/org/logo",
|
||||
"primaryColor": "#00FF88",
|
||||
"secondaryColor": "#4488FF",
|
||||
"workColor": "#00FF88",
|
||||
"restColor": "#4488FF",
|
||||
"moveColor": "#FF4444"
|
||||
}
|
||||
}
|
||||
```
|
||||
`logoPath` is `null` if no custom logo.
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/org/branding
|
||||
`[T]` `[O]`
|
||||
|
||||
Request (any subset):
|
||||
```json
|
||||
{ "appName": "My Gym", "primaryColor": "#FF0066", "workColor": "#FF0066" }
|
||||
```
|
||||
|
||||
Response 200: `{ "data": { ...branding } }`
|
||||
|
||||
Errors: `VALIDATION_FAILED` (400, lists each color that fails contrast check).
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/org/logo
|
||||
`[T]` `[O]`
|
||||
|
||||
Body: `multipart/form-data`, field `logo` (image file).
|
||||
|
||||
Response 200: `{ "data": { "logoPath": "/api/v1/org/logo" } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/org/logo
|
||||
`[T]`
|
||||
|
||||
Streams logo file. Returns 404 if no custom logo set.
|
||||
|
||||
---
|
||||
|
||||
## Videos — /api/v1/videos
|
||||
|
||||
### GET /api/v1/videos
|
||||
`[T]` Coaches and above.
|
||||
|
||||
Query: `?category=Arm+Exercises&page=1&limit=50`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 5, "filename": "1718000000_abc123.mp4", "description": "Barbell curl",
|
||||
"category": "Arm Exercises", "mimeType": "video/mp4",
|
||||
"fileSizeBytes": 45020000, "createdAt": "2025-06-01T12:00:00.000Z",
|
||||
"streamUrl": "/api/v1/videos/stream/1718000000_abc123.mp4" }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
`streamUrl` is included so the frontend doesn't need to construct URLs.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/videos
|
||||
`[T]` Coach+.
|
||||
|
||||
Body: `multipart/form-data`. Fields: `video` (file), `description` (string), `category` (string).
|
||||
|
||||
Pre-upload middleware: `checkUploadAllowed` (507 if disk low), multer file size limit.
|
||||
|
||||
Response 201: `{ "data": { ...video, streamUrl } }`
|
||||
|
||||
Errors: `UPLOAD_TYPE_INVALID` (400), `UPLOAD_SIZE_EXCEEDED` (400), `STORAGE_INSUFFICIENT` (507).
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/videos/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/videos/stream/:filename
|
||||
`[T]`
|
||||
|
||||
Streams video file. Supports `Range` header for seek (required by Safari).
|
||||
|
||||
Response 200 (full) or 206 (partial/range).
|
||||
Headers include `Accept-Ranges: bytes`, `Content-Type` from stored mimeType.
|
||||
|
||||
Errors: `NOT_FOUND` (404 — file not in DB for this org, or doesn't exist on disk).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/categories
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": [ { "id": 1, "name": "Arm Exercises" }, ... ] }`
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/categories
|
||||
`[T]` Coach+.
|
||||
|
||||
Request: `{ "name": "Mobility" }`
|
||||
|
||||
Response 201: `{ "data": { "id": 7, "name": "Mobility" } }`
|
||||
|
||||
Errors: `CONFLICT` (409).
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/categories/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `CONFLICT` (409 if videos exist in this category), `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
## Workouts (Group Display) — /api/v1/workouts
|
||||
|
||||
### GET /api/v1/workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Query: `?page=1&limit=20`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 10, "name": "Tuesday WOD", "workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"createdByUserId": 2,
|
||||
"videos": [
|
||||
{ "slot": 1, "video": { "id": 5, "description": "Barbell curl", "streamUrl": "..." }, "reps": 10 },
|
||||
{ "slot": 2, "video": null, "reps": null }
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
`video: null` when the referenced video has been deleted.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "Tuesday WOD",
|
||||
"workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"video1": 5, "number1": 10,
|
||||
"video2": 8, "number2": 12,
|
||||
"video3": null, "number3": null,
|
||||
"video4": null, "number4": null
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...workout with videos } }`
|
||||
|
||||
Errors: `VALIDATION_FAILED` (400, video IDs not in org).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/workouts/today
|
||||
`[T]` Coach+.
|
||||
|
||||
No query params. Uses org timezone for "today" calculation.
|
||||
|
||||
Response 200 (collection — same shape as GET /workouts).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/workouts/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": { ...workout with videos } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/workouts/:id
|
||||
`[T]` Coach (own only) or Owner (any).
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `AUTH_FORBIDDEN` (403 if Coach tries to delete another's workout), `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
## Timers — /api/v1/timers
|
||||
|
||||
### GET /api/v1/timers
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 3, "name": "HIIT 30/10", "totalTime": 1800, "setTime": 30, "restTime": 10,
|
||||
"moveTime": 15, "setCount": 3, "exerciseCount": 5, "lapCount": 2 }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/timers
|
||||
`[T]` Coach+.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "HIIT 30/10",
|
||||
"totalTime": 1800, "setTime": 30, "restTime": 10, "moveTime": 15,
|
||||
"setCount": 3, "exerciseCount": 5, "lapCount": 2
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...timer } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/timers/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": { ...timer } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/timers/:id
|
||||
`[T]` Coach (own) or Owner.
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/timers/:id/launch
|
||||
`[T]` Coach+.
|
||||
|
||||
No request body.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{ "data": { "sessionId": "timer_3_1718273400000" } }
|
||||
```
|
||||
Client uses `sessionId` to join the Socket.io room.
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/timers/session
|
||||
`[T]` Coach+.
|
||||
|
||||
Request: `{ "sessionId": "timer_3_1718273400000" }`
|
||||
|
||||
Stops the active timer session.
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## CrossFit Workouts — /api/v1/crossfit-workouts
|
||||
|
||||
### GET /api/v1/crossfit-workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Query: `?page=1&limit=20`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 7, "name": "Hero WOD Murph", "workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"workoutItems": ["1 mile run", "100 pull-ups", "200 push-ups", "300 squats", "1 mile run"],
|
||||
"createdByUserId": 2 }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/crossfit-workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "Hero WOD Murph",
|
||||
"workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"workoutItems": ["1 mile run", "100 pull-ups", "200 push-ups"]
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...crossfitWorkout } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/crossfit-workouts/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": { ...crossfitWorkout } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/crossfit-workouts/:id
|
||||
`[T]` `[O]`
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## Clients — /api/v1/clients
|
||||
|
||||
`[F:client-management]` All client endpoints require this feature flag.
|
||||
|
||||
### GET /api/v1/clients
|
||||
`[T]` Coach (own clients) or Owner (all).
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 9, "username": "athlete1", "firstName": "Sara", "lastName": "Kim",
|
||||
"email": "sara@email.com", "isActive": true,
|
||||
"coach": { "id": 2, "firstName": "John", "lastName": "Smith" } }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients
|
||||
`[T]` `[O]` or Coach if org allows self-assign.
|
||||
|
||||
Creates a new Client user and optionally assigns a coach.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"username": "athlete2",
|
||||
"firstName": "Tom",
|
||||
"lastName": "Brady",
|
||||
"email": "tom@email.com",
|
||||
"password": "initialPass",
|
||||
"coachId": 2
|
||||
}
|
||||
```
|
||||
`coachId` optional.
|
||||
|
||||
Response 201: `{ "data": { ...user, coachLink? } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id
|
||||
`[T]` Coach (own clients only) or Owner.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 9, "username": "athlete1", "firstName": "Sara", "lastName": "Kim",
|
||||
"coach": { "id": 2, "firstName": "John" },
|
||||
"upcomingSessionsCount": 3,
|
||||
"pendingWorkoutsCount": 2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/assign
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "coachId": 3 }`
|
||||
|
||||
Response 200: `{ "data": { "linkId": 14, "coachId": 3, "clientId": 9, "assignedAt": "..." } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/clients/:id/assign
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "linkId": 14 }`
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id/workouts
|
||||
`[T]` Coach (own clients) or Client (own) or Owner.
|
||||
|
||||
Query: `?page=1&limit=20&includeCompleted=false`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 22, "name": "Monday Strength", "scheduledDate": "2025-06-12T00:00:00.000Z",
|
||||
"completedAt": null, "coachId": 2,
|
||||
"items": [
|
||||
{ "type": "video", "videoId": 5, "reps": 10, "sets": 3, "notes": "Full ROM",
|
||||
"streamUrl": "/api/v1/videos/stream/..." },
|
||||
{ "type": "text", "text": "Rest 2 min between sets" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/workouts
|
||||
`[T]` Coach (own clients only).
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "Monday Strength",
|
||||
"scheduledDate": "2025-06-12T00:00:00.000Z",
|
||||
"notes": "Focus on form today.",
|
||||
"items": [
|
||||
{ "type": "video", "videoId": 5, "reps": 10, "sets": 3, "notes": "Full ROM" },
|
||||
{ "type": "text", "text": "Rest 2 min" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...clientWorkout } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id/workouts/:workoutId
|
||||
`[T]` Coach (own clients) or Client (own) or Owner.
|
||||
|
||||
Response 200: `{ "data": { ...clientWorkout with items } }`
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/clients/:id/workouts/:workoutId
|
||||
`[T]` Coach (own clients only).
|
||||
|
||||
Request: any subset of `{ name, scheduledDate, notes, items }`.
|
||||
|
||||
Response 200: `{ "data": { ...updated } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/clients/:id/workouts/:workoutId
|
||||
`[T]` Coach (own clients only).
|
||||
|
||||
Soft delete. Response 204.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/workouts/:workoutId/complete
|
||||
`[T]` Coach (own clients) or Client (own).
|
||||
|
||||
No request body.
|
||||
|
||||
Response 200: `{ "data": { "completedAt": "2025-06-12T09:30:00.000Z" } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id/sessions
|
||||
`[T]` Coach (own clients) or Client (own) or Owner.
|
||||
|
||||
Query: `?startAfter=2025-06-01&endBefore=2025-06-30&status=Scheduled&page=1&limit=20`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 31, "title": "Weekly Check-in", "sessionType": "Personal",
|
||||
"startAt": "2025-06-12T09:00:00.000Z", "endAt": "2025-06-12T10:00:00.000Z",
|
||||
"status": "Scheduled", "locationNotes": "Gym Floor B",
|
||||
"sharedNotes": "Bring your training log",
|
||||
"linkedWorkoutId": 22 }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
`coachNotes` is stripped when requester is the Client.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/sessions
|
||||
`[T]` Coach (own clients).
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"title": "Weekly Check-in",
|
||||
"sessionType": "personal",
|
||||
"startAt": "2025-06-12T09:00:00.000Z",
|
||||
"endAt": "2025-06-12T10:00:00.000Z",
|
||||
"locationNotes": "Gym Floor B",
|
||||
"coachNotes": "Client struggling with squat depth",
|
||||
"sharedNotes": "Bring your training log",
|
||||
"linkedWorkoutId": 22
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...session } }`
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/clients/:id/sessions/:sessionId
|
||||
`[T]` Coach (own) or Client (limited fields only).
|
||||
|
||||
Response 200: `{ "data": { ...updated } }`
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/sessions/:sessionId/cancel
|
||||
`[T]` Coach or Client.
|
||||
|
||||
Response 200: `{ "data": { "status": "Cancelled" } }`
|
||||
|
||||
Errors: `CANCELLATION_TOO_LATE` (400) — Client attempting to cancel a session that starts in
|
||||
less than 24 hours. Coaches and Owners are not subject to this restriction.
|
||||
|
||||
---
|
||||
|
||||
## My (Client Self-Service) — /api/v1/my
|
||||
|
||||
### GET /api/v1/my/workouts
|
||||
`[T]` Client role only.
|
||||
|
||||
Alias for `GET /api/v1/clients/:ownId/workouts` scoped to the requesting client.
|
||||
|
||||
Response: same collection shape as client workouts.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/my/sessions
|
||||
`[T]` Client role only.
|
||||
|
||||
Alias for `GET /api/v1/clients/:ownId/sessions`.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/my/profile
|
||||
`[T]` Any role.
|
||||
|
||||
Returns own user record. Alias for `GET /api/v1/users/:ownId`.
|
||||
|
||||
---
|
||||
|
||||
### PUT /api/v1/my/password
|
||||
`[T]` Any role.
|
||||
|
||||
Allows any authenticated user to change their own password after verifying the current one.
|
||||
Owner-managed `PUT /api/v1/users/:id/password` does not require the current password;
|
||||
this endpoint does.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{ "currentPassword": "oldPass123", "newPassword": "newPass456" }
|
||||
```
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `AUTH_FORBIDDEN` (401 if `currentPassword` does not match stored hash), `VALIDATION_FAILED` (400).
|
||||
|
||||
---
|
||||
|
||||
## Calendar (Coach View) — /api/v1/calendar
|
||||
|
||||
### GET /api/v1/calendar
|
||||
`[T]` Coach+. `[F:calendar]`
|
||||
|
||||
Query: `?startAfter=2025-06-01&endBefore=2025-06-30`
|
||||
|
||||
Returns all sessions for the coach across all their clients, aggregated.
|
||||
|
||||
Response 200 (collection of CalendarSession).
|
||||
|
||||
**Phase 2 deferrals:** Conflict detection (overlapping sessions for same coach) and recurring
|
||||
sessions (RRULE / weekly repeat) are not implemented in V2 MVP. Every session is a standalone
|
||||
record. The API accepts overlapping bookings without error.
|
||||
|
||||
---
|
||||
|
||||
## Admin — /api/v1/admin
|
||||
|
||||
### GET /api/v1/admin/storage
|
||||
`[T]` `[O]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"disk": { "total": 53687091200, "used": 21474836480, "free": 32212254720, "usedPercent": 40 },
|
||||
"uploads": { "size": 4831838208, "fileCount": 47 },
|
||||
"warning": false,
|
||||
"warnThresholdBytes": 5368709120
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Audit Logs — /api/v1/audit-logs
|
||||
|
||||
### GET /api/v1/audit-logs
|
||||
`[T]` `[O]`
|
||||
|
||||
Query: `?action=video.upload&userId=2&entityType=video&from=2025-06-01&to=2025-06-30&page=1&limit=50`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 204, "userId": 2, "userRole": "Coach", "action": "video.upload",
|
||||
"entityType": "video", "entityId": 15,
|
||||
"details": { "filename": "1718...", "category": "Arm Exercises", "fileSizeBytes": 45020000 },
|
||||
"ipAddress": "192.168.1.5", "createdAt": "2025-06-11T14:23:00.000Z" }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/audit-logs/export
|
||||
`[T]` `[O]`
|
||||
|
||||
Same query params as GET. Returns CSV stream.
|
||||
|
||||
Response headers:
|
||||
```
|
||||
Content-Type: text/csv
|
||||
Content-Disposition: attachment; filename="audit-log-2025-06-11.csv"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## System Admin — /api/v1/sysadmin
|
||||
|
||||
### GET /api/v1/sysadmin/orgs
|
||||
`[T]` `[SA]`
|
||||
|
||||
Response 200: All organizations with user count summary.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/sysadmin/orgs/:id
|
||||
`[T]` `[SA]`
|
||||
|
||||
Response 200: Full org detail, branding, user list.
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/sysadmin/orgs/:id
|
||||
`[T]` `[SA]`
|
||||
|
||||
Request: any subset of `{ name, timezone, features, isActive, licenseOwner, licenseEmail }`.
|
||||
|
||||
Response 200: `{ "data": { ...org } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/sysadmin/health
|
||||
`[T]` `[SA]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"nodeVersion": "v20.11.0",
|
||||
"uptime": 86423,
|
||||
"db": { "status": "ok", "lastMigration": "005-add-video-mime-type" },
|
||||
"disk": { "free": 32212254720, "usedPercent": 40 },
|
||||
"activeTimerSessions": 0,
|
||||
"orgCount": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Health (No Auth)
|
||||
|
||||
### GET /health
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"uptime": 86423,
|
||||
"db": "ok",
|
||||
"diskAvailableGB": 30.0,
|
||||
"diskWarnActive": false
|
||||
}
|
||||
```
|
||||
Returns `"status": "degraded"` (still HTTP 200) if DB unreachable or disk in warning state.
|
||||
|
||||
---
|
||||
|
||||
## OpenAPI Spec
|
||||
|
||||
### GET /api/v1/openapi.yaml
|
||||
No auth required.
|
||||
|
||||
Returns the OpenAPI 3.0 spec for this API as a YAML file.
|
||||
Generated from code comments or a hand-maintained `openapi.yaml` in the project root.
|
||||
|
||||
Response headers:
|
||||
```
|
||||
Content-Type: application/yaml
|
||||
```
|
||||
|
||||
This endpoint is mentioned in `API_STANDARDS.md` as the authoritative spec location.
|
||||
@@ -0,0 +1,887 @@
|
||||
# VitFit V2 — Backend Method Maps
|
||||
|
||||
TypeScript-style signatures are used for clarity. The implementation is JavaScript (CommonJS).
|
||||
`Promise<T>` return types indicate async functions. All service functions throw `AppError` on failure.
|
||||
|
||||
---
|
||||
|
||||
## core/db.js
|
||||
|
||||
```js
|
||||
initDb(): Promise<Sequelize>
|
||||
```
|
||||
Creates Sequelize instance. Runs PRAGMAs. Returns sequelize.
|
||||
```
|
||||
PRAGMA journal_mode = WAL
|
||||
PRAGMA busy_timeout = 5000
|
||||
PRAGMA foreign_keys = ON
|
||||
```
|
||||
|
||||
```js
|
||||
runMigrations(): Promise<void>
|
||||
```
|
||||
Programmatically runs all pending sequelize-cli migrations in `modules/*/migrations/`.
|
||||
|
||||
```js
|
||||
models: {
|
||||
Organization, Branding,
|
||||
User, DeviceToken,
|
||||
Video, Category,
|
||||
Workout,
|
||||
Timer,
|
||||
CrossfitWorkout,
|
||||
CoachClientLink, ClientWorkout, CalendarSession,
|
||||
AuditLog
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## core/auth.js
|
||||
|
||||
```js
|
||||
authenticateToken(req, res, next): void
|
||||
```
|
||||
Reads `Authorization: Bearer <token>`. Verifies JWT against `JWT_SECRET` with algorithm
|
||||
pinned to `HS256`:
|
||||
```js
|
||||
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, (err, decoded) => { ... });
|
||||
```
|
||||
Algorithm pinning prevents RS256/none algorithm confusion attacks.
|
||||
|
||||
After signature verification, fetches the user row to check `passwordChangedAt`:
|
||||
```js
|
||||
if (user.passwordChangedAt && decoded.iat * 1000 < user.passwordChangedAt.getTime()) {
|
||||
return next(new AppError('AUTH_INVALID', 'Token issued before last password change.', 401));
|
||||
}
|
||||
```
|
||||
This ensures that tokens issued before a password change are rejected, even within their 7-day TTL.
|
||||
|
||||
Sets `req.user = { id, username, role, organizationId }` on success.
|
||||
Calls `next()` on success. Returns `AppError('AUTH_REQUIRED', ..., 401)` if no token,
|
||||
`AppError('AUTH_INVALID', ..., 401)` on invalid or pre-password-change token.
|
||||
|
||||
```js
|
||||
authenticateRole(roles: string[]): Middleware
|
||||
```
|
||||
Returns middleware. Checks `req.user.role` is in `roles`.
|
||||
Returns `AppError('AUTH_FORBIDDEN', ..., 403)` if not.
|
||||
Usage: `router.delete('/:id', authenticateToken, authenticateRole(['Owner', 'SystemAdmin']), handler)`
|
||||
|
||||
```js
|
||||
requireFeature(feature: string): Middleware
|
||||
```
|
||||
Returns middleware. Fetches org features from DB (cached 5 min per orgId).
|
||||
Returns `AppError('FEATURE_DISABLED', ..., 403)` if feature not in org's features array.
|
||||
Usage: `router.post('/', authenticateToken, requireFeature('client-management'), handler)`
|
||||
|
||||
---
|
||||
|
||||
## core/audit.js
|
||||
|
||||
```js
|
||||
log(
|
||||
req: Request,
|
||||
action: string,
|
||||
entityType: string | null,
|
||||
entityId: number | null,
|
||||
details: object
|
||||
): Promise<void>
|
||||
```
|
||||
Creates one AuditLog row. `req.user` provides userId, userRole, organizationId.
|
||||
`req.ip` and `req.get('User-Agent')` provide client info.
|
||||
On DB error: logs via pino at `warn` level and swallows — audit failure must never break the request.
|
||||
|
||||
---
|
||||
|
||||
## core/storage.js
|
||||
|
||||
```js
|
||||
getStorageInfo(): Promise<StorageInfo>
|
||||
```
|
||||
Returns:
|
||||
```js
|
||||
{
|
||||
disk: { total: number, used: number, free: number, usedPercent: number },
|
||||
uploads: { size: number, fileCount: number },
|
||||
warning: boolean // true when free < STORAGE_WARN_BYTES
|
||||
}
|
||||
```
|
||||
Result is cached for 60 seconds. Thread-safe: subsequent calls while in-flight share the same Promise.
|
||||
|
||||
```js
|
||||
checkUploadAllowed(req, res, next): Promise<void>
|
||||
```
|
||||
Middleware. Calls `getStorageInfo()`. Throws `AppError('STORAGE_INSUFFICIENT', ..., 507)` if `warning`.
|
||||
Applied to all upload routes before multer.
|
||||
|
||||
```js
|
||||
getUploadsSize(): Promise<{ size: number, fileCount: number }>
|
||||
```
|
||||
Internal. Reads `UPLOADS_DIR` synchronously (blocking but fast for < 1000 files),
|
||||
sums `stat.size` of each file. Returns totals.
|
||||
|
||||
---
|
||||
|
||||
## core/socket.js
|
||||
|
||||
```js
|
||||
init(httpServer: HttpServer): SocketIoServer
|
||||
```
|
||||
Attaches Socket.io to the HTTP server. Configures CORS. Registers `connection` handler.
|
||||
On `connection`: authenticates socket via JWT passed in `auth.token` handshake data.
|
||||
If auth fails, disconnects with error. Sets `socket.data.user` on success.
|
||||
Returns the `io` instance.
|
||||
|
||||
```js
|
||||
getIo(): SocketIoServer
|
||||
```
|
||||
Returns the singleton `io`. Throws if `init()` has not been called.
|
||||
|
||||
---
|
||||
|
||||
## core/errors.js
|
||||
|
||||
```js
|
||||
class AppError extends Error {
|
||||
constructor(code: string, message: string, status: number, field?: string)
|
||||
code: string
|
||||
status: number
|
||||
field: string | null
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
errorHandler(err, req, res, next): void
|
||||
```
|
||||
Express `(err, req, res, next)` middleware. Last middleware in `app.js`.
|
||||
If `err instanceof AppError`: responds with standard error envelope at `err.status`.
|
||||
Otherwise: logs at `error` level, responds 500 with generic message (hides internals in production).
|
||||
|
||||
---
|
||||
|
||||
## core/respond.js
|
||||
|
||||
```js
|
||||
ok(res: Response, data: object): void
|
||||
```
|
||||
Sends `200 { "data": data }`.
|
||||
|
||||
```js
|
||||
created(res: Response, data: object): void
|
||||
```
|
||||
Sends `201 { "data": data }`.
|
||||
|
||||
```js
|
||||
collection(res: Response, data: any[], total: number, page: number, limit: number): void
|
||||
```
|
||||
Sends `200 { "data": [...], "meta": { total, page, limit, totalPages } }`.
|
||||
|
||||
```js
|
||||
noContent(res: Response): void
|
||||
```
|
||||
Sends `204` with no body.
|
||||
|
||||
```js
|
||||
err(res: Response, code: string, message: string, status: number, field?: string): void
|
||||
```
|
||||
Sends `status { "error": { code, message, field } }`.
|
||||
|
||||
---
|
||||
|
||||
## modules/auth/service.js
|
||||
|
||||
```js
|
||||
login(
|
||||
username: string,
|
||||
password: string,
|
||||
rememberDevice: boolean,
|
||||
deviceName: string,
|
||||
deviceType: 'kiosk' | 'personal'
|
||||
): Promise<{ jwt: string, deviceToken?: string, user: UserPublic }>
|
||||
```
|
||||
**Per-username lockout (in addition to per-IP rate limit on the route):**
|
||||
Maintains a `Map<username, { count, resetAt }>` in process memory. On each failed attempt,
|
||||
increments the counter for that username. If `count >= 10` and `resetAt > Date.now()`, throws
|
||||
`AppError('LOGIN_FAILED', ..., 401)` immediately without hitting the DB. Resets automatically
|
||||
after 15 minutes. This prevents targeted account brute-force from IPs that rotate.
|
||||
|
||||
Finds User by username. Checks `isActive`. Compares password with bcrypt.
|
||||
On any failure: throws `AppError('LOGIN_FAILED', ..., 401)` — same error for unknown username,
|
||||
wrong password, and inactive account (no enumeration).
|
||||
On success: clears per-username failure counter. Signs JWT (7-day), creates DeviceToken if
|
||||
`rememberDevice`. Updates `lastLoginAt`. Logs `auth.login.success` audit event.
|
||||
|
||||
```js
|
||||
deviceLogin(
|
||||
rawToken: string,
|
||||
ipAddress: string,
|
||||
userAgent: string
|
||||
): Promise<{ jwt: string, newDeviceToken: string }>
|
||||
```
|
||||
Route-level rate limiter applied to `POST /auth/device-login` — same 10 req/15 min per-IP
|
||||
limiter as `/auth/login`. The token search space (32-byte random hex = 2²⁵⁶) makes brute force
|
||||
computationally infeasible, but rate limiting prevents this endpoint from being used as an
|
||||
amplification vector or server load probe.
|
||||
|
||||
Hashes `rawToken`. Finds DeviceToken by hash. Validates not revoked, not expired.
|
||||
Issues new JWT. Rotates device token (old revoked, new created with same TTL).
|
||||
Logs `auth.token.refreshed`. Returns new JWT + new raw device token.
|
||||
|
||||
```js
|
||||
refreshToken(userId: number): Promise<{ jwt: string }>
|
||||
```
|
||||
Signs a fresh JWT for the given userId. Called automatically when token < 1 hour from expiry.
|
||||
|
||||
```js
|
||||
createDeviceToken(
|
||||
userId: number,
|
||||
orgId: number,
|
||||
deviceName: string,
|
||||
deviceType: 'kiosk' | 'personal'
|
||||
): Promise<{ rawToken: string, record: DeviceToken }>
|
||||
```
|
||||
Generates `crypto.randomBytes(32).toString('hex')` as raw token.
|
||||
Stores bcrypt hash in DB. TTL: 90 days for kiosk, 30 days for personal.
|
||||
Returns raw token (only time it's in plaintext — not stored anywhere else).
|
||||
|
||||
```js
|
||||
hashToken(rawToken: string): string
|
||||
```
|
||||
Returns `crypto.createHash('sha256').update(rawToken).digest('hex')`.
|
||||
SHA-256 (not bcrypt) for token lookup — device tokens are long random strings, no need for bcrypt cost.
|
||||
|
||||
---
|
||||
|
||||
## modules/users/service.js
|
||||
|
||||
```js
|
||||
getUsers(
|
||||
orgId: number,
|
||||
filters: { role?: string, isActive?: boolean, page?: number, limit?: number }
|
||||
): Promise<{ rows: User[], count: number }>
|
||||
```
|
||||
Returns paginated users for the org. SystemAdmin can pass `orgId = null` to query across orgs.
|
||||
|
||||
```js
|
||||
getUserById(id: number, orgId: number): Promise<User>
|
||||
```
|
||||
Finds user by id within orgId. Throws `AppError('NOT_FOUND', ..., 404)` if not found.
|
||||
|
||||
```js
|
||||
createUser(
|
||||
orgId: number,
|
||||
data: { username, email?, firstName?, lastName?, password, role },
|
||||
actorId: number
|
||||
): Promise<User>
|
||||
```
|
||||
Validates role is not `SystemAdmin` (only setup script can create SystemAdmin).
|
||||
Password validated by Zod schema before reaching this method: minimum 8 characters,
|
||||
at most 128 characters. Bcrypt work factor: 12 rounds.
|
||||
Hashes password. Creates user. Logs `user.create` audit.
|
||||
Throws `AppError('CONFLICT', ..., 409)` on duplicate username.
|
||||
|
||||
```js
|
||||
deactivateUser(targetId: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Last Owner check: counts active Owners in org. If target is last Owner, throws `AppError('LAST_OWNER_PROTECTED', ..., 400)`.
|
||||
Sets `isActive = false`. Deactivates all DeviceTokens for the user. Logs `user.deactivate` audit.
|
||||
|
||||
```js
|
||||
changeRole(
|
||||
targetId: number,
|
||||
newRole: string,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Last Owner check if current role is `Owner` and new role is not `Owner`.
|
||||
Self-role-change check: actorId === targetId throws if actor is Owner.
|
||||
Updates role. Logs `user.role.change` audit.
|
||||
|
||||
```js
|
||||
resetPassword(
|
||||
targetId: number,
|
||||
newPassword: string,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Password validated by Zod schema: minimum 8, maximum 128 characters.
|
||||
Hashes new password (12 bcrypt rounds). Sets `passwordChangedAt = now()` alongside the hash
|
||||
update — this invalidates all JWTs issued before this moment (enforced by `authenticateToken`).
|
||||
Revokes all DeviceTokens for target user.
|
||||
Logs `user.password.reset` audit (no password in log).
|
||||
|
||||
```js
|
||||
changeOwnPassword(
|
||||
userId: number,
|
||||
currentPassword: string,
|
||||
newPassword: string
|
||||
): Promise<void>
|
||||
```
|
||||
`newPassword` validated by Zod schema: minimum 8, maximum 128 characters.
|
||||
Fetches user with password included (bypasses defaultScope). Verifies `currentPassword` against
|
||||
stored bcrypt hash — throws `AppError('AUTH_FORBIDDEN', 'Current password is incorrect.', 401)`
|
||||
on mismatch. Hashes new password (12 bcrypt rounds). Sets `passwordChangedAt = now()` — this
|
||||
invalidates all JWTs and device tokens issued before this moment. Revokes all DeviceTokens for
|
||||
the user (the calling session's JWT is still valid until it next hits `authenticateToken`, at
|
||||
which point it is rejected and the user re-authenticates). Logs `user.password.change` audit
|
||||
(no passwords in log).
|
||||
|
||||
```js
|
||||
updateProfile(
|
||||
userId: number,
|
||||
data: { firstName?, lastName?, email? }
|
||||
): Promise<User>
|
||||
```
|
||||
Updates own profile fields. Logs `user.profile.update` audit with before/after.
|
||||
|
||||
```js
|
||||
getDeviceTokens(userId: number, orgId: number): Promise<DeviceToken[]>
|
||||
```
|
||||
Returns non-revoked device tokens for a user. Returns metadata only — token hash never returned.
|
||||
|
||||
```js
|
||||
revokeDeviceToken(tokenId: number, userId: number, orgId: number): Promise<void>
|
||||
```
|
||||
Sets `isRevoked = true`. Validates token belongs to userId + orgId before revoking.
|
||||
Logs `auth.device.revoked` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/org/service.js
|
||||
|
||||
```js
|
||||
getOrg(orgId: number): Promise<Organization>
|
||||
```
|
||||
Returns org record. Includes Branding via eager load.
|
||||
|
||||
```js
|
||||
updateOrg(
|
||||
orgId: number,
|
||||
data: { name?, timezone?, licenseOwner?, licenseEmail? },
|
||||
actorId: number
|
||||
): Promise<Organization>
|
||||
```
|
||||
Validates timezone is a valid IANA string (check against `Intl.supportedValuesOf('timeZone')`).
|
||||
Logs `org.update` audit.
|
||||
|
||||
```js
|
||||
getBranding(orgId: number): Promise<Branding>
|
||||
```
|
||||
Returns branding for org. Creates default branding if not exists.
|
||||
|
||||
```js
|
||||
updateBranding(
|
||||
orgId: number,
|
||||
data: { appName?, primaryColor?, secondaryColor?, workColor?, restColor?, moveColor? },
|
||||
actorId: number
|
||||
): Promise<Branding>
|
||||
```
|
||||
Validates each color is a valid CSS hex (`/^#[0-9A-Fa-f]{6}$/`).
|
||||
Validates contrast ratio of each color against `#1a1a1a` (display background) is >= 4.5:1.
|
||||
Throws `AppError('VALIDATION_FAILED', ..., 400)` listing each failing color.
|
||||
Logs `branding.update` audit.
|
||||
|
||||
```js
|
||||
validateContrastRatio(hex: string, background: string): number
|
||||
```
|
||||
Internal. Converts hex to relative luminance, calculates WCAG contrast ratio.
|
||||
Returns ratio (e.g., `7.2`).
|
||||
|
||||
```js
|
||||
uploadLogo(orgId: number, file: MulterFile, actorId: number): Promise<Branding>
|
||||
```
|
||||
Validates MIME type via magic bytes (reads first 12 bytes from `file.path`).
|
||||
Allowed types: `image/png`, `image/jpeg`, `image/gif`, `image/webp`.
|
||||
Wraps in `try/finally` to clean up the multer temp file regardless of outcome:
|
||||
```js
|
||||
try {
|
||||
// validate, derive ext from detected MIME, save to UPLOADS_DIR
|
||||
} finally {
|
||||
await fs.promises.unlink(file.path).catch(() => {});
|
||||
}
|
||||
```
|
||||
Deletes old logo file if one existed. Updates `Branding.logoPath`.
|
||||
Logs `logo.upload` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/videos/service.js
|
||||
|
||||
```js
|
||||
getVideos(
|
||||
orgId: number,
|
||||
filters: { category?: string, page?: number, limit?: number }
|
||||
): Promise<{ rows: Video[], count: number }>
|
||||
```
|
||||
Paginated. Filters by category if provided. Orders by `createdAt DESC`.
|
||||
|
||||
```js
|
||||
uploadVideo(
|
||||
orgId: number,
|
||||
file: MulterFile,
|
||||
data: { description: string, category: string },
|
||||
actorId: number
|
||||
): Promise<Video>
|
||||
```
|
||||
Wraps upload logic in `try/finally` to guarantee temp file cleanup:
|
||||
```js
|
||||
try {
|
||||
const detectedMime = await validateMimeType(file.path);
|
||||
const ext = { 'video/mp4': '.mp4', 'video/quicktime': '.mov', 'video/x-m4v': '.m4v' }[detectedMime];
|
||||
// ext is derived from detected MIME — original filename extension is ignored
|
||||
const safeName = `${Date.now()}_${crypto.randomBytes(8).toString('hex')}${ext}`;
|
||||
await fs.promises.rename(file.path, path.join(UPLOADS_DIR, safeName));
|
||||
// create DB record ...
|
||||
} finally {
|
||||
await fs.promises.unlink(file.path).catch(() => {}); // clean up temp if rename failed
|
||||
}
|
||||
```
|
||||
`validateMimeType(file.path)` — opens the temp file with `fs.openSync`, reads exactly the
|
||||
first 12 bytes via `fs.readSync`, closes the file handle, then runs `fileTypeFromBuffer` on
|
||||
those 12 bytes. Throws `UPLOAD_TYPE_INVALID` if result is not `video/mp4`, `video/quicktime`,
|
||||
or `video/x-m4v`. Never loads the full file into memory. Multer must use disk storage
|
||||
(`multer({ dest: process.env.UPLOAD_TEMP_DIR })`) — NOT `memoryStorage()`.
|
||||
File extension is derived from the detected MIME type — the original uploaded filename
|
||||
extension is discarded to prevent serving a valid video file with a `.php` or `.html` extension.
|
||||
Creates Video record with `fileSizeBytes = file.size`.
|
||||
Logs `video.upload` audit.
|
||||
|
||||
```js
|
||||
deleteVideo(videoId: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Finds video (throws 404 if not found or wrong org).
|
||||
Deletes file from `UPLOADS_DIR` (ignores ENOENT — file already gone is fine).
|
||||
Deletes DB record.
|
||||
Logs `video.delete` audit with before snapshot.
|
||||
|
||||
```js
|
||||
getCategories(orgId: number): Promise<Category[]>
|
||||
```
|
||||
Returns all categories for org, ordered by name.
|
||||
|
||||
```js
|
||||
createCategory(
|
||||
orgId: number,
|
||||
name: string,
|
||||
actorId: number
|
||||
): Promise<Category>
|
||||
```
|
||||
Throws `CONFLICT` on duplicate. Logs `category.create` audit.
|
||||
|
||||
```js
|
||||
deleteCategory(
|
||||
categoryId: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Throws `CONFLICT` if any Video in this org has `category = category.name`.
|
||||
Deletes. Logs `category.delete` audit.
|
||||
|
||||
```js
|
||||
validateMimeType(filePath: string, allowedMimes: string[]): Promise<string>
|
||||
```
|
||||
Opens `filePath` with `fs.openSync`, reads exactly 12 bytes via `fs.readSync`, closes the
|
||||
file descriptor, then passes the 12-byte Buffer to `fileTypeFromBuffer` from the `file-type`
|
||||
package. Never loads the whole file into memory.
|
||||
`allowedMimes` is passed by the caller — video uploads use `['video/mp4', 'video/quicktime',
|
||||
'video/x-m4v']`; logo uploads use `['image/png', 'image/jpeg', 'image/gif', 'image/webp']`.
|
||||
Throws `AppError('UPLOAD_TYPE_INVALID', ..., 400)` if detected type is not in `allowedMimes`
|
||||
or is undetectable. Returns the detected MIME type string.
|
||||
|
||||
```js
|
||||
streamVideo(
|
||||
filename: string,
|
||||
orgId: number,
|
||||
rangeHeader: string | undefined,
|
||||
res: Response
|
||||
): Promise<void>
|
||||
```
|
||||
Validates `path.basename(filename) === filename` (path traversal guard).
|
||||
Verifies a Video record with this filename exists in orgId (throws 404 if not).
|
||||
Resolves full path, checks it starts with `path.resolve(UPLOADS_DIR)` (double-check).
|
||||
If `rangeHeader`: parses range, opens `fs.createReadStream(start, end)`, sends 206.
|
||||
Otherwise: sends 200 with full file stream.
|
||||
Sets `Content-Type` from `video.mimeType` stored in DB.
|
||||
|
||||
---
|
||||
|
||||
## modules/workouts/service.js
|
||||
|
||||
```js
|
||||
getWorkouts(
|
||||
orgId: number,
|
||||
filters: { page?: number, limit?: number }
|
||||
): Promise<{ rows: Workout[], count: number }>
|
||||
```
|
||||
Uses LEFT JOIN on all four video slots. Each slot may return null if video was deleted.
|
||||
Returns `[Video removed]` sentinel values handled by the model association.
|
||||
|
||||
```js
|
||||
getWorkoutById(id: number, orgId: number): Promise<Workout>
|
||||
```
|
||||
LEFT JOINs all four video associations. Throws 404 if not found in org.
|
||||
|
||||
```js
|
||||
getTodayWorkouts(orgId: number): Promise<Workout[]>
|
||||
```
|
||||
Fetches org timezone. Uses luxon to compute UTC start/end for today in org's local time.
|
||||
Queries `workoutDate BETWEEN todayStart AND todayEnd`.
|
||||
|
||||
```js
|
||||
createWorkout(
|
||||
orgId: number,
|
||||
data: { name, workoutDate, video1?, video2?, video3?, video4?, number1?, number2?, number3?, number4? },
|
||||
actorId: number
|
||||
): Promise<Workout>
|
||||
```
|
||||
Validates each non-null videoN ID belongs to orgId.
|
||||
Creates Workout. Logs `workout.create` audit.
|
||||
|
||||
```js
|
||||
deleteWorkout(id: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Ownership check: if `req.user.role === 'Coach'`, verifies `createdByUserId === actorId`.
|
||||
Owners can delete any workout. Deletes. Logs `workout.delete` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/timers/service.js
|
||||
|
||||
```js
|
||||
getTimers(orgId: number): Promise<Timer[]>
|
||||
```
|
||||
Returns all timers for org, ordered by `createdAt DESC`.
|
||||
|
||||
```js
|
||||
getTimerById(id: number, orgId: number): Promise<Timer>
|
||||
```
|
||||
Throws 404 if not found in org.
|
||||
|
||||
```js
|
||||
createTimer(
|
||||
orgId: number,
|
||||
data: { name, totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount },
|
||||
actorId: number
|
||||
): Promise<Timer>
|
||||
```
|
||||
Validates all time values are positive integers.
|
||||
Validates `totalTime >= setTime * setCount * exerciseCount * lapCount` (rough sanity check).
|
||||
Creates. Logs `timer.create` audit.
|
||||
|
||||
```js
|
||||
deleteTimer(id: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Ownership check (same as workouts). Stops active session if one exists for this timer.
|
||||
Deletes. Logs `timer.delete` audit.
|
||||
|
||||
```js
|
||||
launchTimer(timerId: number, orgId: number, actorId: number): Promise<{ sessionId: string }>
|
||||
```
|
||||
Fetches timer config. Generates `sessionId = 'timer_' + timerId + '_' + Date.now()`.
|
||||
Creates `TimerEngine` instance. Stores in active sessions Map under `sessionId`.
|
||||
Calls `engine.start()`. Logs `timer.launch` audit.
|
||||
Returns `{ sessionId }` — clients join this Socket.io room.
|
||||
|
||||
```js
|
||||
stopTimer(sessionId: string, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Finds engine by sessionId. Calls `engine.stop()`. Removes from Map. Logs `timer.stop` audit.
|
||||
|
||||
```js
|
||||
getActiveSession(orgId: number): Promise<{ sessionId, state } | null>
|
||||
```
|
||||
Returns the currently running timer session for the org, or null. One active session per org.
|
||||
|
||||
---
|
||||
|
||||
## modules/timers/timer-engine.js
|
||||
|
||||
```js
|
||||
class TimerEngine {
|
||||
constructor(config: TimerConfig, io: SocketIoServer, roomId: string)
|
||||
}
|
||||
```
|
||||
|
||||
**State:**
|
||||
```js
|
||||
{
|
||||
status: 'idle' | 'running' | 'paused' | 'complete',
|
||||
phase: 'set' | 'rest' | 'move',
|
||||
currentLap: number, // 1-indexed
|
||||
currentExercise: number, // 1-indexed
|
||||
currentSet: number, // 1-indexed
|
||||
phaseEndTime: bigint, // process.hrtime.bigint() target for phase end
|
||||
sessionEndTime: bigint, // process.hrtime.bigint() target for session end
|
||||
elapsedSeconds: number
|
||||
}
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
|
||||
```js
|
||||
start(): void
|
||||
```
|
||||
Sets initial state. Records `sessionStartHrTime`. Begins `_tick()` interval (every 100ms for responsiveness).
|
||||
Emits `timer:state` to room with full state snapshot.
|
||||
|
||||
```js
|
||||
stop(): void
|
||||
```
|
||||
Clears interval. Sets `status = 'complete'`. Emits `timer:stopped` to room. Cleans up.
|
||||
|
||||
```js
|
||||
getState(): TimerState
|
||||
```
|
||||
Returns current state snapshot. Called when a client reconnects to re-sync.
|
||||
|
||||
```js
|
||||
_tick(): void [private]
|
||||
```
|
||||
Called every 100ms. Computes `remaining = phaseEndTime - process.hrtime.bigint()` in nanoseconds.
|
||||
Emits `timer:tick` with `{ phaseRemainingMs, totalRemainingMs, ...state }` at most once per second
|
||||
(tracks last-emitted second to avoid flooding).
|
||||
Calls `_advancePhase()` when `phaseRemaining <= 0`.
|
||||
|
||||
```js
|
||||
_advancePhase(): void [private]
|
||||
```
|
||||
State machine transitions:
|
||||
```
|
||||
set → rest (if restTime > 0, else skip to move)
|
||||
rest → move (if moveTime > 0 and not last set, else skip)
|
||||
move → set (increment set counter; if set > setCount, increment exercise; if exercise > exerciseCount, increment lap)
|
||||
last lap + last exercise + last set → complete()
|
||||
```
|
||||
Sets new `phaseEndTime`. Emits `timer:phase-change` with `{ phase, lap, exercise, set }`.
|
||||
|
||||
```js
|
||||
complete(): void [private]
|
||||
```
|
||||
Clears the `setInterval`. Removes this engine from the active sessions `Map` in `service.js`.
|
||||
Sets `status = 'complete'`. Emits `timer:complete` to the room.
|
||||
Does NOT call `stop()` — natural completion and manual stop are distinct paths.
|
||||
`stop()` is only ever called by an explicit coach/owner stop request.
|
||||
|
||||
---
|
||||
|
||||
## modules/crossfit/service.js
|
||||
|
||||
```js
|
||||
getCrossfitWorkouts(
|
||||
orgId: number,
|
||||
filters: { page?: number, limit?: number }
|
||||
): Promise<{ rows: CrossfitWorkout[], count: number }>
|
||||
```
|
||||
Parses `workoutItems` JSON on each row before returning.
|
||||
|
||||
```js
|
||||
createCrossfitWorkout(
|
||||
orgId: number,
|
||||
data: { name, workoutDate, workoutItems: string[] },
|
||||
actorId: number
|
||||
): Promise<CrossfitWorkout>
|
||||
```
|
||||
Validates `workoutItems` via Zod: non-empty array, max 50 items, each item a non-empty
|
||||
string max 500 characters. Stores as JSON. Logs `crossfit.create` audit.
|
||||
|
||||
```js
|
||||
deleteCrossfitWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Owner-only (checked by route). Logs `crossfit.delete` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/clients/service.js
|
||||
|
||||
```js
|
||||
getClients(
|
||||
requesterId: number,
|
||||
orgId: number,
|
||||
requesterRole: string
|
||||
): Promise<User[]>
|
||||
```
|
||||
If `Owner | SystemAdmin`: returns all Client-role users in org.
|
||||
If `Coach`: returns only clients with an active CoachClientLink to requesterId.
|
||||
|
||||
```js
|
||||
getClientById(
|
||||
clientId: number,
|
||||
requesterId: number,
|
||||
orgId: number,
|
||||
requesterRole: string
|
||||
): Promise<User>
|
||||
```
|
||||
Includes active coach assignment. Access check: Coach can only get their own clients.
|
||||
Throws 404 if not found or not accessible.
|
||||
|
||||
```js
|
||||
assignCoach(
|
||||
clientId: number,
|
||||
coachId: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<CoachClientLink>
|
||||
```
|
||||
Validates both users exist in org and have correct roles.
|
||||
Deactivates any existing active link for this client+coach pair (idempotent upsert).
|
||||
Creates new link. Logs `coach.client.assign` audit.
|
||||
|
||||
```js
|
||||
unassignCoach(
|
||||
linkId: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Sets `isActive = false`. Logs `coach.client.unassign` audit.
|
||||
|
||||
```js
|
||||
getClientWorkouts(
|
||||
clientId: number,
|
||||
requesterId: number,
|
||||
orgId: number,
|
||||
requesterRole: string,
|
||||
filters: { page?, limit?, includeCompleted?: boolean }
|
||||
): Promise<{ rows: ClientWorkout[], count: number }>
|
||||
```
|
||||
Access check: Client sees only their own workouts. Coach sees only their clients' workouts.
|
||||
Parses `items` JSON on each row.
|
||||
**coachNotes stripping (server-enforced):** When `requesterRole === 'Client'`, the `notes`
|
||||
field (coach notes on the workout record) is deleted from each row before returning. Item-level
|
||||
`notes` within the `items` array are coaching instructions and remain visible to the client.
|
||||
|
||||
```js
|
||||
createClientWorkout(
|
||||
orgId: number,
|
||||
data: { clientId, name, scheduledDate, notes?, items },
|
||||
actorId: number
|
||||
): Promise<ClientWorkout>
|
||||
```
|
||||
Validates `items` via Zod: max 100 items; each `video` item must have a valid `videoId` in org;
|
||||
each `text` item must have a non-empty string max 1000 characters; item-level `notes` max 500
|
||||
characters. Validates coach has active link to client. Logs `client_workout.create` audit.
|
||||
|
||||
```js
|
||||
updateClientWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
data: Partial<ClientWorkoutData>,
|
||||
actorId: number
|
||||
): Promise<ClientWorkout>
|
||||
```
|
||||
Validates ownership (same coach). Logs `client_workout.update` audit with before/after.
|
||||
|
||||
```js
|
||||
deleteClientWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Soft delete: sets `deletedAt = now()`. Logs `client_workout.delete` audit.
|
||||
|
||||
```js
|
||||
completeClientWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<ClientWorkout>
|
||||
```
|
||||
Sets `completedAt = now()`. Both coach and client can call this. Logs `client_workout.complete` audit.
|
||||
|
||||
```js
|
||||
getSessions(
|
||||
filters: { clientId?, startAfter?, endBefore?, status?, page?, limit? },
|
||||
orgId: number,
|
||||
requesterId: number,
|
||||
requesterRole: string
|
||||
): Promise<{ rows: CalendarSession[], count: number }>
|
||||
```
|
||||
Scope: Coach sees own sessions. Client sees own sessions. Owner sees all.
|
||||
Strips `coachNotes` from response when requester is a Client.
|
||||
|
||||
```js
|
||||
createSession(
|
||||
orgId: number,
|
||||
data: { clientId?, title, sessionType, startAt, endAt, locationNotes?, coachNotes?, sharedNotes?, linkedWorkoutId? },
|
||||
actorId: number
|
||||
): Promise<CalendarSession>
|
||||
```
|
||||
Validates `endAt > startAt`. Validates linkedWorkoutId belongs to clientId if provided.
|
||||
Logs `session.create` audit.
|
||||
|
||||
```js
|
||||
updateSession(
|
||||
id: number,
|
||||
orgId: number,
|
||||
data: Partial<SessionData>,
|
||||
actorId: number
|
||||
): Promise<CalendarSession>
|
||||
```
|
||||
Validates ownership. Logs `session.update` audit with before/after.
|
||||
|
||||
```js
|
||||
cancelSession(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number,
|
||||
actorRole: string
|
||||
): Promise<CalendarSession>
|
||||
```
|
||||
Sets `status = 'cancelled'`. Both coach and client can cancel.
|
||||
**24-hour rule (server-enforced):** If `actorRole === 'Client'` and
|
||||
`(new Date(session.startAt) - Date.now()) / 3600000 < 24`, throws
|
||||
`AppError('CANCELLATION_TOO_LATE', 'Sessions must be cancelled at least 24 hours in advance.', 400)`.
|
||||
Coaches and Owners bypass the 24-hour check.
|
||||
Client cancellation logs `session.cancel` with `cancelledBy: 'client'`.
|
||||
Logs `session.cancel` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/audit/routes.js
|
||||
|
||||
No service.js — reads directly from AuditLog model. Writes are via `core/audit.js`.
|
||||
|
||||
```js
|
||||
GET /api/v1/audit-logs
|
||||
→ authenticateToken, authenticateRole(['Owner', 'SystemAdmin'])
|
||||
→ Queries AuditLog with filters: action, userId, entityType, from, to
|
||||
→ Returns paginated collection
|
||||
|
||||
GET /api/v1/audit-logs/export
|
||||
→ authenticateToken, authenticateRole(['Owner', 'SystemAdmin'])
|
||||
→ Streams CSV response
|
||||
→ Sets Content-Disposition: attachment; filename="audit-log-<date>.csv"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## modules/sysadmin/routes.js
|
||||
|
||||
No service.js — uses models directly with cross-org queries (no orgId filter).
|
||||
|
||||
```js
|
||||
GET /api/v1/sysadmin/orgs
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Returns all orgs with user counts
|
||||
|
||||
GET /api/v1/sysadmin/orgs/:id
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Returns org detail with branding, user list summary
|
||||
|
||||
PATCH /api/v1/sysadmin/orgs/:id
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Updates timezone, features, isActive, licenseOwner, licenseEmail
|
||||
|
||||
GET /api/v1/sysadmin/health
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Returns full health details: version, DB migrations, storage, uptime, active timer sessions
|
||||
```
|
||||
@@ -0,0 +1,426 @@
|
||||
# VitFit V2 — Database Schema
|
||||
|
||||
Sequelize model definitions. Every model is defined in its module's `model.js` file
|
||||
and registered via `core/db.js`. Primary keys, `createdAt`, `updatedAt` are generated
|
||||
by Sequelize unless noted. `timestamps: false` is only used on AuditLog (no `updatedAt`).
|
||||
|
||||
---
|
||||
|
||||
## Associations Summary
|
||||
|
||||
```
|
||||
Organization hasOne Branding (via organizationId)
|
||||
Organization hasMany User (via organizationId)
|
||||
Organization hasMany Video (via organizationId)
|
||||
Organization hasMany Category (via organizationId)
|
||||
Organization hasMany Workout (via organizationId)
|
||||
Organization hasMany Timer (via organizationId)
|
||||
Organization hasMany CrossfitWorkout (via organizationId)
|
||||
Organization hasMany CoachClientLink (via organizationId)
|
||||
Organization hasMany ClientWorkout (via organizationId)
|
||||
Organization hasMany CalendarSession (via organizationId)
|
||||
|
||||
User hasMany DeviceToken (via userId)
|
||||
User hasMany CoachClientLink (as coach, via coachId)
|
||||
User hasMany CoachClientLink (as client, via clientId)
|
||||
User hasMany ClientWorkout (as coach, via coachId)
|
||||
User hasMany ClientWorkout (as client, via clientId)
|
||||
User hasMany CalendarSession (as coach, via coachId)
|
||||
User hasMany CalendarSession (as client, via clientId)
|
||||
|
||||
Workout belongsTo Video (as VideoOne, via video1)
|
||||
Workout belongsTo Video (as VideoTwo, via video2)
|
||||
Workout belongsTo Video (as VideoThree, via video3)
|
||||
Workout belongsTo Video (as VideoFour, via video4)
|
||||
|
||||
ClientWorkout belongsTo CalendarSession (via linkedWorkoutId, optional)
|
||||
```
|
||||
|
||||
AuditLog has no enforced FK associations (see DATA_MODEL.md rationale).
|
||||
|
||||
---
|
||||
|
||||
## Organizations
|
||||
|
||||
```js
|
||||
// modules/org/model.js
|
||||
Organization = sequelize.define('Organization', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
name: { type: DataTypes.STRING, allowNull: false },
|
||||
slug: { type: DataTypes.STRING, unique: true },
|
||||
timezone: { type: DataTypes.STRING, defaultValue: 'UTC' },
|
||||
features: { type: DataTypes.TEXT, defaultValue: '[]',
|
||||
get() { return JSON.parse(this.getDataValue('features') || '[]'); },
|
||||
set(v) { this.setDataValue('features', JSON.stringify(v)); } },
|
||||
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
|
||||
licenseOwner: { type: DataTypes.STRING },
|
||||
licenseEmail: { type: DataTypes.STRING },
|
||||
});
|
||||
```
|
||||
|
||||
Hooks:
|
||||
```js
|
||||
Organization.beforeCreate(org => {
|
||||
if (!org.slug) {
|
||||
org.slug = org.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Brandings
|
||||
|
||||
```js
|
||||
// modules/org/model.js
|
||||
Branding = sequelize.define('Branding', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false, unique: true },
|
||||
appName: { type: DataTypes.STRING, defaultValue: 'VitFit' },
|
||||
logoPath: { type: DataTypes.STRING },
|
||||
primaryColor: { type: DataTypes.STRING, defaultValue: '#00FF88' },
|
||||
secondaryColor: { type: DataTypes.STRING, defaultValue: '#4488FF' },
|
||||
workColor: { type: DataTypes.STRING, defaultValue: '#00FF88' },
|
||||
restColor: { type: DataTypes.STRING, defaultValue: '#4488FF' },
|
||||
moveColor: { type: DataTypes.STRING, defaultValue: '#FF4444' },
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Users
|
||||
|
||||
```js
|
||||
// modules/users/model.js
|
||||
User = sequelize.define('User', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER }, // nullable for SystemAdmin
|
||||
username: { type: DataTypes.STRING, allowNull: false, unique: true },
|
||||
email: { type: DataTypes.STRING, unique: true },
|
||||
password: { type: DataTypes.STRING, allowNull: false },
|
||||
role: { type: DataTypes.ENUM('SystemAdmin', 'Owner', 'Coach', 'Client'),
|
||||
allowNull: false, defaultValue: 'Coach' },
|
||||
firstName: { type: DataTypes.STRING },
|
||||
lastName: { type: DataTypes.STRING },
|
||||
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
|
||||
lastLoginAt: { type: DataTypes.DATE },
|
||||
passwordChangedAt: { type: DataTypes.DATE }, // set on every password change/reset; null for new accounts
|
||||
});
|
||||
```
|
||||
|
||||
Instance method:
|
||||
```js
|
||||
User.prototype.toPublic = function() {
|
||||
const { password, ...rest } = this.toJSON();
|
||||
return rest; // password never sent in responses
|
||||
};
|
||||
```
|
||||
|
||||
Default scope (always applied):
|
||||
```js
|
||||
User.addScope('defaultScope', { attributes: { exclude: ['password', 'passwordChangedAt'] } });
|
||||
```
|
||||
Both `password` and `passwordChangedAt` are excluded from all normal queries.
|
||||
`authenticateToken` and `changeOwnPassword` explicitly select these fields when needed.
|
||||
|
||||
---
|
||||
|
||||
## DeviceTokens
|
||||
|
||||
```js
|
||||
// modules/auth/model.js
|
||||
DeviceToken = sequelize.define('DeviceToken', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
userId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
token: { type: DataTypes.STRING, allowNull: false, unique: true }, // SHA-256 hash
|
||||
deviceName: { type: DataTypes.STRING },
|
||||
deviceType: { type: DataTypes.ENUM('kiosk', 'personal'), defaultValue: 'personal' },
|
||||
lastUsedAt: { type: DataTypes.DATE },
|
||||
expiresAt: { type: DataTypes.DATE, allowNull: false },
|
||||
isRevoked: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||
});
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
DeviceToken.addIndex(['token']); // lookup by hash
|
||||
DeviceToken.addIndex(['userId', 'isRevoked']); // list user's active tokens
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Videos
|
||||
|
||||
```js
|
||||
// modules/videos/model.js
|
||||
Video = sequelize.define('Video', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
filename: { type: DataTypes.STRING, allowNull: false },
|
||||
description: { type: DataTypes.STRING },
|
||||
category: { type: DataTypes.STRING },
|
||||
mimeType: { type: DataTypes.STRING },
|
||||
fileSizeBytes: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
Virtual field appended in service layer (not stored):
|
||||
```js
|
||||
// In service.getVideos() — appended after DB query:
|
||||
video.streamUrl = `/api/v1/videos/stream/${video.filename}`;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Categories
|
||||
|
||||
```js
|
||||
// modules/videos/model.js
|
||||
Category = sequelize.define('Category', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING, allowNull: false },
|
||||
});
|
||||
|
||||
Category.addIndex(['organizationId', 'name'], { unique: true });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Workouts
|
||||
|
||||
```js
|
||||
// modules/workouts/model.js
|
||||
Workout = sequelize.define('Workout', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING },
|
||||
workoutDate: { type: DataTypes.DATE },
|
||||
video1: { type: DataTypes.INTEGER },
|
||||
video2: { type: DataTypes.INTEGER },
|
||||
video3: { type: DataTypes.INTEGER },
|
||||
video4: { type: DataTypes.INTEGER },
|
||||
number1: { type: DataTypes.INTEGER },
|
||||
number2: { type: DataTypes.INTEGER },
|
||||
number3: { type: DataTypes.INTEGER },
|
||||
number4: { type: DataTypes.INTEGER },
|
||||
createdByUserId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
|
||||
// Associations (using aliases to resolve 4x FK to same table)
|
||||
Workout.belongsTo(Video, { foreignKey: 'video1', as: 'VideoOne', constraints: false });
|
||||
Workout.belongsTo(Video, { foreignKey: 'video2', as: 'VideoTwo', constraints: false });
|
||||
Workout.belongsTo(Video, { foreignKey: 'video3', as: 'VideoThree', constraints: false });
|
||||
Workout.belongsTo(Video, { foreignKey: 'video4', as: 'VideoFour', constraints: false });
|
||||
// constraints: false — allows hard-deleted videos without FK violation
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
Workout.addIndex(['organizationId', 'workoutDate']); // used by today-workouts query
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Timers
|
||||
|
||||
```js
|
||||
// modules/timers/model.js
|
||||
Timer = sequelize.define('Timer', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING, allowNull: false },
|
||||
totalTime: { type: DataTypes.INTEGER, allowNull: false },
|
||||
setTime: { type: DataTypes.INTEGER, allowNull: false },
|
||||
restTime: { type: DataTypes.INTEGER, defaultValue: 0 },
|
||||
moveTime: { type: DataTypes.INTEGER, defaultValue: 0 },
|
||||
setCount: { type: DataTypes.INTEGER, allowNull: false },
|
||||
exerciseCount: { type: DataTypes.INTEGER, allowNull: false },
|
||||
lapCount: { type: DataTypes.INTEGER, defaultValue: 1 },
|
||||
createdByUserId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CrossfitWorkouts
|
||||
|
||||
```js
|
||||
// modules/crossfit/model.js
|
||||
CrossfitWorkout = sequelize.define('CrossfitWorkout', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING },
|
||||
workoutDate: { type: DataTypes.DATE },
|
||||
workoutItems: {
|
||||
type: DataTypes.TEXT,
|
||||
get() { return JSON.parse(this.getDataValue('workoutItems') || '[]'); },
|
||||
set(v) { this.setDataValue('workoutItems', JSON.stringify(v)); },
|
||||
},
|
||||
createdByUserId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CoachClientLinks
|
||||
|
||||
```js
|
||||
// modules/clients/model.js
|
||||
CoachClientLink = sequelize.define('CoachClientLink', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
coachId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
clientId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
|
||||
assignedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
|
||||
assignedByUserId:{ type: DataTypes.INTEGER },
|
||||
});
|
||||
|
||||
CoachClientLink.addIndex(['coachId', 'clientId', 'isActive']);
|
||||
CoachClientLink.addIndex(['clientId', 'isActive']); // find active coach for a client
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ClientWorkouts
|
||||
|
||||
```js
|
||||
// modules/clients/model.js
|
||||
ClientWorkout = sequelize.define('ClientWorkout', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
clientId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
coachId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING },
|
||||
scheduledDate: { type: DataTypes.DATE },
|
||||
notes: { type: DataTypes.TEXT },
|
||||
items: {
|
||||
type: DataTypes.TEXT,
|
||||
get() { return JSON.parse(this.getDataValue('items') || '[]'); },
|
||||
set(v) { this.setDataValue('items', JSON.stringify(v)); },
|
||||
},
|
||||
completedAt: { type: DataTypes.DATE },
|
||||
deletedAt: { type: DataTypes.DATE }, // soft delete
|
||||
});
|
||||
|
||||
ClientWorkout.addScope('active', { where: { deletedAt: null } });
|
||||
// All queries use: ClientWorkout.scope('active').findAll(...)
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
ClientWorkout.addIndex(['clientId', 'deletedAt', 'scheduledDate']);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CalendarSessions
|
||||
|
||||
```js
|
||||
// modules/clients/model.js
|
||||
CalendarSession = sequelize.define('CalendarSession', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
coachId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
clientId: { type: DataTypes.INTEGER }, // nullable = group session
|
||||
title: { type: DataTypes.STRING },
|
||||
sessionType: { type: DataTypes.ENUM('personal', 'group', 'assessment', 'other'),
|
||||
defaultValue: 'personal' },
|
||||
startAt: { type: DataTypes.DATE, allowNull: false },
|
||||
endAt: { type: DataTypes.DATE, allowNull: false },
|
||||
locationNotes: { type: DataTypes.STRING },
|
||||
coachNotes: { type: DataTypes.TEXT },
|
||||
sharedNotes: { type: DataTypes.TEXT },
|
||||
status: { type: DataTypes.ENUM('scheduled', 'completed', 'cancelled', 'no-show'),
|
||||
defaultValue: 'scheduled' },
|
||||
linkedWorkoutId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
CalendarSession.addIndex(['coachId', 'startAt']);
|
||||
CalendarSession.addIndex(['clientId', 'startAt']);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## AuditLogs
|
||||
|
||||
```js
|
||||
// modules/audit/model.js
|
||||
AuditLog = sequelize.define('AuditLog', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER }, // no FK constraint — intentional
|
||||
userId: { type: DataTypes.INTEGER }, // no FK constraint — intentional
|
||||
userRole: { type: DataTypes.STRING },
|
||||
action: { type: DataTypes.STRING, allowNull: false },
|
||||
entityType: { type: DataTypes.STRING },
|
||||
entityId: { type: DataTypes.INTEGER },
|
||||
details: {
|
||||
type: DataTypes.TEXT,
|
||||
get() { try { return JSON.parse(this.getDataValue('details') || '{}'); } catch { return {}; } },
|
||||
set(v) { this.setDataValue('details', JSON.stringify(v)); },
|
||||
},
|
||||
ipAddress: { type: DataTypes.STRING },
|
||||
userAgent: { type: DataTypes.STRING },
|
||||
}, {
|
||||
updatedAt: false, // audit logs have no updatedAt
|
||||
createdAt: 'createdAt',
|
||||
});
|
||||
```
|
||||
|
||||
Indexes:
|
||||
```js
|
||||
AuditLog.addIndex(['organizationId', 'createdAt']); // paginate by org
|
||||
AuditLog.addIndex(['userId']); // filter by user
|
||||
AuditLog.addIndex(['action']); // filter by action type
|
||||
AuditLog.addIndex(['entityType', 'entityId']); // find all logs for a specific record
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration Numbering
|
||||
|
||||
```
|
||||
modules/*/migrations/
|
||||
├── 001-baseline.js V1 tables (idempotent — skips if tables exist)
|
||||
├── 002-organizations.js Create Organizations, Brandings tables; seed one org + branding
|
||||
├── 003-users-v2.js Add organizationId, email, firstName, lastName, isActive, lastLoginAt to Users
|
||||
├── 004-videos-v2.js Add organizationId, mimeType, fileSizeBytes to Videos
|
||||
├── 005-categories-v2.js Add organizationId to Categories
|
||||
├── 006-workouts-v2.js Add organizationId, createdByUserId to Workouts
|
||||
├── 007-timers-v2.js Add organizationId, name, createdByUserId to Timers
|
||||
├── 008-crossfit-v2.js Add organizationId, createdByUserId to CrossfitWorkouts
|
||||
├── 009-device-tokens.js Create DeviceTokens table
|
||||
├── 010-coach-client-links.js Create CoachClientLinks table
|
||||
├── 011-client-workouts.js Create ClientWorkouts table (with deletedAt)
|
||||
├── 012-calendar-sessions.js Create CalendarSessions table
|
||||
├── 013-audit-logs.js Create AuditLogs table
|
||||
└── 014-users-password-changed-at.js Add passwordChangedAt column to Users (nullable, no default)
|
||||
```
|
||||
|
||||
Migration 001 checks table existence before creating — safe to run against the populated V1 database.
|
||||
Migrations 002+ are additive only (addColumn, createTable) — no data destroyed.
|
||||
|
||||
---
|
||||
|
||||
## Soft Delete vs. Hard Delete Reference
|
||||
|
||||
| Entity | Delete behavior | Restorable? | Notes |
|
||||
|---|---|---|---|
|
||||
| User | Soft — `isActive = false` | Yes (Owner can reactivate) | Record preserved; history intact |
|
||||
| Organization | Soft — `isActive = false` | Yes (SystemAdmin only) | |
|
||||
| CoachClientLink | Soft — `isActive = false` | Yes (reassign flow) | Old link deactivated, new link created |
|
||||
| ClientWorkout | Soft — `deletedAt` timestamp | Yes (no UI, but data recoverable by DB) | `scope('active')` hides it |
|
||||
| CalendarSession | Soft — `status = 'cancelled'` | No (status change, not hidden) | Remains in history |
|
||||
| Video | Hard — DB record + file removed | No | File on disk is deleted immediately |
|
||||
| Workout | Hard — DB record removed | No | Video FKs use `constraints: false` so video deletion doesn't cascade |
|
||||
| Timer | Hard — DB record removed | No | In-memory sessions already gone if server restarted |
|
||||
| CrossfitWorkout | Hard — DB record removed | No | |
|
||||
| Category | Hard — blocked if videos exist in it | N/A (blocked, not deleted) | Returns `CONFLICT` |
|
||||
| DeviceToken | Hard — DB record removed | No (user must re-login to get new token) | |
|
||||
| AuditLog | Never deleted | N/A | Append-only; no delete endpoint |
|
||||
| Branding | Never deleted | N/A | Updated in-place; one per org |
|
||||
@@ -0,0 +1,394 @@
|
||||
# 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:
|
||||
```markdown
|
||||
## [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:
|
||||
1. Load `.env`
|
||||
2. Initialize pino logger
|
||||
3. Run database migrations via `core/db.js`
|
||||
4. Create Express app, apply global middleware
|
||||
5. Auto-load all modules from `modules/*/routes.js`
|
||||
6. Attach Socket.io via `core/socket.js`
|
||||
7. Register the global error handler
|
||||
8. Start HTTP server on `PORT`
|
||||
9. Signal PM2 ready (`process.send('ready')`)
|
||||
|
||||
Global middleware stack (in order):
|
||||
1. `helmet()` — security headers (including CSP — see ARCHITECTURE.md)
|
||||
2. `cors()` — CORS (restrict origin in production via `CORS_ORIGIN` env)
|
||||
3. `express.json({ limit: '64kb' })` — JSON body parser with explicit size cap; prevents DoS via large payloads
|
||||
4. `express.static('public')` — serve frontend HTML/JS/CSS
|
||||
5. `authRateLimiter` applied to both `POST /api/v1/auth/login` AND `POST /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 overlay
|
||||
- `Api` — fetch wrapper that injects Authorization header, handles 401, retries after token refresh
|
||||
- `Nav` — drawer open/close, mark active link, role-based link visibility
|
||||
- `Branding` — fetches `/api/v1/org/branding` on load, applies CSS custom properties to `:root`
|
||||
- `Page.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:ready` when connected
|
||||
- Exposes `on(event, handler)` and `emit(event, data)` proxies
|
||||
- On reconnect: calls a registered `onReconnect` callback 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:complete` events
|
||||
- Falls back to local countdown using received `endTime` if Socket.io disconnects
|
||||
- `localFallback(endTime)` — runs `Date.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](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
|
||||
```
|
||||
@@ -0,0 +1,650 @@
|
||||
# VitFit V2 — Frontend Page Map
|
||||
|
||||
Every HTML page: purpose, access control, API calls, socket events, and key JS behavior.
|
||||
|
||||
All pages load `core.js` which calls `Page.init(allowedRoles)` on DOMContentLoaded.
|
||||
`Page.init` checks localStorage for a JWT (or attempts device-token re-auth), redirects to `/` if
|
||||
not authenticated or role not in `allowedRoles`. It also fetches branding and applies CSS vars.
|
||||
|
||||
CSS loaded on every page: `base.css`, `layout.css`, `components.css`.
|
||||
Display-mode pages also load: `display.css` (replaces layout, not combined with it).
|
||||
|
||||
---
|
||||
|
||||
## Shared JS Modules
|
||||
|
||||
### public/js/core.js
|
||||
|
||||
Loaded on every page.
|
||||
|
||||
```
|
||||
Auth
|
||||
- getJwt() read from localStorage
|
||||
- setJwt(token) write to localStorage
|
||||
- getDeviceToken() read from localStorage
|
||||
- setDeviceToken(token) write to localStorage
|
||||
- clearSession() remove jwt + deviceToken from localStorage
|
||||
- tryDeviceLogin() POST /auth/device-login with stored device token
|
||||
- isTokenExpiringSoon(jwt) true if exp < now + 1h
|
||||
- autoRefreshIfNeeded() call /auth/refresh-token if expiring soon
|
||||
|
||||
Api
|
||||
- fetch(url, options?) wraps window.fetch; injects Auth header; on 401 → tries
|
||||
autoRefreshIfNeeded then retries once; on 2nd 401 → shows
|
||||
session-expired overlay
|
||||
- get(url, params?) Api.fetch with method GET
|
||||
- post(url, body) Api.fetch with method POST, JSON body
|
||||
- patch(url, body) Api.fetch with method PATCH, JSON body
|
||||
- put(url, body) Api.fetch with method PUT, JSON body
|
||||
- del(url) Api.fetch with method DELETE
|
||||
- upload(url, formData) Api.fetch with method POST, FormData body (no Content-Type header)
|
||||
|
||||
Nav
|
||||
- init(currentPage) build nav drawer from config, highlight active item
|
||||
- roleVisibility(role) filter nav links by role
|
||||
- toggle() open/close drawer on hamburger tap
|
||||
|
||||
Branding
|
||||
- load() GET /api/v1/org/branding → apply to :root CSS vars
|
||||
- apply(branding) set --color-primary, --color-work, --app-name, etc.
|
||||
|
||||
Page
|
||||
- init(allowedRoles) auth check + branding load + nav init
|
||||
- currentUser() decode jwt, return { id, username, role, organizationId }
|
||||
- showSessionExpiredOverlay() shows tap-to-re-login overlay (non-blocking)
|
||||
```
|
||||
|
||||
### public/js/socket-client.js
|
||||
|
||||
```
|
||||
SocketClient
|
||||
- connect() create io() with auth token; bind internal events
|
||||
- on(event, handler) register event handler
|
||||
- emit(event, data) emit to server
|
||||
- joinRoom(roomId) emit timer:join
|
||||
- leaveRoom(roomId) emit timer:leave
|
||||
- onDisconnect(cb) register disconnect callback
|
||||
- onReconnect(cb) register reconnect callback (re-joins room automatically)
|
||||
- destroy() disconnect and remove all listeners (called on page unload)
|
||||
```
|
||||
|
||||
### public/js/display.js
|
||||
|
||||
Used by `workout-display.html` and `crossfit-display.html`.
|
||||
|
||||
```
|
||||
Display
|
||||
- renderWorkout(workout) populate full-screen workout layout
|
||||
- renderCrossfit(crossfit) populate full-screen CrossFit layout
|
||||
- setOffline(true|false) show/hide reconnecting banner (content stays)
|
||||
- startKeepAlive() begin 30s low-opacity CSS animation to prevent AirPlay freeze
|
||||
- applyBranding(branding) set display-mode CSS vars (colors, font)
|
||||
```
|
||||
|
||||
### public/js/timer-display.js
|
||||
|
||||
```
|
||||
TimerDisplay
|
||||
- init(sessionId) join socket room, register event handlers
|
||||
- handleState(state) render full timer state from timer:state event
|
||||
- handleTick(data) update phase countdown display
|
||||
- handlePhaseChange(data) update phase label, color, reset countdown, play sound
|
||||
- handleComplete(data) show completion overlay
|
||||
- handleStopped(data) show stopped overlay
|
||||
- startLocalFallback(endTime) animationFrame loop using Date.now() diff
|
||||
- stopLocalFallback() cancel animationFrame loop
|
||||
- formatTime(ms) returns "MM:SS" string
|
||||
- formatHMS(ms) returns "H:MM:SS" string for total time
|
||||
- setPhaseColor(phase) read CSS var for phase, apply to display elements
|
||||
- setOffline(true|false) show/hide reconnecting indicator (timer continues)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pages — Unauthenticated
|
||||
|
||||
### index.html — Login
|
||||
|
||||
Access: Public (unauthenticated only — redirects to dashboard if already logged in).
|
||||
|
||||
On load:
|
||||
- Check for stored JWT; if valid, redirect to `/dashboard.html`
|
||||
- Check for stored deviceToken; if present, `POST /api/v1/auth/device-login` → redirect on success
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/auth/login
|
||||
body: { username, password, rememberDevice, deviceName, deviceType }
|
||||
on 200: store jwt (+ deviceToken if present), redirect to /dashboard.html
|
||||
on 401: show "Invalid username or password" inline error
|
||||
on 429: show "Too many attempts, please wait" inline error
|
||||
```
|
||||
|
||||
Key behavior:
|
||||
- "Remember this device" checkbox (default checked on iPad-sized screens)
|
||||
- `deviceName` defaults to `navigator.userAgent` parsed to a readable string
|
||||
- `deviceType` defaults to `kiosk` if screen width >= 768px (iPad), else `personal`
|
||||
- Password field: toggle show/hide button
|
||||
|
||||
---
|
||||
|
||||
## Pages — Coach / Owner (Standard Management UI)
|
||||
|
||||
CSS: `base.css`, `layout.css`, `components.css`
|
||||
Shell: banner + hamburger, nav drawer, main content area.
|
||||
|
||||
### dashboard.html — Home
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts/today → render "Today's Workouts" card list
|
||||
GET /api/v1/org → show org name in header
|
||||
GET /api/v1/admin/storage → (Owner only) show disk usage bar in quick-stats
|
||||
```
|
||||
|
||||
Quick-stats cards:
|
||||
- Today's workouts count (link to workouts.html)
|
||||
- Active timers: count of timers defined (link to timers.html)
|
||||
- (Owner only) Disk used %
|
||||
|
||||
---
|
||||
|
||||
### videos.html — Video Library
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → populate filter dropdown
|
||||
GET /api/v1/videos?page=1 → render video grid
|
||||
```
|
||||
|
||||
Actions:
|
||||
- Category filter dropdown → `GET /api/v1/videos?category=X` → re-render grid
|
||||
- Pagination controls → `GET /api/v1/videos?page=N`
|
||||
- Each video card: inline `<video>` element using `streamUrl` as `src`
|
||||
- Delete button: confirm modal → `DELETE /api/v1/videos/:id` → remove card from DOM
|
||||
|
||||
---
|
||||
|
||||
### upload-video.html — Upload Video
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → populate category select
|
||||
```
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/videos (multipart)
|
||||
fields: video (file), description, category
|
||||
on 201: show success toast, reset form
|
||||
on 400 UPLOAD_TYPE_INVALID: "Only MP4, MOV, and M4V files are supported."
|
||||
on 507: "Not enough disk space to upload. Contact your administrator."
|
||||
```
|
||||
|
||||
Progress indicator: `XMLHttpRequest.upload.onprogress` for upload progress bar.
|
||||
|
||||
---
|
||||
|
||||
### categories.html — Manage Categories
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → render list
|
||||
```
|
||||
|
||||
Actions:
|
||||
- Create form: `POST /api/v1/categories` → append to list
|
||||
- Delete button: `DELETE /api/v1/categories/:id`
|
||||
- On CONFLICT 409: "This category has videos. Move or delete the videos first."
|
||||
|
||||
---
|
||||
|
||||
### workouts.html — Group Workouts
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts?page=1 → render paginated workout cards
|
||||
```
|
||||
|
||||
Each workout card shows: name, date, video thumbnails (or "[Video removed]"), video descriptions.
|
||||
|
||||
Actions:
|
||||
- "View" link → `workout-view.html?id=X`
|
||||
- "Display" button → open `workout-display.html?id=X` in same window (full-screen takes over)
|
||||
- Delete button (own workouts for Coach, any for Owner):
|
||||
`DELETE /api/v1/workouts/:id` → remove card
|
||||
|
||||
---
|
||||
|
||||
### create-workout.html — Create Workout
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → populate category dropdowns (one per slot)
|
||||
```
|
||||
|
||||
Slot 1 category change:
|
||||
```
|
||||
GET /api/v1/videos?category=X → populate video select for slot 1
|
||||
```
|
||||
Repeated for slots 2–4 (each has its own category+video selects, initially hidden, revealed by "Add Exercise" button).
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/workouts
|
||||
on 201: redirect to workouts.html
|
||||
on 400: show validation errors inline
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### workout-view.html — Single Workout Detail
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
Query param: `?id=<workoutId>`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts/:id → render workout detail + video players
|
||||
```
|
||||
|
||||
Each video slot renders a `<video>` element with `src = streamUrl`.
|
||||
"Display on TV" button → navigate to `workout-display.html?id=X`.
|
||||
|
||||
---
|
||||
|
||||
### timers.html — Timer List
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/timers → render timer cards
|
||||
```
|
||||
|
||||
Each card: name, summary (e.g. "30s work / 10s rest × 3 sets × 5 exercises × 2 laps").
|
||||
|
||||
Actions:
|
||||
- "Launch" button → `POST /api/v1/timers/:id/launch` → navigate to `timer-display.html?session=<sessionId>`
|
||||
- Delete button → `DELETE /api/v1/timers/:id`
|
||||
|
||||
---
|
||||
|
||||
### create-timer.html — Create Timer
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load: no API calls.
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/timers
|
||||
on 201: redirect to timers.html
|
||||
```
|
||||
|
||||
Live preview: calculated total time shown as user fills in fields.
|
||||
Formula: `totalTime = setTime * setCount * exerciseCount * lapCount + restTime * ... + moveTime * ...`
|
||||
|
||||
---
|
||||
|
||||
### crossfit.html — CrossFit Workouts
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/crossfit-workouts?page=1 → render workout cards
|
||||
```
|
||||
|
||||
Each card: name, date, bullet list of items.
|
||||
|
||||
Actions:
|
||||
- "Display" button → open `crossfit-display.html?id=X`
|
||||
- Delete button (Owner only): `DELETE /api/v1/crossfit-workouts/:id`
|
||||
|
||||
---
|
||||
|
||||
### create-crossfit.html — Create CrossFit Workout
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
Form: name, date, textarea (one item per line).
|
||||
|
||||
Submit:
|
||||
```
|
||||
POST /api/v1/crossfit-workouts
|
||||
body: { name, workoutDate, workoutItems: textarea.value.split('\n').filter(Boolean) }
|
||||
on 201: redirect to crossfit.html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### clients.html — Client Roster
|
||||
|
||||
Access: Owner (all clients), Coach (own clients only).
|
||||
|
||||
Feature flag: `client-management`.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/clients → render client cards
|
||||
```
|
||||
|
||||
Each card: name, username, assigned coach name, pending workout count.
|
||||
|
||||
Actions:
|
||||
- Click card → `client-profile.html?id=X`
|
||||
- "Add Client" button (Owner) → modal with create-user form → `POST /api/v1/clients`
|
||||
|
||||
---
|
||||
|
||||
### client-profile.html — Client Detail
|
||||
|
||||
Access: Owner, Coach (own clients only).
|
||||
|
||||
Query param: `?id=<clientId>`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/clients/:id → render profile header
|
||||
GET /api/v1/clients/:id/workouts?includeCompleted=false → render upcoming workouts
|
||||
GET /api/v1/clients/:id/sessions?status=scheduled → render upcoming sessions
|
||||
```
|
||||
|
||||
Tabs: Workouts | Sessions | History
|
||||
|
||||
Actions:
|
||||
- "Assign New Workout" → modal form → `POST /api/v1/clients/:id/workouts`
|
||||
- "Schedule Session" → modal form → `POST /api/v1/clients/:id/sessions`
|
||||
- Workout "Complete" → `POST /api/v1/clients/:id/workouts/:workoutId/complete`
|
||||
- Workout delete → `DELETE /api/v1/clients/:id/workouts/:workoutId`
|
||||
- Session cancel → `POST /api/v1/clients/:id/sessions/:sessionId/cancel`
|
||||
|
||||
---
|
||||
|
||||
### calendar.html — Coach Calendar
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
Feature flag: `calendar`.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/calendar?startAfter=<monthStart>&endBefore=<monthEnd> → render calendar grid
|
||||
```
|
||||
|
||||
Month navigation recalculates date range and re-fetches.
|
||||
Click on session → expand detail inline.
|
||||
|
||||
**Phase 2 deferrals (not in V2 MVP):**
|
||||
- Conflict detection: overlapping sessions for the same coach are not flagged. The API accepts
|
||||
overlapping bookings. Visual collision awareness is a Phase 2 enhancement.
|
||||
- Recurring sessions: no recurrence rules (RRULE, daily, weekly, etc.). Each session is a
|
||||
standalone record. Repeating a session means creating copies manually. Recurrence engine
|
||||
is Phase 2.
|
||||
|
||||
---
|
||||
|
||||
### profile.html — Own Profile
|
||||
|
||||
Access: All roles.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/my/profile → populate form
|
||||
GET /api/v1/users/:id/devices → list device tokens
|
||||
```
|
||||
|
||||
Actions:
|
||||
- Save profile: `PATCH /api/v1/users/:id` with `{ firstName, lastName, email }`
|
||||
- Change password: form with current + new password → `PUT /api/v1/my/password`
|
||||
- Revoke device: `DELETE /api/v1/users/:id/devices/:tokenId`
|
||||
|
||||
---
|
||||
|
||||
### settings.html — Owner Settings
|
||||
|
||||
Access: Owner only.
|
||||
|
||||
Tabs: Users | Branding | Storage | Devices
|
||||
|
||||
**Users tab:**
|
||||
```
|
||||
GET /api/v1/users → render user table
|
||||
```
|
||||
- Create user: inline form → `POST /api/v1/users`
|
||||
- Deactivate: `DELETE /api/v1/users/:id` (soft)
|
||||
- Change role: inline select → `PUT /api/v1/users/:id/role`
|
||||
- Reset password: inline form → `PUT /api/v1/users/:id/password`
|
||||
|
||||
**Branding tab:**
|
||||
```
|
||||
GET /api/v1/org/branding → populate color inputs + logo preview
|
||||
```
|
||||
- Color pickers (HTML `<input type="color">`) with live preview of timer phase colors
|
||||
- Save colors: `PATCH /api/v1/org/branding`
|
||||
- Logo upload: `POST /api/v1/org/logo`
|
||||
|
||||
**Storage tab:**
|
||||
```
|
||||
GET /api/v1/admin/storage → render disk usage bar + breakdown
|
||||
```
|
||||
Auto-refreshes every 5 minutes. Shows warning banner if `data.warning === true`.
|
||||
|
||||
**Devices tab:**
|
||||
All device tokens across all users in the org.
|
||||
```
|
||||
GET /api/v1/users → for each user, GET /api/v1/users/:id/devices
|
||||
```
|
||||
Revoke: `DELETE /api/v1/users/:id/devices/:tokenId`
|
||||
|
||||
---
|
||||
|
||||
### audit-log.html — Audit Log
|
||||
|
||||
Access: Owner only.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/audit-logs?page=1&limit=50 → render table
|
||||
```
|
||||
|
||||
Filter controls: action (dropdown), date range (from/to), user (dropdown), entity type.
|
||||
Any filter change: re-fetches with new params.
|
||||
|
||||
Expandable rows: click row → show full `details` JSON formatted.
|
||||
|
||||
"Export CSV" button: navigates to `GET /api/v1/audit-logs/export?<same filters>` (browser download).
|
||||
|
||||
---
|
||||
|
||||
### sysadmin.html — System Admin Panel
|
||||
|
||||
Access: SystemAdmin only.
|
||||
|
||||
Tabs: Organizations | Health
|
||||
|
||||
**Organizations tab:**
|
||||
```
|
||||
GET /api/v1/sysadmin/orgs → render org table
|
||||
```
|
||||
- Click org → expand detail: name, slug, timezone, features, user counts, license info
|
||||
- Edit org: inline form → `PATCH /api/v1/sysadmin/orgs/:id`
|
||||
|
||||
**Health tab:**
|
||||
```
|
||||
GET /api/v1/sysadmin/health → render health dashboard
|
||||
```
|
||||
Shows: version, uptime, DB migration status, disk stats, active timer sessions.
|
||||
Manual refresh button.
|
||||
|
||||
---
|
||||
|
||||
## Pages — Display Mode (Full-Screen TV)
|
||||
|
||||
These pages use `display.css` instead of `layout.css`. No nav drawer, no banner.
|
||||
They are opened from the management pages when a coach taps "Display" or "Launch".
|
||||
Full-screen API is requested on load: `document.documentElement.requestFullscreen()`.
|
||||
|
||||
### workout-display.html
|
||||
|
||||
Query param: `?id=<workoutId>`
|
||||
|
||||
CSS: `base.css`, `display.css`
|
||||
JS: `core.js`, `display.js`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts/:id → pass to Display.renderWorkout()
|
||||
```
|
||||
|
||||
Layout:
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ WORKOUT NAME DATE │ small top bar
|
||||
│ │
|
||||
│ [slot 1 description] 10 reps │ large text
|
||||
│ [slot 2 description] 12 reps │
|
||||
│ [slot 3 description] 8 reps │
|
||||
│ │
|
||||
│ [touch: back] [touch: close] │ invisible coach controls
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
`Display.startKeepAlive()` runs on load to prevent AirPlay stream freeze.
|
||||
|
||||
---
|
||||
|
||||
### timer-display.html
|
||||
|
||||
Query param: `?session=<sessionId>`
|
||||
|
||||
CSS: `base.css`, `display.css`
|
||||
JS: `core.js`, `socket-client.js`, `timer-display.js`
|
||||
|
||||
On load:
|
||||
```
|
||||
SocketClient.connect()
|
||||
TimerDisplay.init(sessionId) → joins socket room, registers event handlers
|
||||
```
|
||||
|
||||
Layout:
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ SET LAP 1/2 EXERCISE 2/5 SET 1/3 │ small status bar (phase label left)
|
||||
│ │
|
||||
│ 00:28 │ giant phase countdown
|
||||
│ │
|
||||
│ Total 14:32 │ smaller total time
|
||||
│ │
|
||||
│ [touch: stop — left edge, invisible] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Background color changes with phase (reads `--color-work`, `--color-rest`, `--color-move` CSS vars).
|
||||
10-second warning: countdown turns amber (`--color-warning`).
|
||||
|
||||
On `timer:complete`: background fades to dark, "DONE" displayed in center.
|
||||
On disconnect: `TimerDisplay.startLocalFallback(phaseEndTime)` continues countdown locally.
|
||||
|
||||
---
|
||||
|
||||
### crossfit-display.html
|
||||
|
||||
Query param: `?id=<crossfitWorkoutId>`
|
||||
|
||||
CSS: `base.css`, `display.css`
|
||||
JS: `core.js`, `display.js`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/crossfit-workouts/:id → pass to Display.renderCrossfit()
|
||||
```
|
||||
|
||||
Layout:
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ HERO WOD MURPH June 11 │ small top bar
|
||||
│ │
|
||||
│ 1. 1 mile run │ large numbered list
|
||||
│ 2. 100 pull-ups │
|
||||
│ 3. 200 push-ups │
|
||||
│ 4. 300 air squats │
|
||||
│ 5. 1 mile run │
|
||||
│ │
|
||||
│ [touch: close — right edge, invisible] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pages — Client Portal
|
||||
|
||||
CSS: `base.css`, `layout.css`, `components.css` (same shell, different nav links).
|
||||
|
||||
### my-workouts.html
|
||||
|
||||
Access: Client only.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/my/workouts?includeCompleted=false&page=1 → render workout cards
|
||||
```
|
||||
|
||||
Each card: workout name, scheduled date, item summary (exercise count), completion status.
|
||||
"Mark Complete" button: `POST /api/v1/clients/:ownId/workouts/:workoutId/complete`
|
||||
"View" button: expand inline to show full items list (including video players via streamUrl).
|
||||
|
||||
---
|
||||
|
||||
### my-schedule.html
|
||||
|
||||
Access: Client only.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/my/sessions?status=scheduled&startAfter=<today> → render session list
|
||||
```
|
||||
|
||||
Each card: title, coach name, date/time, location, shared notes.
|
||||
"Cancel" button (if session > 24h away): `POST /api/v1/clients/:ownId/sessions/:id/cancel`
|
||||
|
||||
---
|
||||
|
||||
## Navigation Config (core.js)
|
||||
|
||||
Nav links are defined in a config array in `core.js`. Role-based visibility is enforced client-side
|
||||
(cosmetic only — server enforces real access control).
|
||||
|
||||
```js
|
||||
const NAV_LINKS = [
|
||||
{ label: 'Dashboard', href: '/dashboard.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Videos', href: '/videos.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Workouts', href: '/workouts.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Timers', href: '/timers.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'CrossFit', href: '/crossfit.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Clients', href: '/clients.html', roles: ['Owner', 'Coach'], feature: 'client-management' },
|
||||
{ label: 'Calendar', href: '/calendar.html', roles: ['Owner', 'Coach'], feature: 'calendar' },
|
||||
{ label: 'My Workouts', href: '/my-workouts.html', roles: ['Client'] },
|
||||
{ label: 'My Schedule', href: '/my-schedule.html', roles: ['Client'], feature: 'calendar' },
|
||||
{ label: 'Settings', href: '/settings.html', roles: ['Owner'] },
|
||||
{ label: 'Audit Log', href: '/audit-log.html', roles: ['Owner'] },
|
||||
{ label: 'System Admin', href: '/sysadmin.html', roles: ['SystemAdmin'] },
|
||||
{ label: 'Profile', href: '/profile.html', roles: ['Owner', 'Coach', 'Client'] },
|
||||
{ label: 'Log Out', href: '#', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'],
|
||||
action: 'logout' },
|
||||
];
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
# VitFit V2 — Structure Index
|
||||
|
||||
Implementation blueprints. Read planning docs first, then these structure docs before writing code.
|
||||
|
||||
## Documents
|
||||
|
||||
| Document | What it covers |
|
||||
|----------|---------------|
|
||||
| [FILE_STRUCTURE.md](FILE_STRUCTURE.md) | Every file in the project with purpose, exports, and key behavior |
|
||||
| [BACKEND_METHODS.md](BACKEND_METHODS.md) | Method signatures for all core/ and module service files |
|
||||
| [API_ROUTES.md](API_ROUTES.md) | Every endpoint: method, path, auth, request body, response shape, errors |
|
||||
| [DATABASE_SCHEMA.md](DATABASE_SCHEMA.md) | Sequelize model definitions, associations, indexes, migration order |
|
||||
| [SOCKET_EVENTS.md](SOCKET_EVENTS.md) | Timer engine Socket.io events (server→client and client→server) |
|
||||
| [FRONTEND_MAP.md](FRONTEND_MAP.md) | Every HTML page: access roles, API calls on load, user actions, key JS behavior |
|
||||
| [TESTING.md](TESTING.md) | Test structure, unit/integration/socket/e2e test cases, helpers, scripts |
|
||||
|
||||
## Reading Order
|
||||
|
||||
1. `FILE_STRUCTURE.md` — get the big picture of what exists
|
||||
2. `DATABASE_SCHEMA.md` — understand the data shapes before reading services
|
||||
3. `BACKEND_METHODS.md` — understand what each service function does
|
||||
4. `API_ROUTES.md` — understand the contract between frontend and backend
|
||||
5. `SOCKET_EVENTS.md` — understand the timer real-time system
|
||||
6. `FRONTEND_MAP.md` — understand how each page uses the API
|
||||
7. `TESTING.md` — understand what must be tested and how
|
||||
|
||||
## Module Count
|
||||
|
||||
| Layer | Count |
|
||||
|-------|-------|
|
||||
| Backend modules | 10 (auth, users, org, videos, workouts, timers, crossfit, clients, audit, sysadmin) |
|
||||
| API endpoints | 55 |
|
||||
| Database tables | 13 |
|
||||
| Socket.io events | 8 |
|
||||
| Frontend pages | 22 |
|
||||
| Shared JS modules | 4 (core, socket-client, display, timer-display) |
|
||||
| CSS files | 4 (base, layout, components, display) |
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
- All modules are auto-loaded by `app.js` scanning `modules/*/routes.js`
|
||||
- All service functions throw `AppError` — routes never construct error responses directly
|
||||
- All routes call `core/audit.js log()` after successful mutations
|
||||
- `organizationId` is added to every DB query by the service layer, not the route layer
|
||||
- Display-mode pages (`*-display.html`) are the TV-facing views; all others are coach-facing
|
||||
- `core.js` runs on every page; `socket-client.js` only on display and timer pages
|
||||
@@ -0,0 +1,269 @@
|
||||
# VitFit V2 — Socket.io Event System
|
||||
|
||||
Socket.io is used exclusively for the timer engine. No other feature uses real-time events in V2.
|
||||
|
||||
---
|
||||
|
||||
## Connection and Authentication
|
||||
|
||||
Socket.io clients must authenticate at connection time by passing the JWT in the handshake:
|
||||
|
||||
```js
|
||||
// Client-side (socket-client.js)
|
||||
const socket = io('/', {
|
||||
auth: { token: localStorage.getItem('jwt') },
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 10000,
|
||||
reconnectionAttempts: Infinity
|
||||
});
|
||||
```
|
||||
|
||||
Server-side (core/socket.js):
|
||||
```js
|
||||
io.use((socket, next) => {
|
||||
const token = socket.handshake.auth.token;
|
||||
if (!token) return next(new Error('AUTH_REQUIRED'));
|
||||
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
|
||||
if (err) return next(new Error('AUTH_INVALID'));
|
||||
socket.data.user = user;
|
||||
next();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
On auth failure the socket is disconnected immediately. The client retries with exponential backoff using the reconnect config above.
|
||||
|
||||
---
|
||||
|
||||
## Rooms
|
||||
|
||||
Each active timer session gets its own Socket.io room named by `sessionId`:
|
||||
```
|
||||
timer_<timerId>_<timestamp>
|
||||
e.g. timer_3_1718273400000
|
||||
```
|
||||
|
||||
Clients join a room to receive events for that specific timer session.
|
||||
Multiple clients can join the same room (e.g., the coach's iPad + the display page both watching the same timer).
|
||||
|
||||
---
|
||||
|
||||
## Events: Client → Server
|
||||
|
||||
### `timer:join`
|
||||
Client requests to join a timer session room.
|
||||
|
||||
```js
|
||||
// Emit
|
||||
socket.emit('timer:join', { sessionId: 'timer_3_1718273400000' });
|
||||
```
|
||||
|
||||
Server handler (order of checks):
|
||||
1. Looks up the engine by `sessionId` in the active sessions Map.
|
||||
2. If not found: emits `timer:error { code: 'SESSION_NOT_FOUND' }` and returns.
|
||||
3. **Verifies `engine.orgId === socket.data.user.organizationId`.**
|
||||
If mismatch: emits `timer:error { code: 'SESSION_NOT_FOUND' }` — same error as missing,
|
||||
so cross-org probing cannot distinguish "exists but not yours" from "doesn't exist."
|
||||
4. Joins the socket to the room. Emits `timer:state` back to this socket only.
|
||||
|
||||
```js
|
||||
socket.emit('timer:state', engine.getState());
|
||||
```
|
||||
|
||||
This org check is required because sessionId format (`timer_<timerId>_<timestamp>`) is
|
||||
guessable by anyone who knows a timerId. Without it, a user from Org B could observe
|
||||
Org A's timer state.
|
||||
|
||||
---
|
||||
|
||||
### `timer:leave`
|
||||
Client leaves a timer room. Server removes from room.
|
||||
|
||||
```js
|
||||
socket.emit('timer:leave', { sessionId: 'timer_3_1718273400000' });
|
||||
```
|
||||
|
||||
No server response.
|
||||
|
||||
---
|
||||
|
||||
## Events: Server → Client
|
||||
|
||||
### `timer:state`
|
||||
Full state snapshot. Sent on `timer:join` to the joining socket, and when a client reconnects.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
status: 'running', // 'idle' | 'running' | 'paused' | 'complete'
|
||||
phase: 'set', // 'set' | 'rest' | 'move'
|
||||
currentLap: 1,
|
||||
currentExercise: 2,
|
||||
currentSet: 1,
|
||||
phaseEndTime: 1718273430000, // Unix ms — client uses Date.now() diff
|
||||
sessionEndTime: 1718275200000, // Unix ms — total session end
|
||||
phaseRemainingMs: 28500,
|
||||
totalRemainingMs: 1725000,
|
||||
config: {
|
||||
lapCount: 2, exerciseCount: 5, setCount: 3,
|
||||
setTime: 30, restTime: 10, moveTime: 15, totalTime: 1800
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Client uses `phaseEndTime` (absolute timestamp) to drive local countdown. If the socket goes quiet, the client can continue using `Date.now() - phaseEndTime` without server involvement.
|
||||
|
||||
---
|
||||
|
||||
### `timer:tick`
|
||||
Emitted once per second while timer is running. Lightweight — only changing fields.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
phaseRemainingMs: 27500,
|
||||
totalRemainingMs: 1724000
|
||||
}
|
||||
```
|
||||
|
||||
Client uses this to keep displays in sync. If ticks stop arriving (disconnect), client falls back to computing from `phaseEndTime` received in the last `timer:state`.
|
||||
|
||||
---
|
||||
|
||||
### `timer:phase-change`
|
||||
Emitted when phase transitions (set→rest, rest→move, move→set).
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
phase: 'rest',
|
||||
currentLap: 1,
|
||||
currentExercise: 2,
|
||||
currentSet: 1,
|
||||
phaseEndTime: 1718273440000, // new phase end time
|
||||
phaseRemainingMs: 10000
|
||||
}
|
||||
```
|
||||
|
||||
Client uses this to update the display color, label, and reset the phase countdown.
|
||||
Phase colors are read from CSS custom properties (set by branding loader) — no color data in the event.
|
||||
|
||||
---
|
||||
|
||||
### `timer:complete`
|
||||
Emitted when all laps/exercises/sets are done.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
totalElapsedSeconds: 1798
|
||||
}
|
||||
```
|
||||
|
||||
Client shows completion state. No further tick events will arrive.
|
||||
Timer engine is cleaned up server-side after emitting this.
|
||||
|
||||
---
|
||||
|
||||
### `timer:stopped`
|
||||
Emitted when a coach or owner manually stops the timer via `DELETE /api/v1/timers/session`.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
elapsedSeconds: 342,
|
||||
stoppedByUserId: 2
|
||||
}
|
||||
```
|
||||
|
||||
Client shows stopped state. Distinct from `timer:complete` — the timer did not finish naturally.
|
||||
|
||||
---
|
||||
|
||||
### `timer:error`
|
||||
Emitted when client attempts an invalid operation.
|
||||
|
||||
```js
|
||||
{
|
||||
code: 'SESSION_NOT_FOUND',
|
||||
message: 'No active timer session with that ID.'
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Client-Side Event Handling (timer-display.js)
|
||||
|
||||
```
|
||||
socket connects
|
||||
→ socket.emit('timer:join', { sessionId })
|
||||
→ receives timer:state → render full display state
|
||||
→ store phaseEndTime for local fallback
|
||||
|
||||
socket receives timer:tick
|
||||
→ update phaseRemainingMs display (smooth update, no flicker)
|
||||
|
||||
socket receives timer:phase-change
|
||||
→ update phase label, color, new phaseEndTime, reset phase countdown
|
||||
→ play phase-change sound (if audio unlocked by prior coach tap)
|
||||
|
||||
socket receives timer:complete
|
||||
→ show completion state
|
||||
→ stop local fallback interval if running
|
||||
|
||||
socket receives timer:stopped
|
||||
→ show stopped state
|
||||
|
||||
socket disconnects
|
||||
→ start localFallback(phaseEndTime):
|
||||
every animationFrame: remaining = phaseEndTime - Date.now()
|
||||
if remaining <= 0: show phase-change estimate (cannot know new phase without server)
|
||||
show "Offline - running locally" indicator
|
||||
→ Socket.io reconnects automatically (exponential backoff, infinite attempts)
|
||||
|
||||
socket reconnects
|
||||
→ stop localFallback
|
||||
→ socket.emit('timer:join', { sessionId }) again to re-sync
|
||||
→ receives fresh timer:state → updates display with authoritative state
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Disconnect / Reconnect Protocol
|
||||
|
||||
The client's `socket-client.js` wraps the Socket.io client with:
|
||||
|
||||
1. On `disconnect`: call registered `onDisconnect()` callback (page shows offline indicator)
|
||||
2. On `connect`: call registered `onReconnect()` callback — page re-joins its room and re-syncs
|
||||
3. Socket is created once per page load, not recreated
|
||||
|
||||
For the display pages (timer-display.html, workout-display.html, crossfit-display.html):
|
||||
- Offline indicator is a slim banner at top of screen: `⚠ Reconnecting...`
|
||||
- Content remains fully visible underneath — gym display does not go dark
|
||||
- Indicator disappears automatically when reconnected
|
||||
|
||||
---
|
||||
|
||||
## Active Session Registry (server-side)
|
||||
|
||||
Timer sessions live in a `Map<sessionId, TimerEngine>` in `modules/timers/service.js`.
|
||||
This is in-process memory — sessions do not survive a server restart.
|
||||
|
||||
Consequence: if the server restarts while a timer is running, the session is gone.
|
||||
Clients will receive a `timer:error SESSION_NOT_FOUND` when they reconnect and try to re-join.
|
||||
The display page shows a "Session ended — reconnect to start a new timer" message.
|
||||
The coach starts a new timer session from the timers list page.
|
||||
|
||||
For the current use case (single gym, single timer at a time) this is acceptable.
|
||||
A persistent session store (Redis or DB-backed) is a future enhancement if needed.
|
||||
|
||||
---
|
||||
|
||||
## One Active Session Per Org
|
||||
|
||||
Only one timer session can be running per organization at a time.
|
||||
|
||||
`launchTimer()` checks for an existing active session before creating a new one.
|
||||
If one exists: `AppError('CONFLICT', 'A timer is already running. Stop it before launching another.', 409)`.
|
||||
|
||||
The active session for an org is determined by scanning the in-memory Map for entries matching `orgId`.
|
||||
@@ -0,0 +1,344 @@
|
||||
# VitFit V2 — Test Structure
|
||||
|
||||
---
|
||||
|
||||
## Directory Layout
|
||||
|
||||
```
|
||||
/home/ubuntu/site/
|
||||
└── tests/
|
||||
├── helpers/
|
||||
│ ├── db.js In-memory SQLite setup/teardown for unit + integration tests
|
||||
│ ├── auth.js Generate test JWTs for any role
|
||||
│ ├── factories.js Seeders: makeOrg(), makeUser(role), makeVideo(), makeTimer(), etc.
|
||||
│ └── socket.js Create test Socket.io server + client pairs
|
||||
├── unit/
|
||||
│ ├── timer-engine.test.js
|
||||
│ ├── validate-mime.test.js
|
||||
│ ├── storage.test.js
|
||||
│ ├── contrast.test.js
|
||||
│ └── respond.test.js
|
||||
├── integration/
|
||||
│ ├── 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
|
||||
│ └── migrations.test.js
|
||||
├── socket/
|
||||
│ └── timer-engine.socket.test.js
|
||||
└── e2e/
|
||||
└── display-burn-in.test.js
|
||||
```
|
||||
|
||||
Test runner: **Jest** with `--forceExit` flag (cleans up open DB handles).
|
||||
|
||||
---
|
||||
|
||||
## helpers/db.js
|
||||
|
||||
```js
|
||||
createTestDb(): Promise<{ sequelize, models }>
|
||||
```
|
||||
Creates an in-memory SQLite DB (`:memory:`), runs all migrations, returns sequelize instance.
|
||||
Each test file calls this in `beforeAll` and calls `sequelize.close()` in `afterAll`.
|
||||
Migrations run against in-memory DB, validating that the migration chain is complete and idempotent.
|
||||
|
||||
```js
|
||||
seedOrg(sequelize): Promise<{ org, branding }>
|
||||
seedUser(sequelize, orgId, role, overrides?): Promise<User>
|
||||
seedVideo(sequelize, orgId, overrides?): Promise<Video>
|
||||
```
|
||||
Minimal seed helpers. `factories.js` builds on these with realistic defaults.
|
||||
|
||||
---
|
||||
|
||||
## helpers/auth.js
|
||||
|
||||
```js
|
||||
makeJwt(user: Partial<User>): string
|
||||
```
|
||||
Signs a short-lived (5-minute) test JWT. Does not hit the DB.
|
||||
Usage: `const token = makeJwt({ id: 1, role: 'Coach', organizationId: 1 });`
|
||||
|
||||
```js
|
||||
authHeader(token: string): { Authorization: string }
|
||||
```
|
||||
Returns `{ Authorization: 'Bearer <token>' }` for use in supertest requests.
|
||||
|
||||
---
|
||||
|
||||
## Unit Tests
|
||||
|
||||
### tests/unit/timer-engine.test.js
|
||||
|
||||
Tests the `TimerEngine` state machine in isolation (no real Socket.io).
|
||||
|
||||
```
|
||||
✓ starts in 'idle' status
|
||||
✓ transitions to 'running' on start()
|
||||
✓ phase advances set → rest after setTime elapses
|
||||
✓ phase advances rest → move after restTime elapses
|
||||
✓ phase advances move → set, increments currentSet
|
||||
✓ increments currentExercise after all sets complete
|
||||
✓ increments currentLap after all exercises complete
|
||||
✓ emits timer:complete (not timer:stopped) on natural completion
|
||||
✓ emits timer:stopped (not timer:complete) on manual stop()
|
||||
✓ complete() does NOT call stop() — no double-event emission
|
||||
✓ getState() returns correct snapshot mid-run
|
||||
✓ skips rest phase when restTime = 0
|
||||
✓ skips move phase when moveTime = 0
|
||||
✓ phaseEndTime is an absolute timestamp (not a delta)
|
||||
```
|
||||
|
||||
Uses a mock `io` object that records emitted events.
|
||||
|
||||
### tests/unit/validate-mime.test.js
|
||||
|
||||
```
|
||||
✓ accepts first 12 bytes of a real MP4 file (ftyp magic bytes)
|
||||
✓ accepts first 12 bytes of a MOV file
|
||||
✓ accepts first 12 bytes of an M4V file
|
||||
✓ rejects a WebM file
|
||||
✓ rejects a text file renamed to .mp4
|
||||
✓ rejects an empty buffer
|
||||
✓ throws UPLOAD_TYPE_INVALID (not a generic error)
|
||||
✓ reads only from file path, does NOT load whole file into memory
|
||||
```
|
||||
|
||||
Uses real minimal binary fixtures (12-byte magic byte sequences only).
|
||||
|
||||
### tests/unit/storage.test.js
|
||||
|
||||
```
|
||||
✓ returns warning: false when free > STORAGE_WARN_BYTES
|
||||
✓ returns warning: true when free < STORAGE_WARN_BYTES
|
||||
✓ caches result for 60 seconds (second call within 60s returns cached value)
|
||||
✓ returns fresh result after 60 second cache expiry
|
||||
✓ checkUploadAllowed middleware returns 507 when warning: true
|
||||
✓ checkUploadAllowed middleware calls next() when warning: false
|
||||
```
|
||||
|
||||
Mocks `check-disk-space` to return controlled values.
|
||||
|
||||
### tests/unit/contrast.test.js
|
||||
|
||||
Tests `validateContrastRatio()` in org service.
|
||||
|
||||
```
|
||||
✓ #00FF88 on #1a1a1a passes (>= 4.5:1)
|
||||
✓ #000000 on #1a1a1a fails (ratio too low)
|
||||
✓ #FFFFFF on #1a1a1a passes
|
||||
✓ #777777 on #1a1a1a fails
|
||||
✓ invalid hex throws VALIDATION_FAILED
|
||||
✓ empty string throws VALIDATION_FAILED
|
||||
```
|
||||
|
||||
### tests/unit/respond.test.js
|
||||
|
||||
```
|
||||
✓ ok() sends 200 with { data }
|
||||
✓ created() sends 201 with { data }
|
||||
✓ collection() sends 200 with { data, meta } including correct totalPages
|
||||
✓ noContent() sends 204 with no body
|
||||
✓ err() sends correct status with { error: { code, message, field } }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Tests
|
||||
|
||||
All integration tests use `supertest` against a real Express app with an in-memory SQLite DB.
|
||||
No network calls. No real files written to disk (multer storage overridden to use `/tmp`).
|
||||
|
||||
### tests/integration/migrations.test.js
|
||||
|
||||
**Critical test — run before all others.**
|
||||
|
||||
```
|
||||
✓ migration 001 (baseline) is idempotent — runs twice without error
|
||||
✓ migration 002+ run in order without error
|
||||
✓ all expected tables exist after full migration
|
||||
✓ all expected columns exist on each table
|
||||
✓ running db:migrate on already-migrated DB makes no changes
|
||||
✓ V1-compatible data inserted before migrations is preserved after
|
||||
```
|
||||
|
||||
### tests/integration/auth.test.js
|
||||
|
||||
```
|
||||
✓ POST /auth/login returns jwt on valid credentials
|
||||
✓ POST /auth/login returns LOGIN_FAILED on bad password
|
||||
✓ POST /auth/login returns LOGIN_FAILED on inactive user
|
||||
✓ POST /auth/login rate-limits after 10 attempts
|
||||
✓ POST /auth/login with rememberDevice returns deviceToken
|
||||
✓ POST /auth/device-login returns new jwt + rotated token
|
||||
✓ POST /auth/device-login returns AUTH_DEVICE_TOKEN_INVALID on revoked token
|
||||
✓ POST /auth/device-login returns AUTH_DEVICE_TOKEN_INVALID on expired token
|
||||
✓ POST /auth/refresh-token returns new jwt
|
||||
✓ POST /auth/logout returns 204 and logs audit event
|
||||
✓ Authenticated request with valid jwt returns 200
|
||||
✓ Authenticated request with no jwt returns 401
|
||||
✓ Authenticated request with expired jwt returns 401
|
||||
```
|
||||
|
||||
### tests/integration/users.test.js
|
||||
|
||||
```
|
||||
✓ GET /users returns paginated list for Owner
|
||||
✓ GET /users returns 403 for Coach
|
||||
✓ POST /users creates user with hashed password
|
||||
✓ POST /users returns 409 on duplicate username
|
||||
✓ DELETE /users/:id deactivates user (does not hard delete)
|
||||
✓ DELETE /users/:id returns LAST_OWNER_PROTECTED if last Owner
|
||||
✓ DELETE /users/:id revokes all device tokens for the user
|
||||
✓ PUT /users/:id/role returns LAST_OWNER_PROTECTED when demoting last Owner
|
||||
✓ PUT /users/:id/role returns AUTH_FORBIDDEN when Owner tries to change own role
|
||||
✓ PUT /users/:id/password re-hashes password
|
||||
✓ PUT /api/v1/my/password succeeds with correct currentPassword
|
||||
✓ PUT /api/v1/my/password returns 401 with wrong currentPassword
|
||||
✓ Cross-org: user from org B cannot be found by org A
|
||||
```
|
||||
|
||||
### tests/integration/videos.test.js
|
||||
|
||||
```
|
||||
✓ GET /videos returns only videos for requesting org
|
||||
✓ GET /videos filters by category
|
||||
✓ POST /videos accepts valid MP4 (multer disk + magic-byte check)
|
||||
✓ POST /videos rejects non-video file (UPLOAD_TYPE_INVALID)
|
||||
✓ POST /videos returns 507 when disk below threshold
|
||||
✓ DELETE /videos/:id removes DB record and file
|
||||
✓ DELETE /videos/:id returns 404 for wrong org
|
||||
✓ GET /videos/stream/:filename returns 206 with Range header
|
||||
✓ GET /videos/stream/:filename returns 200 without Range header
|
||||
✓ GET /videos/stream/../secret.txt returns 400 (path traversal blocked)
|
||||
✓ GET /videos/stream/:filename returns 404 for filename not in org's DB
|
||||
```
|
||||
|
||||
### tests/integration/workouts.test.js
|
||||
|
||||
```
|
||||
✓ GET /workouts/today uses org timezone, not server local time
|
||||
✓ GET /workouts/today returns workouts for org's "today" across DST boundary
|
||||
✓ POST /workouts returns VALIDATION_FAILED if video ID belongs to different org
|
||||
✓ DELETE /workouts/:id blocks Coach from deleting another Coach's workout
|
||||
✓ DELETE /workouts/:id allows Owner to delete any workout
|
||||
✓ GET /workouts includes null for deleted video slots (LEFT JOIN)
|
||||
```
|
||||
|
||||
### tests/integration/timers.test.js
|
||||
|
||||
```
|
||||
✓ POST /timers/:id/launch creates session and returns sessionId
|
||||
✓ POST /timers/:id/launch returns 409 if a session already active for org
|
||||
✓ DELETE /timers/session stops active session
|
||||
✓ Timer session not found after server restart (in-memory, expected)
|
||||
```
|
||||
|
||||
### tests/integration/clients.test.js
|
||||
|
||||
```
|
||||
✓ Coach only sees own clients
|
||||
✓ Owner sees all clients in org
|
||||
✓ Client cannot access /clients route
|
||||
✓ POST /clients/:id/workouts validates videoId belongs to org
|
||||
✓ DELETE /clients/:id/workouts/:id soft-deletes (row remains, deletedAt set)
|
||||
✓ GET /clients/:id/workouts excludes coachNotes when requester is client
|
||||
✓ POST /clients/:id/sessions/cancel returns 400 if < 24h until session (client)
|
||||
✓ POST /clients/:id/sessions/cancel succeeds for coach regardless of time
|
||||
✓ Feature flag client-management: returns 403 when flag absent
|
||||
```
|
||||
|
||||
### tests/integration/audit.test.js
|
||||
|
||||
```
|
||||
✓ video.upload event recorded after successful upload
|
||||
✓ auth.login.failed recorded on bad password
|
||||
✓ user.create recorded when Owner creates user
|
||||
✓ Audit log failures do not break the parent request
|
||||
✓ GET /audit-logs returns 403 for Coach
|
||||
✓ GET /audit-logs/export returns CSV with correct headers
|
||||
✓ Audit records survive even if the referenced user is deactivated
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Socket Tests
|
||||
|
||||
### tests/socket/timer-engine.socket.test.js
|
||||
|
||||
Uses a real Socket.io server bound to a random port + a test client.
|
||||
|
||||
```
|
||||
✓ Client receives timer:state on timer:join
|
||||
✓ Client receives timer:tick events after start
|
||||
✓ tick events arrive at most once per second
|
||||
✓ Client receives timer:phase-change on phase transition
|
||||
✓ Client receives timer:complete on natural completion, NOT timer:stopped
|
||||
✓ Client receives timer:stopped on manual stop(), NOT timer:complete
|
||||
✓ Reconnected client receives timer:state after timer:join re-emit
|
||||
✓ timer:error SESSION_NOT_FOUND emitted for unknown sessionId
|
||||
✓ unauthenticated socket is disconnected immediately
|
||||
✓ socket from different org cannot join another org's timer room
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## E2E / Burn-In Test
|
||||
|
||||
### tests/e2e/display-burn-in.test.js
|
||||
|
||||
Long-running test. Only run manually (`npm run test:burnin`). Not in CI.
|
||||
|
||||
Uses Playwright (headless Safari via WebKit engine) to simulate the iPad kiosk scenario.
|
||||
|
||||
```
|
||||
✓ App loads and authenticates via device token
|
||||
✓ Timer display page opens and joins socket room
|
||||
✓ Timer runs for its full configured duration (uses a 60-second test timer)
|
||||
✓ phase:change events fire on schedule
|
||||
✓ timer:complete fires at end, NOT timer:stopped
|
||||
✓ DOM is not rebuilt during timer run (MutationObserver counts mutations < threshold)
|
||||
✓ Memory does not grow > 20 MB over 60-second run (page.metrics())
|
||||
✓ After simulated disconnect and reconnect, timer re-syncs correctly
|
||||
✓ AirPlay keep-alive animation is present in the DOM (CSS animation detected)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Test Scripts (package.json)
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"test": "jest tests/unit tests/integration tests/socket --forceExit",
|
||||
"test:unit": "jest tests/unit --forceExit",
|
||||
"test:int": "jest tests/integration --forceExit",
|
||||
"test:socket": "jest tests/socket --forceExit",
|
||||
"test:burnin": "jest tests/e2e/display-burn-in.test.js --forceExit --testTimeout=300000",
|
||||
"test:ci": "jest tests/unit tests/integration tests/socket --forceExit --ci --coverage"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`test:burnin` is excluded from `test` and `test:ci` — it's a manual check, not a gate.
|
||||
|
||||
---
|
||||
|
||||
## Test Dependencies (devDependencies only)
|
||||
|
||||
```json
|
||||
{
|
||||
"jest": "^29",
|
||||
"supertest": "^6",
|
||||
"playwright": "^1"
|
||||
}
|
||||
```
|
||||
|
||||
No test framework is added to `dependencies` — tests only run in the dev environment.
|
||||
Playwright is installed separately for the burn-in test: `npx playwright install webkit`.
|
||||
Reference in New Issue
Block a user