All files / api/src middleware.js

54.86% Statements 62/113
58.02% Branches 47/81
57.14% Functions 12/21
54.54% Lines 60/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369                      9x 5x   4x 4x 4x                         14x 18x 18x 18x 9x   9x                                       9x 2x           7x 9x   9x 1x           8x   8x 8x 8x   1x         8x 6x           2x 2x                   1x 3x 1x           2x 2x   2x 1x           1x                                                                                                                                                                                                                                                                                                                           6x   6x 6x 6x     6x 6x     6x 6x     6x                   38x 13x     25x 1x     24x 20x 20x     22x 19x   20x       4x       2x       24x 21x 21x             2x                     13x                                    
/**
 * Middleware system for Coherent.js API framework
 * @fileoverview Common middleware utilities for API routes
 */
 
/**
 * Send a JSON response on either an Express response (`status().json()`) or
 * a bare node:http one, so these middleware also work on the Coherent router.
 * @private
 */
function sendJson(res, statusCode, body) {
  if (typeof res.status === 'function' && typeof res.json === 'function') {
    return res.status(statusCode).json(body);
  }
  res.writeHead(statusCode, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(body));
  return undefined;
}
 
/**
 * Creates a custom API middleware with error handling
 *
 * Errors thrown synchronously, and rejections of an async handler, are passed
 * to `next(err)`.
 *
 * @param {Function} handler - Middleware handler function
 * @returns {Function} Middleware function that catches errors
 */
export function createApiMiddleware(handler) {
  return (req, res, next) => {
    try {
      const result = handler(req, res, next);
      if (result && typeof result.then === 'function') {
        return result.catch((_error) => next(_error));
      }
      return result;
    } catch (_error) {
      // Pass errors to next middleware
      next(_error);
    }
  };
}
 
/**
 * Authentication middleware
 *
 * `verifyToken(token)` returns the user for a valid token. A falsy return
 * value (the package's own `verifyToken` answers `null`), a throw, or a
 * rejected promise all mean the token is invalid, and the request gets a 401.
 *
 * @param {Function} verifyToken - `(token) => user | null`, may be async
 * @returns {Function} Middleware function
 * @throws {TypeError} If verifyToken is not a function
 */
export function withAuth(verifyToken) {
  if (typeof verifyToken !== 'function') {
    throw new TypeError(
      '[coherent.js/api] middleware withAuth(verifyToken) expects a function (token) => user | null, ' +
        'e.g. (token) => verifyToken(token, process.env.JWT_SECRET).'
    );
  }
 
  return createApiMiddleware(async (req, res, next) => {
    const authHeader = req.headers.authorization;
 
    if (!authHeader || typeof authHeader !== 'string') {
      return sendJson(res, 401, {
        error: 'Unauthorized',
        message: 'Missing authorization header'
      });
    }
 
    const token = authHeader.replace(/^Bearer\s+/i, '');
 
    let user = null;
    try {
      user = await verifyToken(token);
    } catch {
      user = null;
    }
 
    // A verifier that answers null/undefined/false has rejected the token.
    // Calling next() with req.user = null let the request through.
    if (!user) {
      return sendJson(res, 401, {
        error: 'Unauthorized',
        message: 'Invalid token'
      });
    }
 
    req.user = user;
    next();
  });
}
 
/**
 * Authorization middleware
 * @param {Function} checkPermission - Function to check user permissions
 * @returns {Function} Middleware function
 */
export function withPermission(checkPermission) {
  return createApiMiddleware((req, res, next) => {
    if (!req.user) {
      return sendJson(res, 401, {
        error: 'Unauthorized', 
        message: 'User not authenticated' 
      });
    }
    
    try {
      const hasPermission = checkPermission(req.user, req);
      
      if (!hasPermission) {
        return sendJson(res, 403, {
          error: 'Forbidden', 
          message: 'Insufficient permissions' 
        });
      }
      
      next();
    } catch {
      return sendJson(res, 403, {
        error: 'Forbidden', 
        message: 'Permission check failed' 
      });
    }
  });
}
 
/**
 * Logging middleware
 * @param {Object} options - Logging options
 * @returns {Function} Middleware function
 */
