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 | /** * Middleware system for Coherent.js API framework * @fileoverview Common middleware utilities for API routes */ /** * Creates a custom API middleware with error handling * @param {Function} handler - Middleware handler function * @returns {Function} Middleware function that catches errors */ export function createApiMiddleware(handler) { return (req, res, next) => { try { return handler(req, res, next); } catch (error) { // Pass errors to next middleware next(error); } }; } /** * Authentication middleware * @param {Function} verifyToken - Function to verify authentication token * @returns {Function} Middleware function */ export function withAuth(verifyToken) { return createApiMiddleware((req, res, next) => { const authHeader = req.headers.authorization; if (!authHeader) { return res.status(401).json({ error: 'Unauthorized', message: 'Missing authorization header' }); } const token = authHeader.replace('Bearer ', ''); try { const user = verifyToken(token); req.user = user; next(); } catch { return res.status(401).json({ error: 'Unauthorized', message: 'Invalid token' }); } }); } /** * 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 res.status(401).json({ error: 'Unauthorized', message: 'User not authenticated' }); } try { const hasPermission = checkPermission(req.user, req); if (!hasPermission) { return res.status(403).json({ error: 'Forbidden', message: 'Insufficient permissions' }); } next(); } catch { return res.status(403).json({ 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 res.status(statusCode).json({ 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 * @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) => { if (sanitizeBody && req.body) { req.body = sanitizeObject(req.body); } if (sanitizeQuery && req.query) { req.query = sanitizeObject(req.query); } if (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 (typeof obj === 'object' && obj !== null) { const sanitized = {}; for (const [key, value] of Object.entries(obj)) { sanitized[key] = sanitizeObject(value); } return sanitized; } return obj; } /** * Sanitize a string by escaping HTML entities * @param {string} str - String to sanitize * @returns {string} Sanitized string */ function sanitizeString(str) { return str .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // Export middleware utilities export default { createApiMiddleware, withAuth, withPermission, withLogging, withCors, withRateLimit, withSanitization }; |