# 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