diff --git a/V2/planning/ADDITIONAL_CONSIDERATIONS.md b/V2/planning/ADDITIONAL_CONSIDERATIONS.md new file mode 100644 index 0000000..508993a --- /dev/null +++ b/V2/planning/ADDITIONAL_CONSIDERATIONS.md @@ -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. diff --git a/V2/planning/API_STANDARDS.md b/V2/planning/API_STANDARDS.md new file mode 100644 index 0000000..ea3fde6 --- /dev/null +++ b/V2/planning/API_STANDARDS.md @@ -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 +``` + +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"` | diff --git a/V2/planning/ARCHITECTURE.md b/V2/planning/ARCHITECTURE.md index 1afb111..52c831d 100644 --- a/V2/planning/ARCHITECTURE.md +++ b/V2/planning/ARCHITECTURE.md @@ -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()`) diff --git a/V2/planning/DATA_MODEL.md b/V2/planning/DATA_MODEL.md index f3fcbdf..bc04ca8 100644 --- a/V2/planning/DATA_MODEL.md +++ b/V2/planning/DATA_MODEL.md @@ -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. diff --git a/V2/planning/DESIGN_SYSTEM.md b/V2/planning/DESIGN_SYSTEM.md new file mode 100644 index 0000000..89985dd --- /dev/null +++ b/V2/planning/DESIGN_SYSTEM.md @@ -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 `` every 10s — DOM text change keeps AirPlay active without animation). diff --git a/V2/planning/DISPLAY_DESIGN.md b/V2/planning/DISPLAY_DESIGN.md index 4d992a5..2d92b0a 100644 --- a/V2/planning/DISPLAY_DESIGN.md +++ b/V2/planning/DISPLAY_DESIGN.md @@ -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 | diff --git a/V2/planning/OPERATIONS.md b/V2/planning/OPERATIONS.md new file mode 100644 index 0000000..3d6c3df --- /dev/null +++ b/V2/planning/OPERATIONS.md @@ -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. diff --git a/V2/planning/README.md b/V2/planning/README.md index 68dc24c..e865c89 100644 --- a/V2/planning/README.md +++ b/V2/planning/README.md @@ -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 diff --git a/V2/planning/ROLES_AND_PERMISSIONS.md b/V2/planning/ROLES_AND_PERMISSIONS.md index daade2f..07c207f 100644 --- a/V2/planning/ROLES_AND_PERMISSIONS.md +++ b/V2/planning/ROLES_AND_PERMISSIONS.md @@ -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 | diff --git a/V2/structure/API_ROUTES.md b/V2/structure/API_ROUTES.md new file mode 100644 index 0000000..0da82e4 --- /dev/null +++ b/V2/structure/API_ROUTES.md @@ -0,0 +1,982 @@ +# VitFit V2 — API Routes + +All routes prefixed `/api/v1/`. Auth header: `Authorization: Bearer `. +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. diff --git a/V2/structure/BACKEND_METHODS.md b/V2/structure/BACKEND_METHODS.md new file mode 100644 index 0000000..ff7ab12 --- /dev/null +++ b/V2/structure/BACKEND_METHODS.md @@ -0,0 +1,887 @@ +# VitFit V2 — Backend Method Maps + +TypeScript-style signatures are used for clarity. The implementation is JavaScript (CommonJS). +`Promise` return types indicate async functions. All service functions throw `AppError` on failure. + +--- + +## core/db.js + +```js +initDb(): Promise +``` +Creates Sequelize instance. Runs PRAGMAs. Returns sequelize. +``` +PRAGMA journal_mode = WAL +PRAGMA busy_timeout = 5000 +PRAGMA foreign_keys = ON +``` + +```js +runMigrations(): Promise +``` +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 `. 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 +``` +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 +``` +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 +``` +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` 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 +``` +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 +``` +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 +``` +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 +``` +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 +``` +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 +``` +`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 +``` +Updates own profile fields. Logs `user.profile.update` audit with before/after. + +```js +getDeviceTokens(userId: number, orgId: number): Promise +``` +Returns non-revoked device tokens for a user. Returns metadata only — token hash never returned. + +```js +revokeDeviceToken(tokenId: number, userId: number, orgId: number): Promise +``` +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 +``` +Returns org record. Includes Branding via eager load. + +```js +updateOrg( + orgId: number, + data: { name?, timezone?, licenseOwner?, licenseEmail? }, + actorId: number +): Promise +``` +Validates timezone is a valid IANA string (check against `Intl.supportedValuesOf('timeZone')`). +Logs `org.update` audit. + +```js +getBranding(orgId: number): Promise +``` +Returns branding for org. Creates default branding if not exists. + +```js +updateBranding( + orgId: number, + data: { appName?, primaryColor?, secondaryColor?, workColor?, restColor?, moveColor? }, + actorId: number +): Promise +``` +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 +``` +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