initial commit

This commit is contained in:
Alex Holliday committed 2025-11-13 13:47:26 -08:00
1 parent 7cb985116e
commit 75acf7b38f
955 files changed
+37333 -87054

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
import { Request, Response, NextFunction } from "express";
import { OrgMembership, TeamMembership, IRole } from "@/db/models/index.js";
import ApiError from "@/utils/ApiError.js";
interface IRolesObj {
orgRole?: IRole;
teamRole: IRole;
}
interface IRolesCacheData {
data: IRolesObj;
expiresAt: number;
}
interface ITeamIdsCacheData {
data: string[];
expiresAt: number;
}
const CACHE_TTL = 5 * 60 * 1000;
const rolesCache = new Map<string, IRolesCacheData>();
const teamIdsCache = new Map<string, ITeamIdsCacheData>();
export const invalidateCachesForUser = (userId: string) => {
for (const key of rolesCache.keys()) {
if (key.startsWith(userId + ":")) {
rolesCache.delete(key);
}
}
for (const key of teamIdsCache.keys()) {
if (key.startsWith(userId)) {
teamIdsCache.delete(key);
}
}
};
const getTeamIds = async (userId: string): Promise<string[]> => {
// Try to get from cache
if (teamIdsCache.has(userId)) {
const cached = teamIdsCache.get(userId);
if (!cached) {
throw new ApiError("TeamID cache retrieval error", 500);
}
if (cached.expiresAt > Date.now()) {
return cached.data;
}
}
// If not in cache or expired, fetch from DB
const teamMemberships = await TeamMembership.find({ userId })
.select("teamId")
.lean();
const teamIds = teamMemberships.map((t) => t.teamId.toString());
teamIdsCache.set(userId, {
data: teamIds,
expiresAt: Date.now() + CACHE_TTL,
});
return teamIds;
};
const getRoles = async (
userId: string,
orgId: string,
currentTeamId: string
) => {
// Try to get from cache
if (rolesCache.has(`${userId}:${orgId}:${currentTeamId}`)) {
const cached = rolesCache.get(`${userId}:${orgId}:${currentTeamId}`);
if (!cached) {
throw new ApiError("Roles cache retrieval error", 500);
}
if (cached.expiresAt > Date.now()) {
return cached.data;
}
}
const [orgRole, teamRole] = await Promise.all([
OrgMembership.findOne({ userId, orgId })
.populate<{ roleId: IRole }>("roleId")
.select("roleId")
.lean(),
TeamMembership.findOne({ userId, teamId: currentTeamId })
.populate<{ roleId: IRole }>("roleId")
.select("roleId")
.lean(),
]);
if (!orgRole) {
throw new ApiError("User has no role in the organization", 403);
}
if (!teamRole) {
throw new ApiError("User has no role in the team", 403);
}
const cacheData = { orgRole: orgRole.roleId, teamRole: teamRole.roleId };
rolesCache.set(`${userId}:${orgId}:${currentTeamId}`, {
data: cacheData,
expiresAt: Date.now() + CACHE_TTL,
});
return cacheData;
};
export const addUserContext = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
if (!req.user) {
throw new ApiError("User not authenticated", 401);
}
// Get identifiers
const sub = req.user.sub;
const orgId = req.user.orgId;
const currentTeamId = req.headers["x-team-id"] as string;
// Get user team IDs
const teamIds = await getTeamIds(sub);
// Short circuit if user doesn't belong to selected team
if (!teamIds.includes(currentTeamId)) {
throw new ApiError("User does not belong to the selected team", 403);
}
// Get user roles to context
const { orgRole, teamRole } = await getRoles(sub, orgId, currentTeamId);
// Populate user context
req.user.teamIds = teamIds;
req.user.roles = {
orgRole,
teamRole,
};
req.user.currentTeamId = currentTeamId;
return next();
} catch (error) {
next(error);
}
};
+18
View File
@@ -0,0 +1,18 @@
import { Request, Response, NextFunction } from "express";
import { getChildLogger } from "@/logger/Logger.js";
import ApiError from "@/utils/ApiError.js";
const logger = getChildLogger("ErrorHandler");
export const errorHandler = (
err: Error | ApiError,
req: Request,
res: Response,
next: NextFunction
) => {
logger.error(err);
if (err instanceof ApiError) {
res.status(err.status).json({ message: err.message });
} else {
res.status(500).json({ message: err.message || "Internal Server Error" });
}
};
+70
View File
@@ -0,0 +1,70 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "@/utils/ApiError.js";
import { TeamMembership } from "@/db/models/index.js";
import type { IRole } from "@/db/models/index.js";
export const hasPermission = (
permissions: string[],
requiredPermissions: string[]
) => {
if (permissions.includes("*")) return true;
const matches = (requiredPermission: string, userPermission: string) => {
if (userPermission === requiredPermission) return true;
if (userPermission.endsWith(".*")) {
const prefix = userPermission.slice(0, -2);
return requiredPermission.startsWith(prefix + ".");
}
return false;
};
return requiredPermissions.every((requiredPermission) => {
return permissions.some((permission) =>
matches(requiredPermission, permission)
);
});
};
const verifyTeamPermission = (resourceActions: string[]) => {
return async (req: Request, res: Response, next: NextFunction) => {
const tokenizedUser = req.user;
if (!tokenizedUser) {
throw new ApiError("No user", 400);
}
const userId = tokenizedUser.sub;
if (!userId) {
throw new ApiError("No user ID", 400);
}
const orgPermissions = tokenizedUser.roles?.orgRole?.permissions || [];
const teamPermissions = tokenizedUser.roles?.teamRole.permissions || [];
const allPermissions = [...orgPermissions, ...teamPermissions];
const allowed = hasPermission(allPermissions, resourceActions);
if (!allowed) {
throw new ApiError("Insufficient permissions", 403);
}
next();
};
};
const verifyOrgPermission = (resourceActions: string[]) => {
return async (req: Request, res: Response, next: NextFunction) => {
const userContext = req.user;
if (!userContext) {
throw new ApiError("No user", 400);
}
const orgPermissions = userContext.roles?.orgRole?.permissions || [];
const allowed = hasPermission(orgPermissions, resourceActions);
if (!allowed) {
throw new ApiError("Insufficient permissions", 403);
}
next();
};
};
export { verifyTeamPermission, verifyOrgPermission };
+20
View File
@@ -0,0 +1,20 @@
import { Request, Response, NextFunction } from "express";
import { decode } from "@/utils/JWTUtils.js";
import ApiError from "@/utils/ApiError.js";
const verifyToken = (req: Request, res: Response, next: NextFunction) => {
const token = req.cookies.token;
if (!token) {
const error = new ApiError("No token provided", 401);
return next(error);
}
try {
const decoded = decode(token);
req.user = decoded;
next();
} catch (error) {
next(error);
}
};
export { verifyToken };
-22
View File
@@ -1,22 +0,0 @@
import { logger } from "../../utils/logger.js";
import ServiceRegistry from "../../service/v1/system/serviceRegistry.js";
import StringService from "../../service/v1/system/stringService.js";
const handleErrors = (error, req, res, next) => {
const status = error.status || 500;
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
const message = error.message || stringService.authIncorrectPassword;
const service = error.service || stringService.unknownService;
logger.error({
message: message,
service: service,
method: error.method,
stack: error.stack,
});
res.error({
status,
msg: message,
});
};
export { handleErrors };
-57
View File
@@ -1,57 +0,0 @@
import jwt from "jsonwebtoken";
const TOKEN_PREFIX = "Bearer ";
const SERVICE_NAME = "allowedRoles";
import ServiceRegistry from "../../service/v1/system/serviceRegistry.js";
import StringService from "../../service/v1/system/stringService.js";
import SettingsService from "../../service/v1/system/settingsService.js";
const isAllowed = (allowedRoles) => {
return (req, res, next) => {
const token = req.headers["authorization"];
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
// If no token is pressent, return an error
if (!token) {
const error = new Error(stringService.noAuthToken);
error.status = 401;
error.service = SERVICE_NAME;
next(error);
return;
}
// If the token is improperly formatted, return an error
if (!token.startsWith(TOKEN_PREFIX)) {
const error = new Error(stringService.invalidAuthToken);
error.status = 400;
error.service = SERVICE_NAME;
next(error);
return;
}
// Parse the token
try {
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
var decoded = jwt.verify(parsedToken, jwtSecret);
const userRoles = decoded.role;
// Check if the user has the required role
if (userRoles.some((role) => allowedRoles.includes(role))) {
next();
return;
} else {
const error = new Error(stringService.insufficientPermissions);
error.status = 403;
error.service = SERVICE_NAME;
next(error);
return;
}
} catch (error) {
error.status = 401;
error.method = "isAllowed";
error.service = SERVICE_NAME;
next(error);
return;
}
};
};
export { isAllowed };
@@ -1,27 +0,0 @@
import { logger } from "../../utils/logger.js";
const languageMiddleware = (stringService, translationService) => async (req, res, next) => {
try {
const acceptLanguage = req.headers["accept-language"] || "en";
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
translationService.setLanguage(language);
stringService.setLanguage(language);
next();
} catch (error) {
logger.error({
message: error.message,
service: "languageMiddleware",
});
const acceptLanguage = req.headers["accept-language"] || "en";
const language = acceptLanguage.split(",")[0].slice(0, 2).toLowerCase();
translationService.setLanguage(language);
stringService.setLanguage(language);
next();
}
};
export default languageMiddleware;
-17
View File
@@ -1,17 +0,0 @@
import rateLimit from "express-rate-limit";
export const generalApiLimiter = rateLimit({
window: 60 * 1000,
limit: 600,
standardHeaders: true,
legacyHeaders: false,
ipv6Subnet: 64,
});
export const authApiLimiter = rateLimit({
window: 60 * 1000,
limit: 15,
standardHeaders: true,
legacyHeaders: false,
ipv6Subnet: 64,
});
@@ -1,66 +0,0 @@
/**
* Middleware that adds standardized response methods to the Express response object.
* This allows for consistent API responses throughout the application.
*
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {import('express').NextFunction} next - Express next middleware function
*/
const responseHandler = (req, res, next) => {
/**
* Sends a standardized success response
*
* @param {Object} options - Success response options
* @param {number} [options.status=200] - HTTP status code
* @param {string} [options.msg="OK"] - Success message
* @param {*} [options.data=null] - Response data payload
* @returns {Object} Express response object
*/
res.success = ({ status = 200, msg = "OK", data = null, headers = {} }) => {
// Set custom headers if provided
Object.entries(headers).forEach(([key, value]) => {
res.set(key, value);
});
return res.status(status).json({
success: true,
msg: msg,
data: data,
});
};
/**
* Sends a standardized error response
*
* @param {Object} options - Error response options
* @param {number} [options.status=500] - HTTP status code
* @param {string} [options.msg="Internal server error"] - Error message
* @param {*} [options.data=null] - Additional error data (if any)
* @returns {Object} Express response object
*/
res.error = ({ status = 500, msg = "Internal server error", data = null }) => {
return res.status(status).json({
success: false,
msg,
data,
});
};
/**
* Sends a raw file response (for CSV, PDF, etc.)
* @param {Object} options
* @param {Buffer|string} options.data - The file content
* @param {Object} options.headers - Headers to set (e.g. Content-Type, Content-Disposition)
* @param {number} [options.status=200] - HTTP status code
*/
res.file = ({ data, headers = {}, status = 200 }) => {
Object.entries(headers).forEach(([key, value]) => {
res.setHeader(key, value);
});
return res.status(status).send(data);
};
next();
};
export { responseHandler };
-85
View File
@@ -1,85 +0,0 @@
import { JSDOM } from "jsdom";
import DOMPurify from "isomorphic-dompurify";
// Initialize DOMPurify with jsdom
const window = new JSDOM("").window;
const purify = DOMPurify(window);
/**
* Sanitizes user input to prevent XSS attacks
* @param {string} input - The input string to sanitize
* @param {Object} options - Sanitization options
* @returns {string} The sanitized string
*/
export const sanitizeInput = (input, options = {}) => {
if (typeof input !== "string") {
return input;
}
// Default configuration - remove all HTML tags and attributes
const defaultConfig = {
ALLOWED_TAGS: [],
ALLOWED_ATTR: [],
KEEP_CONTENT: true,
...options,
};
return purify.sanitize(input, defaultConfig);
};
/**
* Sanitizes an object recursively
* @param {Object} obj - The object to sanitize
* @param {Object} options - Sanitization options
* @returns {Object} The sanitized object
*/
export const sanitizeObject = (obj, options = {}) => {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((item) => sanitizeObject(item, options));
}
const sanitized = {};
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "string") {
sanitized[key] = sanitizeInput(value, options);
} else if (typeof value === "object" && value !== null) {
sanitized[key] = sanitizeObject(value, options);
} else {
sanitized[key] = value;
}
}
return sanitized;
};
/**
* Express middleware for sanitizing request body
* @param {Object} options - Sanitization options
* @returns {Function} Express middleware function
*/
export const sanitizeBody = (options = {}) => {
return (req, res, next) => {
if (req.body && typeof req.body === "object") {
req.body = sanitizeObject(req.body, options);
}
next();
};
};
/**
* Express middleware for sanitizing query parameters
* @param {Object} options - Sanitization options
* @returns {Function} Express middleware function
*/
export const sanitizeQuery = (options = {}) => {
return (req, res, next) => {
if (req.query && typeof req.query === "object") {
req.query = sanitizeObject(req.query, options);
}
next();
};
};
-57
View File
@@ -1,57 +0,0 @@
import jwt from "jsonwebtoken";
import ServiceRegistry from "../../service/v1/system/serviceRegistry.js";
import SettingsService from "../../service/v1/system/settingsService.js";
import StringService from "../../service/v1/system/stringService.js";
const SERVICE_NAME = "verifyJWT";
const TOKEN_PREFIX = "Bearer ";
/**
* Verifies the JWT token
* @function
* @param {express.Request} req
* @param {express.Response} res
* @param {express.NextFunction} next
* @returns {express.Response}
*/
const verifyJWT = (req, res, next) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
const token = req.headers["authorization"];
// Make sure a token is provided
if (!token) {
const error = new Error(stringService.noAuthToken);
error.status = 401;
error.service = SERVICE_NAME;
next(error);
return;
}
// Make sure it is properly formatted
if (!token.startsWith(TOKEN_PREFIX)) {
const error = new Error(stringService.invalidAuthToken); // Instantiate a new Error object for improperly formatted token
error.status = 401;
error.service = SERVICE_NAME;
error.method = "verifyJWT";
next(error);
return;
}
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
// Verify the token's authenticity
const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
if (err) {
const errorMessage = err.name === "TokenExpiredError" ? stringService.expiredAuthToken : stringService.invalidAuthToken;
err.details = { msg: errorMessage };
err.status = 401;
err.service = SERVICE_NAME;
err.method = "verifyJWT";
next(err);
return;
} else {
// Token is valid, carry on
req.user = decoded;
next();
}
});
};
export { verifyJWT };
@@ -1,59 +0,0 @@
import { logger } from "../../utils/logger.js";
import ServiceRegistry from "../../service/v1/system/serviceRegistry.js";
import StringService from "../../service/v1/system/stringService.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "verifyOwnership";
const verifyOwnership = (Model, paramName) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
return async (req, res, next) => {
const userId = req.user._id;
let documentId = req.params[paramName];
try {
if (typeof documentId === "string") {
documentId = ObjectId.createFromHexString(documentId);
}
const doc = await Model.findById(documentId);
//If the document is not found, return a 404 error
if (!doc) {
logger.error({
message: stringService.verifyOwnerNotFound,
service: SERVICE_NAME,
method: "verifyOwnership",
});
const error = new Error(stringService.verifyOwnerNotFound);
error.status = 404;
throw error;
}
// Special case for User model, as it will not have a `userId` field as other docs will
if (Model.modelName === "User") {
if (userId.toString() !== doc._id.toString()) {
const error = new Error(stringService.verifyOwnerUnauthorized);
error.status = 403;
throw error;
}
next();
return;
}
// If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) {
const error = new Error("Unauthorized");
error.status = 403;
throw error;
}
next();
return;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "verifyOwnership";
next(error);
return;
}
};
};
export { verifyOwnership };
@@ -1,66 +0,0 @@
const jwt = require("jsonwebtoken");
const logger = require("../../utils/logger.js");
const SERVICE_NAME = "verifyAdmin";
const TOKEN_PREFIX = "Bearer ";
import ServiceRegistry from "../service/serviceRegistry.js";
import SettingsService from "../service/settingsService.js";
import StringService from "../service/stringService.js";
/**
* Verifies the JWT token
* @function
* @param {express.Request} req
* @param {express.Response} res
* @param {express.NextFunction} next
* @returns {express.Response}
*/
const verifySuperAdmin = (req, res, next) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
const token = req.headers["authorization"];
// Make sure a token is provided
if (!token) {
const error = new Error(stringService.noAuthToken);
error.status = 401;
error.service = SERVICE_NAME;
next(error);
return;
}
// Make sure it is properly formatted
if (!token.startsWith(TOKEN_PREFIX)) {
const error = new Error(stringService.invalidAuthToken); // Instantiate a new Error object for improperly formatted token
error.status = 400;
error.service = SERVICE_NAME;
error.method = "verifySuperAdmin";
next(error);
return;
}
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
// verify admin role is present
const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
if (err) {
logger.error({
message: err.message,
service: SERVICE_NAME,
method: "verifySuperAdmin",
stack: err.stack,
details: stringService.invalidAuthToken,
});
return res.status(401).json({ success: false, msg: stringService.invalidAuthToken });
}
if (decoded.role.includes("superadmin") === false) {
logger.error({
message: stringService.invalidAuthToken,
service: SERVICE_NAME,
method: "verifySuperAdmin",
stack: err.stack,
});
return res.status(401).json({ success: false, msg: stringService.unauthorized });
}
next();
});
};
module.exports = { verifySuperAdmin };
@@ -1,38 +0,0 @@
const SERVICE_NAME = "verifyTeamAccess";
const verifyTeamAccess = (Model, paramName) => {
return async (req, res, next) => {
try {
const documentId = req.params[paramName];
const doc = await Model.findById(documentId);
if (!doc) {
const error = new Error("Document not found");
error.status = 404;
throw error;
}
if (!req?.user?.teamId || !doc.teamId) {
const error = new Error("Missing team information");
error.status = 400;
throw error;
}
if (req.user.teamId.toString() === doc.teamId.toString()) {
next();
return;
}
const error = new Error("Unauthorized");
error.status = 403;
throw error;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "verifyTeamAccess";
next(error);
return;
}
};
};
export { verifyTeamAccess };
@@ -1,77 +0,0 @@
import { Request, Response, NextFunction } from "express";
import ApiError from "../../utils/ApiError.js";
import { User, IUser, Role, IRole } from "../../db/v2/models/index.js";
const rolesCache = new Map<string, { roles: IRole[]; timestamp: number }>();
// const CACHE_TTL = 30 * 60 * 1000; // 30 minutes
const CACHE_TTL = 1; // 30 minutes
const MAX_CACHE_SIZE = 1000;
const getCachedRoles = async (userId: string) => {
if (rolesCache.size >= MAX_CACHE_SIZE) {
const oldestKey = rolesCache.keys().next().value;
if (!oldestKey) return null;
rolesCache.delete(oldestKey);
}
const cached = rolesCache.get(userId);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.roles;
}
const user: IUser | null = await User.findById(userId);
if (!user) {
return null;
}
const roles = await Role.find({ _id: { $in: user.roles } });
rolesCache.set(userId, { roles, timestamp: Date.now() });
return roles;
};
const hasPermission = (roles: IRole[], requiredPermissions: string[]) => {
const userPermissions = [...new Set(roles.flatMap((role) => role.permissions))];
if (userPermissions.includes("*")) return true;
const matches = (requiredPermission: string, userPermission: string) => {
if (userPermission === requiredPermission) return true;
if (userPermission.endsWith(".*")) {
const prefix = userPermission.slice(0, -2);
return requiredPermission.startsWith(prefix + ".");
}
return false;
};
return requiredPermissions.every((requiredPermission) => {
return userPermissions.some((userPermission) => matches(requiredPermission, userPermission));
});
};
const verifyPermission = (resourceActions: string[]) => {
return async (req: Request, res: Response, next: NextFunction) => {
const tokenizedUser = req.user;
if (!tokenizedUser) {
throw new ApiError("No user", 400);
}
const userId = tokenizedUser.sub;
if (!userId) {
throw new ApiError("No user ID", 400);
}
const userRoles = await getCachedRoles(userId);
if (!userRoles) {
throw new ApiError("User roles not found", 400);
}
const allowed = hasPermission(userRoles, resourceActions);
if (!allowed) {
throw new ApiError("Insufficient permissions", 403);
}
next();
};
};
export { verifyPermission };
-21
View File
@@ -1,21 +0,0 @@
import { Request, Response, NextFunction } from "express";
import { decode } from "../../utils/JWTUtils.js";
import ApiError from "../../utils/ApiError.js";
const verifyToken = (req: Request, res: Response, next: NextFunction) => {
const token = req.cookies.token;
if (!token) {
const error = new ApiError("No token provided", 401);
return next(error);
}
try {
const decoded = decode(token);
req.user = decoded;
next();
} catch (error) {
next(error);
}
};
export { verifyToken };
+37
View File
@@ -0,0 +1,37 @@
import { Request, Response, NextFunction } from "express";
import { z, ZodObject, ZodRawShape, ZodError } from "zod";
import { getChildLogger } from "@/logger/Logger.js";
const logger = getChildLogger("ValidationMiddleware");
export const validateBody = <T extends ZodObject<ZodRawShape>>(schema: T) => {
return (req: Request, res: Response, next: NextFunction) => {
try {
req.body = schema.strict().parse(req.body); // enforce strict keys
next();
} catch (err) {
logger.error("Error validating request body:", err);
if (err instanceof ZodError) {
return res.status(400).json({ errors: z.treeifyError(err) });
}
return res.status(500).json({ message: "Server error" });
}
};
};
export type TypedQueryRequest<T> = Request & { validatedQuery: T };
export const validateQuery = <T extends ZodObject<ZodRawShape>>(schema: T) => {
return (req: Request, res: Response, next: NextFunction) => {
try {
req.validatedQuery = schema.strict().parse(req.query);
next();
} catch (err) {
logger.error("Error validating request query:", err);
if (err instanceof ZodError) {
return res.status(400).json({ errors: z.treeifyError(err) });
}
return res.status(500).json({ message: "Server error" });
}
};
};