Files
2026-06-11 10:52:07 -04:00

983 lines
19 KiB
Markdown

# VitFit V2 — API Routes
All routes prefixed `/api/v1/`. Auth header: `Authorization: Bearer <jwt>`.
Response envelopes: see `API_STANDARDS.md`. Dates: ISO 8601 UTC strings.
Legend: `[T]` = requires authenticateToken `[O]` = Owner+ `[SA]` = SystemAdmin only `[F:x]` = requires feature flag
---
## Auth — /api/v1/auth
### POST /api/v1/auth/login
No auth required.
Request:
```json
{
"username": "coach1",
"password": "secret",
"rememberDevice": true,
"deviceName": "Gym iPad",
"deviceType": "kiosk"
}
```
`rememberDevice`, `deviceName`, `deviceType` are optional (default: no device token).
Response 200:
```json
{
"data": {
"jwt": "eyJ...",
"deviceToken": "a3f9...",
"user": { "id": 1, "username": "coach1", "role": "Coach", "firstName": "Jason", "organizationId": 1 }
}
}
```
`deviceToken` only present when `rememberDevice: true`. Store in localStorage as `deviceToken`.
Errors: `LOGIN_FAILED` (401), rate-limited after 10 attempts/15 min (429).
Two independent rate limits apply:
- **Per-IP** — `express-rate-limit` middleware, 10 req/15 min per source IP.
- **Per-username** — tracked in process memory by auth service. 10 failed attempts for the
same `username` string within 15 minutes triggers immediate `LOGIN_FAILED` regardless of IP.
Resets automatically on success or after 15 minutes. Prevents targeted account brute-force
from rotating IPs.
---
### POST /api/v1/auth/device-login
No auth required. Used on page load to silently re-authenticate.
Request:
```json
{ "deviceToken": "a3f9..." }
```
Response 200:
```json
{
"data": {
"jwt": "eyJ...",
"deviceToken": "b7e2...",
"user": { "id": 1, "username": "coach1", "role": "Coach", "organizationId": 1 }
}
}
```
Old token is invalidated. New token replaces it in localStorage.
Errors: `AUTH_DEVICE_TOKEN_INVALID` (401).
Rate limited: same 10 req/15 min per-IP limiter as `/auth/login`. The token search space
(32-byte random = 2²⁵⁶) makes brute force computationally infeasible; rate limiting prevents
server load abuse and probing.
---
### POST /api/v1/auth/refresh-token
`[T]`
No request body. Called by `core.js` when token is within 1 hour of expiry.
Response 200:
```json
{ "data": { "jwt": "eyJ..." } }
```
---
### POST /api/v1/auth/logout
`[T]`
No request body. Logs audit event. JWT invalidation is client-side (delete from localStorage).
Response 204.
---
## Users — /api/v1/users
### GET /api/v1/users
`[T]` `[O]`
Query: `?role=Coach&isActive=true&page=1&limit=50`
Response 200 (collection):
```json
{
"data": [
{ "id": 2, "username": "jsmith", "email": "j@gym.com", "firstName": "John", "lastName": "Smith",
"role": "Coach", "isActive": true, "lastLoginAt": "2025-06-10T14:22:00.000Z" }
],
"meta": { "total": 4, "page": 1, "limit": 50, "totalPages": 1 }
}
```
---
### POST /api/v1/users
`[T]` `[O]`
Request:
```json
{
"username": "newcoach",
"email": "coach@gym.com",
"firstName": "Mike",
"lastName": "Jones",
"password": "initialPass123",
"role": "Coach"
}
```
`email`, `firstName`, `lastName` optional. `role` must be `Owner`, `Coach`, or `Client`.
Response 201: `{ "data": { ...user } }`
Errors: `CONFLICT` (409 duplicate username), `VALIDATION_FAILED` (400).
---
### GET /api/v1/users/:id
`[T]` `[O]`
Response 200: `{ "data": { ...user, deviceTokens: [ { id, deviceName, deviceType, lastUsedAt, expiresAt } ] } }`
Errors: `NOT_FOUND` (404).
---
### PATCH /api/v1/users/:id
`[T]` Own profile only (any role) OR `[O]` for any user in org.
Request (any subset):
```json
{ "firstName": "Jason", "lastName": "A", "email": "new@email.com" }
```
Response 200: `{ "data": { ...updatedUser } }`
---
### DELETE /api/v1/users/:id
`[T]` `[O]`
Soft deactivate. Not a true delete.
Response 204.
Errors: `LAST_OWNER_PROTECTED` (400), `NOT_FOUND` (404).
---
### PUT /api/v1/users/:id/role
`[T]` `[O]`
Request: `{ "role": "Owner" }`
Response 200: `{ "data": { ...user } }`
Errors: `LAST_OWNER_PROTECTED` (400), `AUTH_FORBIDDEN` (403 if Owner tries to self-change).
---
### PUT /api/v1/users/:id/password
`[T]` `[O]`
Request: `{ "newPassword": "newPass456" }`
Response 204.
---
### GET /api/v1/users/:id/devices
`[T]` Own devices (any role) OR `[O]` for any user in org.
Response 200:
```json
{
"data": [
{ "id": 3, "deviceName": "Gym iPad", "deviceType": "kiosk",
"lastUsedAt": "2025-06-11T08:00:00.000Z", "expiresAt": "2025-09-09T08:00:00.000Z" }
]
}
```
Token hash is never returned.
---
### DELETE /api/v1/users/:id/devices/:tokenId
`[T]` Own devices (any role) OR `[O]`.
Response 204.
---
## Organization — /api/v1/org
### GET /api/v1/org
`[T]`
Response 200:
```json
{
"data": {
"id": 1, "name": "CrossFit Downtown", "slug": "crossfit-downtown",
"timezone": "America/New_York", "features": ["client-management", "calendar"],
"licenseOwner": "Jason A", "licenseEmail": "jason@gym.com"
}
}
```
---
### PATCH /api/v1/org
`[T]` `[O]`
Request (any subset): `{ "name": "CrossFit Uptown", "timezone": "America/Chicago" }`
Response 200: `{ "data": { ...org } }`
Errors: `VALIDATION_FAILED` (400 invalid timezone).
---
### GET /api/v1/org/branding
`[T]`
Response 200:
```json
{
"data": {
"appName": "CrossFit Downtown",
"logoPath": "/api/v1/org/logo",
"primaryColor": "#00FF88",
"secondaryColor": "#4488FF",
"workColor": "#00FF88",
"restColor": "#4488FF",
"moveColor": "#FF4444"
}
}
```
`logoPath` is `null` if no custom logo.
---
### PATCH /api/v1/org/branding
`[T]` `[O]`
Request (any subset):
```json
{ "appName": "My Gym", "primaryColor": "#FF0066", "workColor": "#FF0066" }
```
Response 200: `{ "data": { ...branding } }`
Errors: `VALIDATION_FAILED` (400, lists each color that fails contrast check).
---
### POST /api/v1/org/logo
`[T]` `[O]`
Body: `multipart/form-data`, field `logo` (image file).
Response 200: `{ "data": { "logoPath": "/api/v1/org/logo" } }`
---
### GET /api/v1/org/logo
`[T]`
Streams logo file. Returns 404 if no custom logo set.
---
## Videos — /api/v1/videos
### GET /api/v1/videos
`[T]` Coaches and above.
Query: `?category=Arm+Exercises&page=1&limit=50`
Response 200 (collection):
```json
{
"data": [
{ "id": 5, "filename": "1718000000_abc123.mp4", "description": "Barbell curl",
"category": "Arm Exercises", "mimeType": "video/mp4",
"fileSizeBytes": 45020000, "createdAt": "2025-06-01T12:00:00.000Z",
"streamUrl": "/api/v1/videos/stream/1718000000_abc123.mp4" }
],
"meta": { ... }
}
```
`streamUrl` is included so the frontend doesn't need to construct URLs.
---
### POST /api/v1/videos
`[T]` Coach+.
Body: `multipart/form-data`. Fields: `video` (file), `description` (string), `category` (string).
Pre-upload middleware: `checkUploadAllowed` (507 if disk low), multer file size limit.
Response 201: `{ "data": { ...video, streamUrl } }`
Errors: `UPLOAD_TYPE_INVALID` (400), `UPLOAD_SIZE_EXCEEDED` (400), `STORAGE_INSUFFICIENT` (507).
---
### DELETE /api/v1/videos/:id
`[T]` Coach+.
Response 204.
Errors: `NOT_FOUND` (404).
---
### GET /api/v1/videos/stream/:filename
`[T]`
Streams video file. Supports `Range` header for seek (required by Safari).
Response 200 (full) or 206 (partial/range).
Headers include `Accept-Ranges: bytes`, `Content-Type` from stored mimeType.
Errors: `NOT_FOUND` (404 — file not in DB for this org, or doesn't exist on disk).
---
### GET /api/v1/categories
`[T]` Coach+.
Response 200: `{ "data": [ { "id": 1, "name": "Arm Exercises" }, ... ] }`
---
### POST /api/v1/categories
`[T]` Coach+.
Request: `{ "name": "Mobility" }`
Response 201: `{ "data": { "id": 7, "name": "Mobility" } }`
Errors: `CONFLICT` (409).
---
### DELETE /api/v1/categories/:id
`[T]` Coach+.
Response 204.
Errors: `CONFLICT` (409 if videos exist in this category), `NOT_FOUND` (404).
---
## Workouts (Group Display) — /api/v1/workouts
### GET /api/v1/workouts
`[T]` Coach+.
Query: `?page=1&limit=20`
Response 200 (collection):
```json
{
"data": [
{
"id": 10, "name": "Tuesday WOD", "workoutDate": "2025-06-11T00:00:00.000Z",
"createdByUserId": 2,
"videos": [
{ "slot": 1, "video": { "id": 5, "description": "Barbell curl", "streamUrl": "..." }, "reps": 10 },
{ "slot": 2, "video": null, "reps": null }
]
}
],
"meta": { ... }
}
```
`video: null` when the referenced video has been deleted.
---
### POST /api/v1/workouts
`[T]` Coach+.
Request:
```json
{
"name": "Tuesday WOD",
"workoutDate": "2025-06-11T00:00:00.000Z",
"video1": 5, "number1": 10,
"video2": 8, "number2": 12,
"video3": null, "number3": null,
"video4": null, "number4": null
}
```
Response 201: `{ "data": { ...workout with videos } }`
Errors: `VALIDATION_FAILED` (400, video IDs not in org).
---
### GET /api/v1/workouts/today
`[T]` Coach+.
No query params. Uses org timezone for "today" calculation.
Response 200 (collection — same shape as GET /workouts).
---
### GET /api/v1/workouts/:id
`[T]` Coach+.
Response 200: `{ "data": { ...workout with videos } }`
---
### DELETE /api/v1/workouts/:id
`[T]` Coach (own only) or Owner (any).
Response 204.
Errors: `AUTH_FORBIDDEN` (403 if Coach tries to delete another's workout), `NOT_FOUND` (404).
---
## Timers — /api/v1/timers
### GET /api/v1/timers
`[T]` Coach+.
Response 200 (collection):
```json
{
"data": [
{ "id": 3, "name": "HIIT 30/10", "totalTime": 1800, "setTime": 30, "restTime": 10,
"moveTime": 15, "setCount": 3, "exerciseCount": 5, "lapCount": 2 }
],
"meta": { ... }
}
```
---
### POST /api/v1/timers
`[T]` Coach+.
Request:
```json
{
"name": "HIIT 30/10",
"totalTime": 1800, "setTime": 30, "restTime": 10, "moveTime": 15,
"setCount": 3, "exerciseCount": 5, "lapCount": 2
}
```
Response 201: `{ "data": { ...timer } }`
---
### GET /api/v1/timers/:id
`[T]` Coach+.
Response 200: `{ "data": { ...timer } }`
---
### DELETE /api/v1/timers/:id
`[T]` Coach (own) or Owner.
Response 204.
---
### POST /api/v1/timers/:id/launch
`[T]` Coach+.
No request body.
Response 200:
```json
{ "data": { "sessionId": "timer_3_1718273400000" } }
```
Client uses `sessionId` to join the Socket.io room.
---
### DELETE /api/v1/timers/session
`[T]` Coach+.
Request: `{ "sessionId": "timer_3_1718273400000" }`
Stops the active timer session.
Response 204.
---
## CrossFit Workouts — /api/v1/crossfit-workouts
### GET /api/v1/crossfit-workouts
`[T]` Coach+.
Query: `?page=1&limit=20`
Response 200 (collection):
```json
{
"data": [
{ "id": 7, "name": "Hero WOD Murph", "workoutDate": "2025-06-11T00:00:00.000Z",
"workoutItems": ["1 mile run", "100 pull-ups", "200 push-ups", "300 squats", "1 mile run"],
"createdByUserId": 2 }
],
"meta": { ... }
}
```
---
### POST /api/v1/crossfit-workouts
`[T]` Coach+.
Request:
```json
{
"name": "Hero WOD Murph",
"workoutDate": "2025-06-11T00:00:00.000Z",
"workoutItems": ["1 mile run", "100 pull-ups", "200 push-ups"]
}
```
Response 201: `{ "data": { ...crossfitWorkout } }`
---
### GET /api/v1/crossfit-workouts/:id
`[T]` Coach+.
Response 200: `{ "data": { ...crossfitWorkout } }`
---
### DELETE /api/v1/crossfit-workouts/:id
`[T]` `[O]`
Response 204.
---
## Clients — /api/v1/clients
`[F:client-management]` All client endpoints require this feature flag.
### GET /api/v1/clients
`[T]` Coach (own clients) or Owner (all).
Response 200 (collection):
```json
{
"data": [
{ "id": 9, "username": "athlete1", "firstName": "Sara", "lastName": "Kim",
"email": "sara@email.com", "isActive": true,
"coach": { "id": 2, "firstName": "John", "lastName": "Smith" } }
],
"meta": { ... }
}
```
---
### POST /api/v1/clients
`[T]` `[O]` or Coach if org allows self-assign.
Creates a new Client user and optionally assigns a coach.
Request:
```json
{
"username": "athlete2",
"firstName": "Tom",
"lastName": "Brady",
"email": "tom@email.com",
"password": "initialPass",
"coachId": 2
}
```
`coachId` optional.
Response 201: `{ "data": { ...user, coachLink? } }`
---
### GET /api/v1/clients/:id
`[T]` Coach (own clients only) or Owner.
Response 200:
```json
{
"data": {
"id": 9, "username": "athlete1", "firstName": "Sara", "lastName": "Kim",
"coach": { "id": 2, "firstName": "John" },
"upcomingSessionsCount": 3,
"pendingWorkoutsCount": 2
}
}
```
---
### POST /api/v1/clients/:id/assign
`[T]` `[O]`
Request: `{ "coachId": 3 }`
Response 200: `{ "data": { "linkId": 14, "coachId": 3, "clientId": 9, "assignedAt": "..." } }`
---
### DELETE /api/v1/clients/:id/assign
`[T]` `[O]`
Request: `{ "linkId": 14 }`
Response 204.
---
### GET /api/v1/clients/:id/workouts
`[T]` Coach (own clients) or Client (own) or Owner.
Query: `?page=1&limit=20&includeCompleted=false`
Response 200 (collection):
```json
{
"data": [
{ "id": 22, "name": "Monday Strength", "scheduledDate": "2025-06-12T00:00:00.000Z",
"completedAt": null, "coachId": 2,
"items": [
{ "type": "video", "videoId": 5, "reps": 10, "sets": 3, "notes": "Full ROM",
"streamUrl": "/api/v1/videos/stream/..." },
{ "type": "text", "text": "Rest 2 min between sets" }
]
}
],
"meta": { ... }
}
```
---
### POST /api/v1/clients/:id/workouts
`[T]` Coach (own clients only).
Request:
```json
{
"name": "Monday Strength",
"scheduledDate": "2025-06-12T00:00:00.000Z",
"notes": "Focus on form today.",
"items": [
{ "type": "video", "videoId": 5, "reps": 10, "sets": 3, "notes": "Full ROM" },
{ "type": "text", "text": "Rest 2 min" }
]
}
```
Response 201: `{ "data": { ...clientWorkout } }`
---
### GET /api/v1/clients/:id/workouts/:workoutId
`[T]` Coach (own clients) or Client (own) or Owner.
Response 200: `{ "data": { ...clientWorkout with items } }`
---
### PATCH /api/v1/clients/:id/workouts/:workoutId
`[T]` Coach (own clients only).
Request: any subset of `{ name, scheduledDate, notes, items }`.
Response 200: `{ "data": { ...updated } }`
---
### DELETE /api/v1/clients/:id/workouts/:workoutId
`[T]` Coach (own clients only).
Soft delete. Response 204.
---
### POST /api/v1/clients/:id/workouts/:workoutId/complete
`[T]` Coach (own clients) or Client (own).
No request body.
Response 200: `{ "data": { "completedAt": "2025-06-12T09:30:00.000Z" } }`
---
### GET /api/v1/clients/:id/sessions
`[T]` Coach (own clients) or Client (own) or Owner.
Query: `?startAfter=2025-06-01&endBefore=2025-06-30&status=Scheduled&page=1&limit=20`
Response 200 (collection):
```json
{
"data": [
{ "id": 31, "title": "Weekly Check-in", "sessionType": "Personal",
"startAt": "2025-06-12T09:00:00.000Z", "endAt": "2025-06-12T10:00:00.000Z",
"status": "Scheduled", "locationNotes": "Gym Floor B",
"sharedNotes": "Bring your training log",
"linkedWorkoutId": 22 }
],
"meta": { ... }
}
```
`coachNotes` is stripped when requester is the Client.
---
### POST /api/v1/clients/:id/sessions
`[T]` Coach (own clients).
Request:
```json
{
"title": "Weekly Check-in",
"sessionType": "personal",
"startAt": "2025-06-12T09:00:00.000Z",
"endAt": "2025-06-12T10:00:00.000Z",
"locationNotes": "Gym Floor B",
"coachNotes": "Client struggling with squat depth",
"sharedNotes": "Bring your training log",
"linkedWorkoutId": 22
}
```
Response 201: `{ "data": { ...session } }`
---
### PATCH /api/v1/clients/:id/sessions/:sessionId
`[T]` Coach (own) or Client (limited fields only).
Response 200: `{ "data": { ...updated } }`
---
### POST /api/v1/clients/:id/sessions/:sessionId/cancel
`[T]` Coach or Client.
Response 200: `{ "data": { "status": "Cancelled" } }`
Errors: `CANCELLATION_TOO_LATE` (400) — Client attempting to cancel a session that starts in
less than 24 hours. Coaches and Owners are not subject to this restriction.
---
## My (Client Self-Service) — /api/v1/my
### GET /api/v1/my/workouts
`[T]` Client role only.
Alias for `GET /api/v1/clients/:ownId/workouts` scoped to the requesting client.
Response: same collection shape as client workouts.
---
### GET /api/v1/my/sessions
`[T]` Client role only.
Alias for `GET /api/v1/clients/:ownId/sessions`.
---
### GET /api/v1/my/profile
`[T]` Any role.
Returns own user record. Alias for `GET /api/v1/users/:ownId`.
---
### PUT /api/v1/my/password
`[T]` Any role.
Allows any authenticated user to change their own password after verifying the current one.
Owner-managed `PUT /api/v1/users/:id/password` does not require the current password;
this endpoint does.
Request:
```json
{ "currentPassword": "oldPass123", "newPassword": "newPass456" }
```
Response 204.
Errors: `AUTH_FORBIDDEN` (401 if `currentPassword` does not match stored hash), `VALIDATION_FAILED` (400).
---
## Calendar (Coach View) — /api/v1/calendar
### GET /api/v1/calendar
`[T]` Coach+. `[F:calendar]`
Query: `?startAfter=2025-06-01&endBefore=2025-06-30`
Returns all sessions for the coach across all their clients, aggregated.
Response 200 (collection of CalendarSession).
**Phase 2 deferrals:** Conflict detection (overlapping sessions for same coach) and recurring
sessions (RRULE / weekly repeat) are not implemented in V2 MVP. Every session is a standalone
record. The API accepts overlapping bookings without error.
---
## Admin — /api/v1/admin
### GET /api/v1/admin/storage
`[T]` `[O]`
Response 200:
```json
{
"data": {
"disk": { "total": 53687091200, "used": 21474836480, "free": 32212254720, "usedPercent": 40 },
"uploads": { "size": 4831838208, "fileCount": 47 },
"warning": false,
"warnThresholdBytes": 5368709120
}
}
```
---
## Audit Logs — /api/v1/audit-logs
### GET /api/v1/audit-logs
`[T]` `[O]`
Query: `?action=video.upload&userId=2&entityType=video&from=2025-06-01&to=2025-06-30&page=1&limit=50`
Response 200 (collection):
```json
{
"data": [
{ "id": 204, "userId": 2, "userRole": "Coach", "action": "video.upload",
"entityType": "video", "entityId": 15,
"details": { "filename": "1718...", "category": "Arm Exercises", "fileSizeBytes": 45020000 },
"ipAddress": "192.168.1.5", "createdAt": "2025-06-11T14:23:00.000Z" }
],
"meta": { ... }
}
```
---
### GET /api/v1/audit-logs/export
`[T]` `[O]`
Same query params as GET. Returns CSV stream.
Response headers:
```
Content-Type: text/csv
Content-Disposition: attachment; filename="audit-log-2025-06-11.csv"
```
---
## System Admin — /api/v1/sysadmin
### GET /api/v1/sysadmin/orgs
`[T]` `[SA]`
Response 200: All organizations with user count summary.
---
### GET /api/v1/sysadmin/orgs/:id
`[T]` `[SA]`
Response 200: Full org detail, branding, user list.
---
### PATCH /api/v1/sysadmin/orgs/:id
`[T]` `[SA]`
Request: any subset of `{ name, timezone, features, isActive, licenseOwner, licenseEmail }`.
Response 200: `{ "data": { ...org } }`
---
### GET /api/v1/sysadmin/health
`[T]` `[SA]`
Response 200:
```json
{
"data": {
"status": "ok",
"version": "1.0.0",
"nodeVersion": "v20.11.0",
"uptime": 86423,
"db": { "status": "ok", "lastMigration": "005-add-video-mime-type" },
"disk": { "free": 32212254720, "usedPercent": 40 },
"activeTimerSessions": 0,
"orgCount": 1
}
}
```
---
## Health (No Auth)
### GET /health
Response 200:
```json
{
"status": "ok",
"version": "1.0.0",
"uptime": 86423,
"db": "ok",
"diskAvailableGB": 30.0,
"diskWarnActive": false
}
```
Returns `"status": "degraded"` (still HTTP 200) if DB unreachable or disk in warning state.
---
## OpenAPI Spec
### GET /api/v1/openapi.yaml
No auth required.
Returns the OpenAPI 3.0 spec for this API as a YAML file.
Generated from code comments or a hand-maintained `openapi.yaml` in the project root.
Response headers:
```
Content-Type: application/yaml
```
This endpoint is mentioned in `API_STANDARDS.md` as the authoritative spec location.