All files / api/src security.js

84.8% Statements 106/125
77.65% Branches 73/94
100% Functions 18/18
85.24% Lines 104/122

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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                            16x                           6x 6x                   22x                                     40x 32x   8x                             10x   10x           10x 10x   10x 8x                 8x           8x 8x 8x 8x   8x                     18x   18x 18x     18x 2x     17x 3x       14x 14x       14x     14x 14x   14x 8x       6x     6x 6x       6x                                         13x   13x 5x 5x     13x 1x     1x 2x 2x 2x       2x 1x 1x   1x 1x       12x   12x 5x 5x   5x 4x 4x     1x 1x                   3x   3x 2x 1x 1x 1x     1x 1x 1x 1x                       13x 13x 13x                           22x 22x 22x   22x 17x                                 4x 4x 4x                         10x 10x 10x 8x 8x                         8x     3x         5x                 5x 1x   1x 1x   1x         1x 1x     1x       1x       1x         1x 1x 1x 1x                                  
/**
 * Security Middleware for Coherent.js API Framework
 * @fileoverview Provides authentication, authorization, and security utilities
 */
 
import { createHmac, randomBytes, pbkdf2Sync, timingSafeEqual } from 'crypto';
import { Buffer } from 'buffer';
 
/**
 * Base64 URL encode
 * @param {string} str - String to encode
 * @returns {string} Base64 URL encoded string
 */
function base64UrlEncode(str) {
  return Buffer.from(str)
    .toString('base64')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}
 
/**
 * Base64 URL decode
 * @param {string} str - Base64 URL encoded string
 * @returns {string} Decoded string
 */
function base64UrlDecode(str) {
  // Add padding if needed
  str += '='.repeat((4 - str.length % 4) % 4);
  return Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString();
}
 
/**
 * Create HMAC signature for JWT
 * @param {string} data - Data to sign
 * @param {string} secret - Secret key
 * @returns {string} HMAC signature
 */
function createSignature(data, secret) {
  return createHmac('sha256', secret).update(data).digest('base64')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}
 
/**
 * Refuse to sign or verify without a caller-supplied secret.
 *
 * There used to be a built-in default, 'your-secret-key'. It was public, so
 * anyone could mint a token -- `{ role: 'admin' }` included -- that every
 * `withAuth()` without a configured secret accepted. A missing secret is a
 * deployment mistake, so it fails loudly instead of quietly falling back.
 *
 * @private
 * @param {unknown} secret - Secret supplied by the caller
 * @param {string} usage - How the caller should pass it, for the message
 */
function requireSecret(secret, usage) {
  if (typeof secret === 'string' ? secret.length > 0 : Buffer.isBuffer(secret) && secret.length > 0) {
    return;
  }
  throw new TypeError(
    `[coherent.js/api] ${usage}: a JWT secret is required (a non-empty string or Buffer), ` +
      'for example process.env.JWT_SECRET. There is no default secret.'
  );
}
 
/**
 * Generate JWT token
 * @param {Object} payload - Token payload
 * @param {string} expiresIn - Expiration time (e.g., '1h', '30m', '7d')
 * @param {string} secret - Secret key (required)
 * @returns {string} JWT token
 * @throws {TypeError} If no secret is given
 */
export function generateJWT(payload, expiresIn = '1h', secret) {
  requireSecret(secret, "generateJWT(payload, expiresIn, secret) was called without a secret");
 
  const header = {
    alg: 'HS256',
    typ: 'JWT'
  };
 
  // Calculate expiration time
  const now = Math.floor(Date.now() / 1000);
  let exp = now;
  
  if (expiresIn.endsWith('h')) {
    exp += parseInt(expiresIn) * 3600;
  } else Eif (expiresIn.endsWith('m')) {
    exp += parseInt(expiresIn) * 60;
  } else if (expiresIn.endsWith('d')) {
    exp += parseInt(expiresIn) * 86400;
  } else {
    exp += 3600; // Default 1 hour
  }
 
  const tokenPayload = {
    ...payload,
    iat: now,
    exp: exp
  };
 
  const encodedHeader = base64UrlEncode(JSON.stringify(header));
  const encodedPayload = base64UrlEncode(JSON.stringify(tokenPayload));
  const data = `${encodedHeader}.${encodedPayload}`;
  const signature = createSignature(data, secret);
 
  return `${data}.${signature}`;
}
 