export function withLogging(options = {}) {
  const { logger = console, level = 'info' } = options;
  
  return createApiMiddleware((req, res, next) => {
    const startTime = Date.now();
    
    // Log request
    logger[level](`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    
    // Capture response finish to log completion
    const originalSend = res.send;
    res.send = function(body) {
      const duration = Date.now() - startTime;
      logger[level](`[${new Date().toISOString()}] ${req.method} ${req.url} ${res.statusCode} - ${duration}ms`);
      return originalSend.call(this, body);
    };
    
    next();
  });
}
 
/**
 * CORS middleware
 * @param {Object} options - CORS options
 * @returns {Function} Middleware function
 */
export function withCors(options = {}) {
  const {
    origin = '*',
    methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
    allowedHeaders = ['Content-Type', 'Authorization'],
    exposedHeaders = [],
    credentials = false,
    maxAge = 86400
  } = options;
  
  return createApiMiddleware((req, res, next) => {
    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', origin);
    
    if (credentials) {
      res.setHeader('Access-Control-Allow-Credentials', 'true');
    }
    
    if (req.method === 'OPTIONS') {
      // Preflight request
      res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
      res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '));
      res.setHeader('Access-Control-Expose-Headers', exposedHeaders.join(', '));
      res.setHeader('Access-Control-Max-Age', maxAge.toString());
      res.status(204).send('');
      return;
    }
    
    next();
  });
}
 
/**
 * Rate limiting middleware
 * @param {Object} options - Rate limiting options
 * @returns {Function} Middleware function
 */
export function withRateLimit(options = {}) {
  const {
    windowMs = 60000, // 1 minute
    max = 100, // limit each IP to 100 requests per windowMs
    message = 'Too many requests, please try again later',
    statusCode = 429
  } = options;
  
  // Store request counts per IP
  const requestCounts = new Map();
  
  // Cleanup old entries periodically (do not keep event loop alive)
  const cleanupInterval = setInterval(() => {
    const now = Date.now();
    for (const [ip, record] of requestCounts.entries()) {
      if (now - record.resetTime > windowMs) {
        requestCounts.delete(ip);
      }
    }
  }, windowMs);
  if (typeof cleanupInterval.unref === 'function') {
    cleanupInterval.unref();
  }
  
  return createApiMiddleware((req, res, next) => {
    const ip = req.ip || req.connection.remoteAddress;
    const now = Date.now();
    
    if (!requestCounts.has(ip)) {
      requestCounts.set(ip, {
        count: 0,
        resetTime: now + windowMs
      });
    }
    
    const record = requestCounts.get(ip);
    
    // Reset count if window has passed
    if (now > record.resetTime) {
      record.count = 0;
      record.resetTime = now + windowMs;
    }
    
    // Increment count
    record.count++;
    
    // Check if limit exceeded
    if (record.count > max) {
      return sendJson(res, statusCode, {
        error: 'Rate limit exceeded',
        message
      });
    }
    
    // Add rate limit info to response headers
    res.setHeader('X-RateLimit-Limit', max);
    res.setHeader('X-RateLimit-Remaining', Math.max(0, max - record.count));
    res.setHeader('X-RateLimit-Reset', new Date(record.resetTime).toISOString());
    
    next();
  });
}
 
/**
 * Input sanitization middleware
 *
 * HTML-escapes every string in `req.body`, `req.query` and `req.params`.
 * Escaping is idempotent: an existing entity such as `&` or `<` is
 * left alone, so data that passes through twice (or was stored escaped and
 * submitted again) is not double-encoded into `&`. Keys that could
 * rewrite a prototype (`__proto__`, `constructor`, `prototype`) are dropped.
 *
 * @param {Object} options - Sanitization options
 * @returns {Function} Middleware function
 */
export function withSanitization(options = {}) {
  const { 
    sanitizeBody = true, 
    sanitizeQuery = true, 
    sanitizeParams = true 
  } = options;
  
  return createApiMiddleware((req, res, next) => {
    Eif (sanitizeBody && req.body) {
      req.body = sanitizeObject(req.body);
    }
    
    Eif (sanitizeQuery && req.query) {
      req.query = sanitizeObject(req.query);
    }
    
    Eif (sanitizeParams && req.params) {
      req.params = sanitizeObject(req.params);
    }
    
    next();
  });
}
 
/**
 * Sanitize an object by escaping HTML entities
 * @param {any} obj - Object to sanitize
 * @returns {any} Sanitized object
 */
function sanitizeObject(obj) {
  if (typeof obj === 'string') {
    return sanitizeString(obj);
  }
 
  if (Array.isArray(obj)) {
    return obj.map(sanitizeObject);
  }
 
  if (isPlainObject(obj)) {
    const sanitized = {};
    for (const [key, value] of Object.entries(obj)) {
      // `sanitized['__proto__'] = value` would make `value` the prototype:
      // a body of {"__proto__":{"isAdmin":true}} then read isAdmin === true.
      if (UNSAFE_KEYS.has(key)) continue;
      sanitized[key] = sanitizeObject(value);
    }
    return sanitized;
  }
 
  // Dates, Buffers and other instances are passed through untouched.
  return obj;
}
 
/** Keys that reach a prototype when assigned or deep-merged. @private */
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
 
/** @private */
function isPlainObject(value) {
  if (value === null || typeof value !== 'object') return false;
  const proto = Object.getPrototypeOf(value);
  return proto === Object.prototype || proto === null;
}
 
/**
 * An `&` that does not already start a character reference.
 * @private
 */
const BARE_AMPERSAND = /&(?!(?:[a-zA-Z][a-zA-Z0-9]{1,31}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});)/g;
 
/**
 * Sanitize a string by escaping HTML entities
 *
 * Idempotent: `sanitizeString(sanitizeString(s)) === sanitizeString(s)`.
 *
 * @param {string} str - String to sanitize
 * @returns {string} Sanitized string
 */
function sanitizeString(str) {
  return str
    .replace(BARE_AMPERSAND, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}
 
// Export middleware utilities
export default {
  createApiMiddleware,
  withAuth,
  withPermission,
  withLogging,
  withCors,
  withRateLimit,
  withSanitization
};