UNPKG

security-gateway

Version:

A plug-and-play security gateway that detects malicious traffic and redirects it to a decoy API

68 lines (54 loc) 1.96 kB
// middleware/dynamicPatching.js const { v4: uuidv4 } = require('uuid'); /** * Middleware to modify responses with honeypot data */ const dynamicPatching = (req, res, next, honeypotConfig) => { // Add random request ID header req.headers['x-request-id'] = uuidv4(); // Add timestamp header req.headers['x-request-timestamp'] = Date.now().toString(); // Only modify responses if enabled if (!honeypotConfig.modifyResponses) { return next(); } // Buffer to collect response data let responseBody = []; // Capture the original write and end methods const originalWrite = res.write; const originalEnd = res.end; // Override the write method res.write = function(chunk) { responseBody.push(chunk); return originalWrite.apply(res, arguments); }; // Override the end method res.end = function(chunk) { if (chunk) { responseBody.push(chunk); } // Try to modify JSON responses if (res.getHeader('content-type') && res.getHeader('content-type').includes('application/json')) { try { const buffer = Buffer.concat(responseBody); const text = buffer.toString('utf8'); const json = JSON.parse(text); // Add honeypot data json._trace_id = uuidv4(); json._sec_timestamp = new Date().toISOString(); // Convert back to Buffer and update content length const modifiedBody = Buffer.from(JSON.stringify(json)); res.setHeader('content-length', modifiedBody.length); // Call original end with modified body return originalEnd.call(res, modifiedBody); } catch (error) { console.error('Error modifying response:', error); } } // Fall back to original behavior return originalEnd.apply(res, arguments); }; next(); }; module.exports = { dynamicPatching };