/**
 * JWT token verification
 * @param {string} token - Bearer token or JWT token
 * @param {string} secret - Secret key (required)
 * @returns {Object|null} Decoded payload or null if invalid
 * @throws {TypeError} If no secret is given
 */
export function verifyToken(token, secret) {
  requireSecret(secret, 'verifyToken(token, secret) was called without a secret');
 
  try {
    let jwtToken = token;
    
    // Handle Bearer token format
    if (token && token.startsWith('Bearer ')) {
      jwtToken = token.slice(7);
    }
    
    if (!jwtToken) {
      return null;
    }
 
    // Split JWT into parts
    const parts = jwtToken.split('.');
    Iif (parts.length !== 3) {
      return null;
    }
 
    const [encodedHeader, encodedPayload, signature] = parts;
 
    // Verify signature
    const data = `${encodedHeader}.${encodedPayload}`;
    const expectedSignature = createSignature(data, secret);
    
    if (!safeEqual(signature, expectedSignature)) {
      return null;
    }
 
    // Decode and parse payload
    const payload = JSON.parse(base64UrlDecode(encodedPayload));
 
    // Check expiration
    const now = Math.floor(Date.now() / 1000);
    Iif (payload.exp && payload.exp < now) {
      return null; // Token expired
    }
 
    return payload;
  } catch {
    return null;
  }
}
 
/**
 * Authentication middleware
 *
 * Verifies the `Authorization: Bearer <jwt>` header with `options.secret`, or
 * hands the request to `options.verify` for any other scheme. One of the two
 * is required: there is no default secret.
 *
 * @param {Object} options - Auth options
 * @param {string|Buffer} [options.secret] - HS256 secret the tokens were signed with
 * @param {Function} [options.verify] - `(req) => user | null`, may be async; replaces JWT verification
 * @param {boolean} [options.required=true] - Answer 401 when no valid user is found
 * @returns {Function} Middleware function
 * @throws {TypeError} If neither `secret` nor `verify` is given
 */
export function withAuth(options = {}) {
  const { secret, verify, required = true } = options ?? {};
 
  const reject = (res) => {
    res.writeHead(401, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Unauthorized' }));
  };
 
  if (verify !== undefined) {
    Iif (typeof verify !== 'function') {
      throw new TypeError('[coherent.js/api] withAuth({ verify }) expects verify to be a function (req) => user.');
    }
    return async (req, res) => {
      let user = null;
      try {
        user = (await verify(req)) || null;
      } catch {
        user = null;
      }
      if (required && !user) {
        reject(res);
        return;
      }
      req.user = user;
      return null; // Continue to next middleware
    };
  }
 
  requireSecret(secret, 'withAuth({ secret }) was created without a secret');
 
  return (req, res) => {
    const authHeader = req.headers.authorization;
    const user = verifyToken(authHeader, secret);
 
    if (required && !user) {
      reject(res);
      return;
    }
 
    req.user = user;
    return null; // Continue to next middleware
  };
}
 
/**
 * Authorization middleware
 * @param {string|Array} roles - Required roles
 * @returns {Function} Middleware function
 */
export function withRole(roles) {
  const requiredRoles = Array.isArray(roles) ? roles : [roles];
  
  return (req, res) => {
    if (!req.user) {
      res.writeHead(401, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'Unauthorized' }));
      return;
    }
    
    Eif (!requiredRoles.includes(req.user.role)) {
      res.writeHead(403, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'Forbidden' }));
      return;
    }
    
    return null; // Continue to next middleware
  };
}
 
/**
 * PBKDF2 parameters of the `"<salt>:<hash>"` format. Changing them would
 * make every stored hash fail to verify, so they stay as they are.
 * @private
 */
const PBKDF2_ITERATIONS = 10000;
const PBKDF2_KEY_LENGTH = 64;
const PBKDF2_DIGEST = 'sha512';
 
