888 lines
27 KiB
Markdown
888 lines
27 KiB
Markdown
# VitFit V2 — Backend Method Maps
|
|
|
|
TypeScript-style signatures are used for clarity. The implementation is JavaScript (CommonJS).
|
|
`Promise<T>` return types indicate async functions. All service functions throw `AppError` on failure.
|
|
|
|
---
|
|
|
|
## core/db.js
|
|
|
|
```js
|
|
initDb(): Promise<Sequelize>
|
|
```
|
|
Creates Sequelize instance. Runs PRAGMAs. Returns sequelize.
|
|
```
|
|
PRAGMA journal_mode = WAL
|
|
PRAGMA busy_timeout = 5000
|
|
PRAGMA foreign_keys = ON
|
|
```
|
|
|
|
```js
|
|
runMigrations(): Promise<void>
|
|
```
|
|
Programmatically runs all pending sequelize-cli migrations in `modules/*/migrations/`.
|
|
|
|
```js
|
|
models: {
|
|
Organization, Branding,
|
|
User, DeviceToken,
|
|
Video, Category,
|
|
Workout,
|
|
Timer,
|
|
CrossfitWorkout,
|
|
CoachClientLink, ClientWorkout, CalendarSession,
|
|
AuditLog
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## core/auth.js
|
|
|
|
```js
|
|
authenticateToken(req, res, next): void
|
|
```
|
|
Reads `Authorization: Bearer <token>`. Verifies JWT against `JWT_SECRET` with algorithm
|
|
pinned to `HS256`:
|
|
```js
|
|
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, (err, decoded) => { ... });
|
|
```
|
|
Algorithm pinning prevents RS256/none algorithm confusion attacks.
|
|
|
|
After signature verification, fetches the user row to check `passwordChangedAt`:
|
|
```js
|
|
if (user.passwordChangedAt && decoded.iat * 1000 < user.passwordChangedAt.getTime()) {
|
|
return next(new AppError('AUTH_INVALID', 'Token issued before last password change.', 401));
|
|
}
|
|
```
|
|
This ensures that tokens issued before a password change are rejected, even within their 7-day TTL.
|
|
|
|
Sets `req.user = { id, username, role, organizationId }` on success.
|
|
Calls `next()` on success. Returns `AppError('AUTH_REQUIRED', ..., 401)` if no token,
|
|
`AppError('AUTH_INVALID', ..., 401)` on invalid or pre-password-change token.
|
|
|
|
```js
|
|
authenticateRole(roles: string[]): Middleware
|
|
```
|
|
Returns middleware. Checks `req.user.role` is in `roles`.
|
|
Returns `AppError('AUTH_FORBIDDEN', ..., 403)` if not.
|
|
Usage: `router.delete('/:id', authenticateToken, authenticateRole(['Owner', 'SystemAdmin']), handler)`
|
|
|
|
```js
|
|
requireFeature(feature: string): Middleware
|
|
```
|
|
Returns middleware. Fetches org features from DB (cached 5 min per orgId).
|
|
Returns `AppError('FEATURE_DISABLED', ..., 403)` if feature not in org's features array.
|
|
Usage: `router.post('/', authenticateToken, requireFeature('client-management'), handler)`
|
|
|
|
---
|
|
|
|
## core/audit.js
|
|
|
|
```js
|
|
log(
|
|
req: Request,
|
|
action: string,
|
|
entityType: string | null,
|
|
entityId: number | null,
|
|
details: object
|
|
): Promise<void>
|
|
```
|
|
Creates one AuditLog row. `req.user` provides userId, userRole, organizationId.
|
|
`req.ip` and `req.get('User-Agent')` provide client info.
|
|
On DB error: logs via pino at `warn` level and swallows — audit failure must never break the request.
|
|
|
|
---
|
|
|
|
## core/storage.js
|
|
|
|
```js
|
|
getStorageInfo(): Promise<StorageInfo>
|
|
```
|
|
Returns:
|
|
```js
|
|
{
|
|
disk: { total: number, used: number, free: number, usedPercent: number },
|
|
uploads: { size: number, fileCount: number },
|
|
warning: boolean // true when free < STORAGE_WARN_BYTES
|
|
}
|
|
```
|
|
Result is cached for 60 seconds. Thread-safe: subsequent calls while in-flight share the same Promise.
|
|
|
|
```js
|
|
checkUploadAllowed(req, res, next): Promise<void>
|
|
```
|
|
Middleware. Calls `getStorageInfo()`. Throws `AppError('STORAGE_INSUFFICIENT', ..., 507)` if `warning`.
|
|
Applied to all upload routes before multer.
|
|
|
|
```js
|
|
getUploadsSize(): Promise<{ size: number, fileCount: number }>
|
|
```
|
|
Internal. Reads `UPLOADS_DIR` synchronously (blocking but fast for < 1000 files),
|
|
sums `stat.size` of each file. Returns totals.
|
|
|
|
---
|
|
|
|
## core/socket.js
|
|
|
|
```js
|
|
init(httpServer: HttpServer): SocketIoServer
|
|
```
|
|
Attaches Socket.io to the HTTP server. Configures CORS. Registers `connection` handler.
|
|
On `connection`: authenticates socket via JWT passed in `auth.token` handshake data.
|
|
If auth fails, disconnects with error. Sets `socket.data.user` on success.
|
|
Returns the `io` instance.
|
|
|
|
```js
|
|
getIo(): SocketIoServer
|
|
```
|
|
Returns the singleton `io`. Throws if `init()` has not been called.
|
|
|
|
---
|
|
|
|
## core/errors.js
|
|
|
|
```js
|
|
class AppError extends Error {
|
|
constructor(code: string, message: string, status: number, field?: string)
|
|
code: string
|
|
status: number
|
|
field: string | null
|
|
}
|
|
```
|
|
|
|
```js
|
|
errorHandler(err, req, res, next): void
|
|
```
|
|
Express `(err, req, res, next)` middleware. Last middleware in `app.js`.
|
|
If `err instanceof AppError`: responds with standard error envelope at `err.status`.
|
|
Otherwise: logs at `error` level, responds 500 with generic message (hides internals in production).
|
|
|
|
---
|
|
|
|
## core/respond.js
|
|
|
|
```js
|
|
ok(res: Response, data: object): void
|
|
```
|
|
Sends `200 { "data": data }`.
|
|
|
|
```js
|
|
created(res: Response, data: object): void
|
|
```
|
|
Sends `201 { "data": data }`.
|
|
|
|
```js
|
|
collection(res: Response, data: any[], total: number, page: number, limit: number): void
|
|
```
|
|
Sends `200 { "data": [...], "meta": { total, page, limit, totalPages } }`.
|
|
|
|
```js
|
|
noContent(res: Response): void
|
|
```
|
|
Sends `204` with no body.
|
|
|
|
```js
|
|
err(res: Response, code: string, message: string, status: number, field?: string): void
|
|
```
|
|
Sends `status { "error": { code, message, field } }`.
|
|
|
|
---
|
|
|
|
## modules/auth/service.js
|
|
|
|
```js
|
|
login(
|
|
username: string,
|
|
password: string,
|
|
rememberDevice: boolean,
|
|
deviceName: string,
|
|
deviceType: 'kiosk' | 'personal'
|
|
): Promise<{ jwt: string, deviceToken?: string, user: UserPublic }>
|
|
```
|
|
**Per-username lockout (in addition to per-IP rate limit on the route):**
|
|
Maintains a `Map<username, { count, resetAt }>` in process memory. On each failed attempt,
|
|
increments the counter for that username. If `count >= 10` and `resetAt > Date.now()`, throws
|
|
`AppError('LOGIN_FAILED', ..., 401)` immediately without hitting the DB. Resets automatically
|
|
after 15 minutes. This prevents targeted account brute-force from IPs that rotate.
|
|
|
|
Finds User by username. Checks `isActive`. Compares password with bcrypt.
|
|
On any failure: throws `AppError('LOGIN_FAILED', ..., 401)` — same error for unknown username,
|
|
wrong password, and inactive account (no enumeration).
|
|
On success: clears per-username failure counter. Signs JWT (7-day), creates DeviceToken if
|
|
`rememberDevice`. Updates `lastLoginAt`. Logs `auth.login.success` audit event.
|
|
|
|
```js
|
|
deviceLogin(
|
|
rawToken: string,
|
|
ipAddress: string,
|
|
userAgent: string
|
|
): Promise<{ jwt: string, newDeviceToken: string }>
|
|
```
|
|
Route-level rate limiter applied to `POST /auth/device-login` — same 10 req/15 min per-IP
|
|
limiter as `/auth/login`. The token search space (32-byte random hex = 2²⁵⁶) makes brute force
|
|
computationally infeasible, but rate limiting prevents this endpoint from being used as an
|
|
amplification vector or server load probe.
|
|
|
|
Hashes `rawToken`. Finds DeviceToken by hash. Validates not revoked, not expired.
|
|
Issues new JWT. Rotates device token (old revoked, new created with same TTL).
|
|
Logs `auth.token.refreshed`. Returns new JWT + new raw device token.
|
|
|
|
```js
|
|
refreshToken(userId: number): Promise<{ jwt: string }>
|
|
```
|
|
Signs a fresh JWT for the given userId. Called automatically when token < 1 hour from expiry.
|
|
|
|
```js
|
|
createDeviceToken(
|
|
userId: number,
|
|
orgId: number,
|
|
deviceName: string,
|
|
deviceType: 'kiosk' | 'personal'
|
|
): Promise<{ rawToken: string, record: DeviceToken }>
|
|
```
|
|
Generates `crypto.randomBytes(32).toString('hex')` as raw token.
|
|
Stores bcrypt hash in DB. TTL: 90 days for kiosk, 30 days for personal.
|
|
Returns raw token (only time it's in plaintext — not stored anywhere else).
|
|
|
|
```js
|
|
hashToken(rawToken: string): string
|
|
```
|
|
Returns `crypto.createHash('sha256').update(rawToken).digest('hex')`.
|
|
SHA-256 (not bcrypt) for token lookup — device tokens are long random strings, no need for bcrypt cost.
|
|
|
|
---
|
|
|
|
## modules/users/service.js
|
|
|
|
```js
|
|
getUsers(
|
|
orgId: number,
|
|
filters: { role?: string, isActive?: boolean, page?: number, limit?: number }
|
|
): Promise<{ rows: User[], count: number }>
|
|
```
|
|
Returns paginated users for the org. SystemAdmin can pass `orgId = null` to query across orgs.
|
|
|
|
```js
|
|
getUserById(id: number, orgId: number): Promise<User>
|
|
```
|
|
Finds user by id within orgId. Throws `AppError('NOT_FOUND', ..., 404)` if not found.
|
|
|
|
```js
|
|
createUser(
|
|
orgId: number,
|
|
data: { username, email?, firstName?, lastName?, password, role },
|
|
actorId: number
|
|
): Promise<User>
|
|
```
|
|
Validates role is not `SystemAdmin` (only setup script can create SystemAdmin).
|
|
Password validated by Zod schema before reaching this method: minimum 8 characters,
|
|
at most 128 characters. Bcrypt work factor: 12 rounds.
|
|
Hashes password. Creates user. Logs `user.create` audit.
|
|
Throws `AppError('CONFLICT', ..., 409)` on duplicate username.
|
|
|
|
```js
|
|
deactivateUser(targetId: number, orgId: number, actorId: number): Promise<void>
|
|
```
|
|
Last Owner check: counts active Owners in org. If target is last Owner, throws `AppError('LAST_OWNER_PROTECTED', ..., 400)`.
|
|
Sets `isActive = false`. Deactivates all DeviceTokens for the user. Logs `user.deactivate` audit.
|
|
|
|
```js
|
|
changeRole(
|
|
targetId: number,
|
|
newRole: string,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<void>
|
|
```
|
|
Last Owner check if current role is `Owner` and new role is not `Owner`.
|
|
Self-role-change check: actorId === targetId throws if actor is Owner.
|
|
Updates role. Logs `user.role.change` audit.
|
|
|
|
```js
|
|
resetPassword(
|
|
targetId: number,
|
|
newPassword: string,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<void>
|
|
```
|
|
Password validated by Zod schema: minimum 8, maximum 128 characters.
|
|
Hashes new password (12 bcrypt rounds). Sets `passwordChangedAt = now()` alongside the hash
|
|
update — this invalidates all JWTs issued before this moment (enforced by `authenticateToken`).
|
|
Revokes all DeviceTokens for target user.
|
|
Logs `user.password.reset` audit (no password in log).
|
|
|
|
```js
|
|
changeOwnPassword(
|
|
userId: number,
|
|
currentPassword: string,
|
|
newPassword: string
|
|
): Promise<void>
|
|
```
|
|
`newPassword` validated by Zod schema: minimum 8, maximum 128 characters.
|
|
Fetches user with password included (bypasses defaultScope). Verifies `currentPassword` against
|
|
stored bcrypt hash — throws `AppError('AUTH_FORBIDDEN', 'Current password is incorrect.', 401)`
|
|
on mismatch. Hashes new password (12 bcrypt rounds). Sets `passwordChangedAt = now()` — this
|
|
invalidates all JWTs and device tokens issued before this moment. Revokes all DeviceTokens for
|
|
the user (the calling session's JWT is still valid until it next hits `authenticateToken`, at
|
|
which point it is rejected and the user re-authenticates). Logs `user.password.change` audit
|
|
(no passwords in log).
|
|
|
|
```js
|
|
updateProfile(
|
|
userId: number,
|
|
data: { firstName?, lastName?, email? }
|
|
): Promise<User>
|
|
```
|
|
Updates own profile fields. Logs `user.profile.update` audit with before/after.
|
|
|
|
```js
|
|
getDeviceTokens(userId: number, orgId: number): Promise<DeviceToken[]>
|
|
```
|
|
Returns non-revoked device tokens for a user. Returns metadata only — token hash never returned.
|
|
|
|
```js
|
|
revokeDeviceToken(tokenId: number, userId: number, orgId: number): Promise<void>
|
|
```
|
|
Sets `isRevoked = true`. Validates token belongs to userId + orgId before revoking.
|
|
Logs `auth.device.revoked` audit.
|
|
|
|
---
|
|
|
|
## modules/org/service.js
|
|
|
|
```js
|
|
getOrg(orgId: number): Promise<Organization>
|
|
```
|
|
Returns org record. Includes Branding via eager load.
|
|
|
|
```js
|
|
updateOrg(
|
|
orgId: number,
|
|
data: { name?, timezone?, licenseOwner?, licenseEmail? },
|
|
actorId: number
|
|
): Promise<Organization>
|
|
```
|
|
Validates timezone is a valid IANA string (check against `Intl.supportedValuesOf('timeZone')`).
|
|
Logs `org.update` audit.
|
|
|
|
```js
|
|
getBranding(orgId: number): Promise<Branding>
|
|
```
|
|
Returns branding for org. Creates default branding if not exists.
|
|
|
|
```js
|
|
updateBranding(
|
|
orgId: number,
|
|
data: { appName?, primaryColor?, secondaryColor?, workColor?, restColor?, moveColor? },
|
|
actorId: number
|
|
): Promise<Branding>
|
|
```
|
|
Validates each color is a valid CSS hex (`/^#[0-9A-Fa-f]{6}$/`).
|
|
Validates contrast ratio of each color against `#1a1a1a` (display background) is >= 4.5:1.
|
|
Throws `AppError('VALIDATION_FAILED', ..., 400)` listing each failing color.
|
|
Logs `branding.update` audit.
|
|
|
|
```js
|
|
validateContrastRatio(hex: string, background: string): number
|
|
```
|
|
Internal. Converts hex to relative luminance, calculates WCAG contrast ratio.
|
|
Returns ratio (e.g., `7.2`).
|
|
|
|
```js
|
|
uploadLogo(orgId: number, file: MulterFile, actorId: number): Promise<Branding>
|
|
```
|
|
Validates MIME type via magic bytes (reads first 12 bytes from `file.path`).
|
|
Allowed types: `image/png`, `image/jpeg`, `image/gif`, `image/webp`.
|
|
Wraps in `try/finally` to clean up the multer temp file regardless of outcome:
|
|
```js
|
|
try {
|
|
// validate, derive ext from detected MIME, save to UPLOADS_DIR
|
|
} finally {
|
|
await fs.promises.unlink(file.path).catch(() => {});
|
|
}
|
|
```
|
|
Deletes old logo file if one existed. Updates `Branding.logoPath`.
|
|
Logs `logo.upload` audit.
|
|
|
|
---
|
|
|
|
## modules/videos/service.js
|
|
|
|
```js
|
|
getVideos(
|
|
orgId: number,
|
|
filters: { category?: string, page?: number, limit?: number }
|
|
): Promise<{ rows: Video[], count: number }>
|
|
```
|
|
Paginated. Filters by category if provided. Orders by `createdAt DESC`.
|
|
|
|
```js
|
|
uploadVideo(
|
|
orgId: number,
|
|
file: MulterFile,
|
|
data: { description: string, category: string },
|
|
actorId: number
|
|
): Promise<Video>
|
|
```
|
|
Wraps upload logic in `try/finally` to guarantee temp file cleanup:
|
|
```js
|
|
try {
|
|
const detectedMime = await validateMimeType(file.path);
|
|
const ext = { 'video/mp4': '.mp4', 'video/quicktime': '.mov', 'video/x-m4v': '.m4v' }[detectedMime];
|
|
// ext is derived from detected MIME — original filename extension is ignored
|
|
const safeName = `${Date.now()}_${crypto.randomBytes(8).toString('hex')}${ext}`;
|
|
await fs.promises.rename(file.path, path.join(UPLOADS_DIR, safeName));
|
|
// create DB record ...
|
|
} finally {
|
|
await fs.promises.unlink(file.path).catch(() => {}); // clean up temp if rename failed
|
|
}
|
|
```
|
|
`validateMimeType(file.path)` — opens the temp file with `fs.openSync`, reads exactly the
|
|
first 12 bytes via `fs.readSync`, closes the file handle, then runs `fileTypeFromBuffer` on
|
|
those 12 bytes. Throws `UPLOAD_TYPE_INVALID` if result is not `video/mp4`, `video/quicktime`,
|
|
or `video/x-m4v`. Never loads the full file into memory. Multer must use disk storage
|
|
(`multer({ dest: process.env.UPLOAD_TEMP_DIR })`) — NOT `memoryStorage()`.
|
|
File extension is derived from the detected MIME type — the original uploaded filename
|
|
extension is discarded to prevent serving a valid video file with a `.php` or `.html` extension.
|
|
Creates Video record with `fileSizeBytes = file.size`.
|
|
Logs `video.upload` audit.
|
|
|
|
```js
|
|
deleteVideo(videoId: number, orgId: number, actorId: number): Promise<void>
|
|
```
|
|
Finds video (throws 404 if not found or wrong org).
|
|
Deletes file from `UPLOADS_DIR` (ignores ENOENT — file already gone is fine).
|
|
Deletes DB record.
|
|
Logs `video.delete` audit with before snapshot.
|
|
|
|
```js
|
|
getCategories(orgId: number): Promise<Category[]>
|
|
```
|
|
Returns all categories for org, ordered by name.
|
|
|
|
```js
|
|
createCategory(
|
|
orgId: number,
|
|
name: string,
|
|
actorId: number
|
|
): Promise<Category>
|
|
```
|
|
Throws `CONFLICT` on duplicate. Logs `category.create` audit.
|
|
|
|
```js
|
|
deleteCategory(
|
|
categoryId: number,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<void>
|
|
```
|
|
Throws `CONFLICT` if any Video in this org has `category = category.name`.
|
|
Deletes. Logs `category.delete` audit.
|
|
|
|
```js
|
|
validateMimeType(filePath: string, allowedMimes: string[]): Promise<string>
|
|
```
|
|
Opens `filePath` with `fs.openSync`, reads exactly 12 bytes via `fs.readSync`, closes the
|
|
file descriptor, then passes the 12-byte Buffer to `fileTypeFromBuffer` from the `file-type`
|
|
package. Never loads the whole file into memory.
|
|
`allowedMimes` is passed by the caller — video uploads use `['video/mp4', 'video/quicktime',
|
|
'video/x-m4v']`; logo uploads use `['image/png', 'image/jpeg', 'image/gif', 'image/webp']`.
|
|
Throws `AppError('UPLOAD_TYPE_INVALID', ..., 400)` if detected type is not in `allowedMimes`
|
|
or is undetectable. Returns the detected MIME type string.
|
|
|
|
```js
|
|
streamVideo(
|
|
filename: string,
|
|
orgId: number,
|
|
rangeHeader: string | undefined,
|
|
res: Response
|
|
): Promise<void>
|
|
```
|
|
Validates `path.basename(filename) === filename` (path traversal guard).
|
|
Verifies a Video record with this filename exists in orgId (throws 404 if not).
|
|
Resolves full path, checks it starts with `path.resolve(UPLOADS_DIR)` (double-check).
|
|
If `rangeHeader`: parses range, opens `fs.createReadStream(start, end)`, sends 206.
|
|
Otherwise: sends 200 with full file stream.
|
|
Sets `Content-Type` from `video.mimeType` stored in DB.
|
|
|
|
---
|
|
|
|
## modules/workouts/service.js
|
|
|
|
```js
|
|
getWorkouts(
|
|
orgId: number,
|
|
filters: { page?: number, limit?: number }
|
|
): Promise<{ rows: Workout[], count: number }>
|
|
```
|
|
Uses LEFT JOIN on all four video slots. Each slot may return null if video was deleted.
|
|
Returns `[Video removed]` sentinel values handled by the model association.
|
|
|
|
```js
|
|
getWorkoutById(id: number, orgId: number): Promise<Workout>
|
|
```
|
|
LEFT JOINs all four video associations. Throws 404 if not found in org.
|
|
|
|
```js
|
|
getTodayWorkouts(orgId: number): Promise<Workout[]>
|
|
```
|
|
Fetches org timezone. Uses luxon to compute UTC start/end for today in org's local time.
|
|
Queries `workoutDate BETWEEN todayStart AND todayEnd`.
|
|
|
|
```js
|
|
createWorkout(
|
|
orgId: number,
|
|
data: { name, workoutDate, video1?, video2?, video3?, video4?, number1?, number2?, number3?, number4? },
|
|
actorId: number
|
|
): Promise<Workout>
|
|
```
|
|
Validates each non-null videoN ID belongs to orgId.
|
|
Creates Workout. Logs `workout.create` audit.
|
|
|
|
```js
|
|
deleteWorkout(id: number, orgId: number, actorId: number): Promise<void>
|
|
```
|
|
Ownership check: if `req.user.role === 'Coach'`, verifies `createdByUserId === actorId`.
|
|
Owners can delete any workout. Deletes. Logs `workout.delete` audit.
|
|
|
|
---
|
|
|
|
## modules/timers/service.js
|
|
|
|
```js
|
|
getTimers(orgId: number): Promise<Timer[]>
|
|
```
|
|
Returns all timers for org, ordered by `createdAt DESC`.
|
|
|
|
```js
|
|
getTimerById(id: number, orgId: number): Promise<Timer>
|
|
```
|
|
Throws 404 if not found in org.
|
|
|
|
```js
|
|
createTimer(
|
|
orgId: number,
|
|
data: { name, totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount },
|
|
actorId: number
|
|
): Promise<Timer>
|
|
```
|
|
Validates all time values are positive integers.
|
|
Validates `totalTime >= setTime * setCount * exerciseCount * lapCount` (rough sanity check).
|
|
Creates. Logs `timer.create` audit.
|
|
|
|
```js
|
|
deleteTimer(id: number, orgId: number, actorId: number): Promise<void>
|
|
```
|
|
Ownership check (same as workouts). Stops active session if one exists for this timer.
|
|
Deletes. Logs `timer.delete` audit.
|
|
|
|
```js
|
|
launchTimer(timerId: number, orgId: number, actorId: number): Promise<{ sessionId: string }>
|
|
```
|
|
Fetches timer config. Generates `sessionId = 'timer_' + timerId + '_' + Date.now()`.
|
|
Creates `TimerEngine` instance. Stores in active sessions Map under `sessionId`.
|
|
Calls `engine.start()`. Logs `timer.launch` audit.
|
|
Returns `{ sessionId }` — clients join this Socket.io room.
|
|
|
|
```js
|
|
stopTimer(sessionId: string, orgId: number, actorId: number): Promise<void>
|
|
```
|
|
Finds engine by sessionId. Calls `engine.stop()`. Removes from Map. Logs `timer.stop` audit.
|
|
|
|
```js
|
|
getActiveSession(orgId: number): Promise<{ sessionId, state } | null>
|
|
```
|
|
Returns the currently running timer session for the org, or null. One active session per org.
|
|
|
|
---
|
|
|
|
## modules/timers/timer-engine.js
|
|
|
|
```js
|
|
class TimerEngine {
|
|
constructor(config: TimerConfig, io: SocketIoServer, roomId: string)
|
|
}
|
|
```
|
|
|
|
**State:**
|
|
```js
|
|
{
|
|
status: 'idle' | 'running' | 'paused' | 'complete',
|
|
phase: 'set' | 'rest' | 'move',
|
|
currentLap: number, // 1-indexed
|
|
currentExercise: number, // 1-indexed
|
|
currentSet: number, // 1-indexed
|
|
phaseEndTime: bigint, // process.hrtime.bigint() target for phase end
|
|
sessionEndTime: bigint, // process.hrtime.bigint() target for session end
|
|
elapsedSeconds: number
|
|
}
|
|
```
|
|
|
|
**Methods:**
|
|
|
|
```js
|
|
start(): void
|
|
```
|
|
Sets initial state. Records `sessionStartHrTime`. Begins `_tick()` interval (every 100ms for responsiveness).
|
|
Emits `timer:state` to room with full state snapshot.
|
|
|
|
```js
|
|
stop(): void
|
|
```
|
|
Clears interval. Sets `status = 'complete'`. Emits `timer:stopped` to room. Cleans up.
|
|
|
|
```js
|
|
getState(): TimerState
|
|
```
|
|
Returns current state snapshot. Called when a client reconnects to re-sync.
|
|
|
|
```js
|
|
_tick(): void [private]
|
|
```
|
|
Called every 100ms. Computes `remaining = phaseEndTime - process.hrtime.bigint()` in nanoseconds.
|
|
Emits `timer:tick` with `{ phaseRemainingMs, totalRemainingMs, ...state }` at most once per second
|
|
(tracks last-emitted second to avoid flooding).
|
|
Calls `_advancePhase()` when `phaseRemaining <= 0`.
|
|
|
|
```js
|
|
_advancePhase(): void [private]
|
|
```
|
|
State machine transitions:
|
|
```
|
|
set → rest (if restTime > 0, else skip to move)
|
|
rest → move (if moveTime > 0 and not last set, else skip)
|
|
move → set (increment set counter; if set > setCount, increment exercise; if exercise > exerciseCount, increment lap)
|
|
last lap + last exercise + last set → complete()
|
|
```
|
|
Sets new `phaseEndTime`. Emits `timer:phase-change` with `{ phase, lap, exercise, set }`.
|
|
|
|
```js
|
|
complete(): void [private]
|
|
```
|
|
Clears the `setInterval`. Removes this engine from the active sessions `Map` in `service.js`.
|
|
Sets `status = 'complete'`. Emits `timer:complete` to the room.
|
|
Does NOT call `stop()` — natural completion and manual stop are distinct paths.
|
|
`stop()` is only ever called by an explicit coach/owner stop request.
|
|
|
|
---
|
|
|
|
## modules/crossfit/service.js
|
|
|
|
```js
|
|
getCrossfitWorkouts(
|
|
orgId: number,
|
|
filters: { page?: number, limit?: number }
|
|
): Promise<{ rows: CrossfitWorkout[], count: number }>
|
|
```
|
|
Parses `workoutItems` JSON on each row before returning.
|
|
|
|
```js
|
|
createCrossfitWorkout(
|
|
orgId: number,
|
|
data: { name, workoutDate, workoutItems: string[] },
|
|
actorId: number
|
|
): Promise<CrossfitWorkout>
|
|
```
|
|
Validates `workoutItems` via Zod: non-empty array, max 50 items, each item a non-empty
|
|
string max 500 characters. Stores as JSON. Logs `crossfit.create` audit.
|
|
|
|
```js
|
|
deleteCrossfitWorkout(
|
|
id: number,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<void>
|
|
```
|
|
Owner-only (checked by route). Logs `crossfit.delete` audit.
|
|
|
|
---
|
|
|
|
## modules/clients/service.js
|
|
|
|
```js
|
|
getClients(
|
|
requesterId: number,
|
|
orgId: number,
|
|
requesterRole: string
|
|
): Promise<User[]>
|
|
```
|
|
If `Owner | SystemAdmin`: returns all Client-role users in org.
|
|
If `Coach`: returns only clients with an active CoachClientLink to requesterId.
|
|
|
|
```js
|
|
getClientById(
|
|
clientId: number,
|
|
requesterId: number,
|
|
orgId: number,
|
|
requesterRole: string
|
|
): Promise<User>
|
|
```
|
|
Includes active coach assignment. Access check: Coach can only get their own clients.
|
|
Throws 404 if not found or not accessible.
|
|
|
|
```js
|
|
assignCoach(
|
|
clientId: number,
|
|
coachId: number,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<CoachClientLink>
|
|
```
|
|
Validates both users exist in org and have correct roles.
|
|
Deactivates any existing active link for this client+coach pair (idempotent upsert).
|
|
Creates new link. Logs `coach.client.assign` audit.
|
|
|
|
```js
|
|
unassignCoach(
|
|
linkId: number,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<void>
|
|
```
|
|
Sets `isActive = false`. Logs `coach.client.unassign` audit.
|
|
|
|
```js
|
|
getClientWorkouts(
|
|
clientId: number,
|
|
requesterId: number,
|
|
orgId: number,
|
|
requesterRole: string,
|
|
filters: { page?, limit?, includeCompleted?: boolean }
|
|
): Promise<{ rows: ClientWorkout[], count: number }>
|
|
```
|
|
Access check: Client sees only their own workouts. Coach sees only their clients' workouts.
|
|
Parses `items` JSON on each row.
|
|
**coachNotes stripping (server-enforced):** When `requesterRole === 'Client'`, the `notes`
|
|
field (coach notes on the workout record) is deleted from each row before returning. Item-level
|
|
`notes` within the `items` array are coaching instructions and remain visible to the client.
|
|
|
|
```js
|
|
createClientWorkout(
|
|
orgId: number,
|
|
data: { clientId, name, scheduledDate, notes?, items },
|
|
actorId: number
|
|
): Promise<ClientWorkout>
|
|
```
|
|
Validates `items` via Zod: max 100 items; each `video` item must have a valid `videoId` in org;
|
|
each `text` item must have a non-empty string max 1000 characters; item-level `notes` max 500
|
|
characters. Validates coach has active link to client. Logs `client_workout.create` audit.
|
|
|
|
```js
|
|
updateClientWorkout(
|
|
id: number,
|
|
orgId: number,
|
|
data: Partial<ClientWorkoutData>,
|
|
actorId: number
|
|
): Promise<ClientWorkout>
|
|
```
|
|
Validates ownership (same coach). Logs `client_workout.update` audit with before/after.
|
|
|
|
```js
|
|
deleteClientWorkout(
|
|
id: number,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<void>
|
|
```
|
|
Soft delete: sets `deletedAt = now()`. Logs `client_workout.delete` audit.
|
|
|
|
```js
|
|
completeClientWorkout(
|
|
id: number,
|
|
orgId: number,
|
|
actorId: number
|
|
): Promise<ClientWorkout>
|
|
```
|
|
Sets `completedAt = now()`. Both coach and client can call this. Logs `client_workout.complete` audit.
|
|
|
|
```js
|
|
getSessions(
|
|
filters: { clientId?, startAfter?, endBefore?, status?, page?, limit? },
|
|
orgId: number,
|
|
requesterId: number,
|
|
requesterRole: string
|
|
): Promise<{ rows: CalendarSession[], count: number }>
|
|
```
|
|
Scope: Coach sees own sessions. Client sees own sessions. Owner sees all.
|
|
Strips `coachNotes` from response when requester is a Client.
|
|
|
|
```js
|
|
createSession(
|
|
orgId: number,
|
|
data: { clientId?, title, sessionType, startAt, endAt, locationNotes?, coachNotes?, sharedNotes?, linkedWorkoutId? },
|
|
actorId: number
|
|
): Promise<CalendarSession>
|
|
```
|
|
Validates `endAt > startAt`. Validates linkedWorkoutId belongs to clientId if provided.
|
|
Logs `session.create` audit.
|
|
|
|
```js
|
|
updateSession(
|
|
id: number,
|
|
orgId: number,
|
|
data: Partial<SessionData>,
|
|
actorId: number
|
|
): Promise<CalendarSession>
|
|
```
|
|
Validates ownership. Logs `session.update` audit with before/after.
|
|
|
|
```js
|
|
cancelSession(
|
|
id: number,
|
|
orgId: number,
|
|
actorId: number,
|
|
actorRole: string
|
|
): Promise<CalendarSession>
|
|
```
|
|
Sets `status = 'cancelled'`. Both coach and client can cancel.
|
|
**24-hour rule (server-enforced):** If `actorRole === 'Client'` and
|
|
`(new Date(session.startAt) - Date.now()) / 3600000 < 24`, throws
|
|
`AppError('CANCELLATION_TOO_LATE', 'Sessions must be cancelled at least 24 hours in advance.', 400)`.
|
|
Coaches and Owners bypass the 24-hour check.
|
|
Client cancellation logs `session.cancel` with `cancelledBy: 'client'`.
|
|
Logs `session.cancel` audit.
|
|
|
|
---
|
|
|
|
## modules/audit/routes.js
|
|
|
|
No service.js — reads directly from AuditLog model. Writes are via `core/audit.js`.
|
|
|
|
```js
|
|
GET /api/v1/audit-logs
|
|
→ authenticateToken, authenticateRole(['Owner', 'SystemAdmin'])
|
|
→ Queries AuditLog with filters: action, userId, entityType, from, to
|
|
→ Returns paginated collection
|
|
|
|
GET /api/v1/audit-logs/export
|
|
→ authenticateToken, authenticateRole(['Owner', 'SystemAdmin'])
|
|
→ Streams CSV response
|
|
→ Sets Content-Disposition: attachment; filename="audit-log-<date>.csv"
|
|
```
|
|
|
|
---
|
|
|
|
## modules/sysadmin/routes.js
|
|
|
|
No service.js — uses models directly with cross-org queries (no orgId filter).
|
|
|
|
```js
|
|
GET /api/v1/sysadmin/orgs
|
|
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
|
→ Returns all orgs with user counts
|
|
|
|
GET /api/v1/sysadmin/orgs/:id
|
|
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
|
→ Returns org detail with branding, user list summary
|
|
|
|
PATCH /api/v1/sysadmin/orgs/:id
|
|
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
|
→ Updates timezone, features, isActive, licenseOwner, licenseEmail
|
|
|
|
GET /api/v1/sysadmin/health
|
|
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
|
→ Returns full health details: version, DB migrations, storage, uptime, active timer sessions
|
|
```
|