This commit is contained in:
Ccjcarkbla
2026-06-13 08:03:45 -04:00
parent cfcd6ae11e
commit a2c300678b
121 changed files with 8639 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const logger = require('./logger');
async function log(req, action, entityType, entityId, details = {}) {
try {
const { models } = require('./db');
await models.AuditLog.create({
organizationId: req.user?.organizationId ?? null,
userId: req.user?.id ?? null,
userRole: req.user?.role ?? null,
action,
entityType: entityType ?? null,
entityId: entityId ?? null,
details,
ipAddress: req.ip,
userAgent: req.get('User-Agent'),
});
} catch (err) {
logger.warn({ err, action }, 'Audit log write failed');
}
}
module.exports = { log };
+94
View File
@@ -0,0 +1,94 @@
'use strict';
const jwt = require('jsonwebtoken');
const { AppError } = require('./errors');
// Feature flag cache: orgId → { features: string[], fetchedAt: number }
const featureCache = new Map();
const FEATURE_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
function authenticateToken(req, res, next) {
const header = req.headers.authorization;
if (!header || !header.startsWith('Bearer ')) {
return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401));
}
const token = header.slice(7);
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, async (err, decoded) => {
if (err) {
return next(new AppError('AUTH_INVALID', 'Invalid or expired token.', 401));
}
try {
const { models } = require('./db');
const user = await models.User.findByPk(decoded.id, {
attributes: ['id', 'username', 'role', 'organizationId', 'isActive', 'passwordChangedAt'],
});
if (!user || !user.isActive) {
return next(new AppError('AUTH_INVALID', 'User not found or inactive.', 401));
}
if (user.passwordChangedAt && decoded.iat * 1000 < user.passwordChangedAt.getTime()) {
return next(new AppError('AUTH_INVALID', 'Token issued before last password change.', 401));
}
req.user = {
id: user.id,
username: user.username,
role: user.role,
organizationId: user.organizationId,
};
next();
} catch (dbErr) {
next(dbErr);
}
});
}
function authenticateRole(roles) {
return (req, res, next) => {
if (!req.user) {
return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401));
}
if (!roles.includes(req.user.role)) {
return next(new AppError('AUTH_FORBIDDEN', 'You do not have permission to perform this action.', 403));
}
next();
};
}
function requireFeature(feature) {
return async (req, res, next) => {
if (!req.user) {
return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401));
}
const orgId = req.user.organizationId;
const cached = featureCache.get(orgId);
if (cached && Date.now() - cached.fetchedAt < FEATURE_CACHE_TTL) {
if (!cached.features.includes(feature)) {
return next(new AppError('FEATURE_DISABLED', 'This feature is not enabled for your organization.', 403));
}
return next();
}
try {
const { models } = require('./db');
const org = await models.Organization.findByPk(orgId, { attributes: ['features'] });
const features = org ? org.features : [];
featureCache.set(orgId, { features, fetchedAt: Date.now() });
if (!features.includes(feature)) {
return next(new AppError('FEATURE_DISABLED', 'This feature is not enabled for your organization.', 403));
}
next();
} catch (err) {
next(err);
}
};
}
module.exports = { authenticateToken, authenticateRole, requireFeature };
+91
View File
@@ -0,0 +1,91 @@
'use strict';
const { Sequelize, DataTypes } = require('sequelize');
const path = require('path');
const fs = require('fs');
const logger = require('./logger');
let sequelize;
let models = {};
function initDb() {
const dbPath = process.env.DB_PATH || path.join(__dirname, '..', 'database.sqlite');
sequelize = new Sequelize({
dialect: 'sqlite',
storage: dbPath,
logging: (sql) => logger.trace({ sql }, 'SQL'),
});
// Required SQLite pragmas
sequelize.query('PRAGMA journal_mode = WAL;');
sequelize.query('PRAGMA busy_timeout = 5000;');
sequelize.query('PRAGMA foreign_keys = ON;');
// Register all models by scanning module directories
const modulesDir = path.join(__dirname, '..', 'modules');
fs.readdirSync(modulesDir).forEach(name => {
const modelPath = path.join(modulesDir, name, 'model.js');
if (fs.existsSync(modelPath)) {
const moduleModels = require(modelPath)(sequelize, DataTypes);
Object.assign(models, moduleModels);
}
});
// Run associations after all models are loaded
Object.values(models).forEach(model => {
if (typeof model.associate === 'function') {
model.associate(models);
}
});
logger.info({ dbPath }, 'Database initialized');
return sequelize.authenticate();
}
async function runMigrations() {
const { Umzug, SequelizeStorage } = require('umzug');
// Collect all migration files from modules/*/migrations/
const modulesDir = path.join(__dirname, '..', 'modules');
const migrationFiles = [];
fs.readdirSync(modulesDir).sort().forEach(moduleName => {
const migrationsDir = path.join(modulesDir, moduleName, 'migrations');
if (fs.existsSync(migrationsDir)) {
fs.readdirSync(migrationsDir).sort().forEach(file => {
if (file.endsWith('.js')) {
migrationFiles.push(path.join(migrationsDir, file));
}
});
}
});
// Sort globally by filename prefix (001, 002, ...)
migrationFiles.sort((a, b) => path.basename(a).localeCompare(path.basename(b)));
const umzug = new Umzug({
migrations: migrationFiles.map(filePath => ({
name: path.basename(filePath, '.js'),
path: filePath,
up: async ({ context }) => require(filePath).up(context, Sequelize),
down: async ({ context }) => require(filePath).down(context, Sequelize),
})),
context: sequelize.getQueryInterface(),
storage: new SequelizeStorage({ sequelize }),
logger,
});
const pending = await umzug.pending();
if (pending.length > 0) {
logger.info({ count: pending.length }, 'Running pending migrations');
await umzug.up();
logger.info('Migrations complete');
}
}
function getSequelize() {
return sequelize;
}
module.exports = { initDb, runMigrations, getSequelize, get sequelize() { return sequelize; }, get models() { return models; } };
+42
View File
@@ -0,0 +1,42 @@
'use strict';
const logger = require('./logger');
class AppError extends Error {
constructor(code, message, status = 500, field = null) {
super(message);
this.name = 'AppError';
this.code = code;
this.status = status;
this.field = field;
}
}
function errorHandler(err, req, res, next) {
if (err instanceof AppError) {
return res.status(err.status).json({
error: {
code: err.code,
message: err.message,
...(err.field ? { field: err.field } : {}),
},
});
}
// Multer errors
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({
error: { code: 'UPLOAD_SIZE_EXCEEDED', message: 'File exceeds the maximum allowed size.' },
});
}
logger.error({ err, req: { method: req.method, url: req.url } }, 'Unhandled error');
const message = process.env.NODE_ENV === 'production'
? 'An unexpected error occurred.'
: err.message;
res.status(500).json({ error: { code: 'INTERNAL_ERROR', message } });
}
module.exports = { AppError, errorHandler };
+13
View File
@@ -0,0 +1,13 @@
'use strict';
const pino = require('pino');
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty', options: { colorize: true, ignore: 'pid,hostname' } }
: undefined,
redact: ['req.headers.authorization', 'body.password', 'body.currentPassword', 'body.newPassword'],
});
module.exports = logger;
+33
View File
@@ -0,0 +1,33 @@
'use strict';
function ok(res, data) {
res.status(200).json({ data });
}
function created(res, data) {
res.status(201).json({ data });
}
function collection(res, data, total, page, limit) {
res.status(200).json({
data,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
});
}
function noContent(res) {
res.status(204).end();
}
function err(res, code, message, status, field) {
res.status(status).json({
error: { code, message, ...(field ? { field } : {}) },
});
}
module.exports = { ok, created, collection, noContent, err };
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const { z } = require('zod');
const login = z.object({
username: z.string().min(1).max(64),
password: z.string().min(1).max(128),
rememberDevice: z.boolean().optional().default(false),
deviceName: z.string().max(200).optional(),
deviceType: z.enum(['kiosk', 'personal']).optional().default('personal'),
});
const deviceLogin = z.object({
deviceToken: z.string().min(1),
});
const changeOwnPassword = z.object({
currentPassword: z.string().min(1).max(128),
newPassword: z.string().min(8).max(128),
});
module.exports = { login, deviceLogin, changeOwnPassword };
+54
View File
@@ -0,0 +1,54 @@
'use strict';
const { z } = require('zod');
const createClient = z.object({
username: z.string().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/),
firstName: z.string().max(100).optional(),
lastName: z.string().max(100).optional(),
email: z.string().email().optional(),
password: z.string().min(8).max(128),
coachId: z.number().int().positive().optional(),
});
const assignCoach = z.object({
coachId: z.number().int().positive(),
});
const workoutItem = z.discriminatedUnion('type', [
z.object({
type: z.literal('video'),
videoId: z.number().int().positive(),
reps: z.number().int().min(0).optional(),
sets: z.number().int().min(0).optional(),
notes: z.string().max(500).optional(),
}),
z.object({
type: z.literal('text'),
text: z.string().min(1).max(1000),
}),
]);
const createClientWorkout = z.object({
name: z.string().min(1).max(200),
scheduledDate: z.string().datetime().optional(),
notes: z.string().max(2000).optional(),
items: z.array(workoutItem).min(1).max(100),
});
const updateClientWorkout = createClientWorkout.partial();
const createSession = z.object({
title: z.string().min(1).max(200),
sessionType: z.enum(['personal', 'group', 'assessment', 'other']).default('personal'),
startAt: z.string().datetime(),
endAt: z.string().datetime(),
locationNotes: z.string().max(500).optional(),
coachNotes: z.string().max(2000).optional(),
sharedNotes: z.string().max(2000).optional(),
linkedWorkoutId: z.number().int().positive().optional(),
});
const updateSession = createSession.partial();
module.exports = { createClient, assignCoach, createClientWorkout, updateClientWorkout, createSession, updateSession };
+11
View File
@@ -0,0 +1,11 @@
'use strict';
const { z } = require('zod');
const createCrossfitWorkout = z.object({
name: z.string().min(1).max(200),
workoutDate: z.string().datetime().optional(),
workoutItems: z.array(z.string().min(1).max(500)).min(1).max(50),
});
module.exports = { createCrossfitWorkout };
+23
View File
@@ -0,0 +1,23 @@
'use strict';
const { z } = require('zod');
const hexColor = z.string().regex(/^#[0-9A-Fa-f]{6}$/, 'Must be a valid hex color (e.g. #00FF88)');
const updateOrg = z.object({
name: z.string().min(1).max(200).optional(),
timezone: z.string().max(100).optional(),
licenseOwner: z.string().max(200).optional(),
licenseEmail: z.string().email().optional(),
}).strict();
const updateBranding = z.object({
appName: z.string().min(1).max(200).optional(),
primaryColor: hexColor.optional(),
secondaryColor: hexColor.optional(),
workColor: hexColor.optional(),
restColor: hexColor.optional(),
moveColor: hexColor.optional(),
}).strict();
module.exports = { updateOrg, updateBranding };
+19
View File
@@ -0,0 +1,19 @@
'use strict';
const { z } = require('zod');
const positiveInt = z.number().int().positive();
const nonNegInt = z.number().int().min(0);
const createTimer = z.object({
name: z.string().min(1).max(200),
totalTime: positiveInt,
setTime: positiveInt,
restTime: nonNegInt.default(0),
moveTime: nonNegInt.default(0),
setCount: positiveInt,
exerciseCount: positiveInt,
lapCount: positiveInt.default(1),
});
module.exports = { createTimer };
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const { z } = require('zod');
const createUser = z.object({
username: z.string().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/, 'Username may only contain letters, numbers, underscores, dots, and hyphens'),
email: z.string().email().optional(),
firstName: z.string().max(100).optional(),
lastName: z.string().max(100).optional(),
password: z.string().min(8).max(128),
role: z.enum(['Owner', 'Coach', 'Client']),
});
const updateProfile = z.object({
firstName: z.string().max(100).optional(),
lastName: z.string().max(100).optional(),
email: z.string().email().optional(),
}).strict();
const resetPassword = z.object({
newPassword: z.string().min(8).max(128),
});
const changeRole = z.object({
role: z.enum(['Owner', 'Coach', 'Client']),
});
module.exports = { createUser, updateProfile, resetPassword, changeRole };
+14
View File
@@ -0,0 +1,14 @@
'use strict';
const { z } = require('zod');
const uploadVideo = z.object({
description: z.string().max(500).optional().default(''),
category: z.string().min(1).max(100),
});
const createCategory = z.object({
name: z.string().min(1).max(100),
});
module.exports = { uploadVideo, createCategory };
+18
View File
@@ -0,0 +1,18 @@
'use strict';
const { z } = require('zod');
const createWorkout = z.object({
name: z.string().min(1).max(200),
workoutDate: z.string().datetime().optional(),
video1: z.number().int().positive().nullable().optional(),
video2: z.number().int().positive().nullable().optional(),
video3: z.number().int().positive().nullable().optional(),
video4: z.number().int().positive().nullable().optional(),
number1: z.number().int().min(0).nullable().optional(),
number2: z.number().int().min(0).nullable().optional(),
number3: z.number().int().min(0).nullable().optional(),
number4: z.number().int().min(0).nullable().optional(),
});
module.exports = { createWorkout };
+49
View File
@@ -0,0 +1,49 @@
'use strict';
const { Server } = require('socket.io');
const jwt = require('jsonwebtoken');
const logger = require('./logger');
let io;
function init(httpServer) {
io = new Server(httpServer, {
cors: {
origin: process.env.NODE_ENV === 'production'
? process.env.CORS_ORIGIN
: true,
credentials: true,
},
});
io.use((socket, next) => {
const token = socket.handshake.auth?.token;
if (!token) {
return next(new Error('Authentication required'));
}
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, (err, decoded) => {
if (err) return next(new Error('Invalid token'));
socket.data.user = decoded;
next();
});
});
io.on('connection', (socket) => {
logger.debug({ userId: socket.data.user?.id }, 'Socket connected');
socket.on('disconnect', (reason) => {
logger.debug({ userId: socket.data.user?.id, reason }, 'Socket disconnected');
});
});
logger.info('Socket.io initialized');
return io;
}
function getIo() {
if (!io) throw new Error('Socket.io not initialized — call init() first');
return io;
}
module.exports = { init, getIo };
+74
View File
@@ -0,0 +1,74 @@
'use strict';
const fs = require('fs');
const path = require('path');
const checkDiskSpace = require('check-disk-space').default;
const { AppError } = require('./errors');
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', 'uploads');
const WARN_BYTES = () => parseInt(process.env.STORAGE_WARN_BYTES || String(5 * 1024 ** 3), 10);
let cache = null;
let cacheTime = 0;
let inflightPromise = null;
async function getUploadsSize() {
const dir = UPLOADS_DIR();
let total = 0;
let count = 0;
try {
const files = fs.readdirSync(dir);
for (const f of files) {
try {
const stat = fs.statSync(path.join(dir, f));
if (stat.isFile()) { total += stat.size; count++; }
} catch {}
}
} catch {}
return { size: total, fileCount: count };
}
async function getStorageInfo() {
if (cache && Date.now() - cacheTime < 60_000) return cache;
if (inflightPromise) return inflightPromise;
inflightPromise = (async () => {
const [disk, uploads] = await Promise.all([
checkDiskSpace(UPLOADS_DIR()),
getUploadsSize(),
]);
const result = {
disk: {
total: disk.size,
used: disk.size - disk.free,
free: disk.free,
usedPercent: Math.round(((disk.size - disk.free) / disk.size) * 100),
},
uploads,
warning: disk.free < WARN_BYTES(),
warnThresholdBytes: WARN_BYTES(),
};
cache = result;
cacheTime = Date.now();
inflightPromise = null;
return result;
})();
return inflightPromise;
}
async function checkUploadAllowed(req, res, next) {
try {
const info = await getStorageInfo();
if (info.warning) {
return next(new AppError('STORAGE_INSUFFICIENT', 'Not enough disk space to upload. Contact your administrator.', 507));
}
next();
} catch (err) {
next(err);
}
}
module.exports = { getStorageInfo, checkUploadAllowed };