/**
 * Compare two strings in time that depends only on their length.
 *
 * `===` stops at the first differing character, which lets an attacker who
 * can time responses recover a valid HMAC signature byte by byte.
 *
 * @private
 * @param {string} a - Received value
 * @param {string} b - Expected value
 * @returns {boolean} True when equal
 */
function safeEqual(a, b) {
  Iif (typeof a !== 'string' || typeof b !== 'string') return false;
  const left = Buffer.from(a);
  const right = Buffer.from(b);
  // timingSafeEqual needs equal lengths; the expected length is public.
  if (left.length !== right.length) return false;
  return timingSafeEqual(left, right);
}
 
/**
 * Password hashing utility
 *
 * PBKDF2-HMAC-SHA512, 10,000 iterations, 16-byte random salt, stored as
 * `"<salt hex>:<hash hex>"`. It is synchronous and blocks the event loop for
 * the duration of the derivation (a few milliseconds); that iteration count
 * is well below current OWASP guidance (210,000 for PBKDF2-SHA512), so for
 * new systems prefer a dedicated password hashing library (argon2, bcrypt,
 * or `crypto.scrypt`) with its async API.
 *
 * @param {string} password - Plain text password
 * @returns {string} Hashed password
 */
export function hashPassword(password) {
  const salt = randomBytes(16).toString('hex');
  const hash = pbkdf2Sync(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEY_LENGTH, PBKDF2_DIGEST).toString('hex');
  return `${salt}:${hash}`;
}
 
/**
 * Password verification utility
 *
 * Compares in constant time. Synchronous, like `hashPassword()`.
 *
 * @param {string} password - Plain text password
 * @param {string} hashedPassword - Hashed password from database
 * @returns {boolean} True if password matches
 */
export function verifyPassword(password, hashedPassword) {
  try {
    const [salt, hash] = hashedPassword.split(':');
    if (!salt || !hash) return false;
    const verifyHash = pbkdf2Sync(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEY_LENGTH, PBKDF2_DIGEST).toString('hex');
    return safeEqual(hash, verifyHash);
  } catch {
    return false;
  }
}
 
/**
 * Generate secure random token (for non-JWT use cases)
 * @param {number} length - Number of random bytes; the hex string is twice as long
 * @returns {string} Random token
 * @throws {TypeError} If length is not a positive integer (e.g. a JWT payload)
 */
export function generateToken(length = 32) {
  if (!Number.isInteger(length) || length <= 0) {
    // The type definitions used to describe generateToken(payload, { secret })
    // as a JWT generator; point callers who followed them to the real one.
    throw new TypeError(
      '[coherent.js/api] generateToken(length) returns random hex and takes a byte count. ' +
        'To sign a JWT use generateJWT(payload, expiresIn, secret).'
    );
  }
  return randomBytes(length).toString('hex');
}
 
/**
 * Input validation middleware
 * @param {Object} rules - Validation rules
 * @returns {Function} Middleware function
 */
export function withInputValidation(rules) {
  return (req, res) => {
    const errors = [];
    
    for (const [field, rule] of Object.entries(rules)) {
      const value = req.body[field];
      
      Iif (rule.required && (value === undefined || value === null || value === '')) {
        errors.push(`${field} is required`);
        continue;
      }
      
      Eif (value !== undefined && rule.type && typeof value !== rule.type) {
        errors.push(`${field} must be of type ${rule.type}`);
      }
      
      Iif (value && rule.minLength && value.length < rule.minLength) {
        errors.push(`${field} must be at least ${rule.minLength} characters`);
      }
      
      Iif (value && rule.maxLength && value.length > rule.maxLength) {
        errors.push(`${field} must be at most ${rule.maxLength} characters`);
      }
      
      Iif (value && rule.pattern && !rule.pattern.test(value)) {
        errors.push(`${field} format is invalid`);
      }
    }
    
    Eif (errors.length > 0) {
      res.writeHead(400, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'Validation failed', details: errors }));
      return;
    }
    
    return null; // Continue to next middleware
  };
}
 
export default {
  verifyToken,
  generateJWT,
  withAuth,
  withRole,
  hashPassword,
  verifyPassword,
  generateToken,
  withInputValidation
};