From bc06f3e3e0ec399d9ffcb4d802faf914a8a0e482 Mon Sep 17 00:00:00 2001 From: Wolfsblvt Date: Wed, 12 Nov 2025 20:13:58 +0100 Subject: [PATCH] Refactor: make whitelist validation a bit more robust (#4757) * refactor: extract IP whitelist validation into helper function - Added isIPInWhitelist helper with error handling for individual whitelist entry checks - Replaced inline whitelist matching logic with reusable function calls - Added JSDoc type annotations and error logging for failed IP matching attempts * refactor: simplify whitelist validation with upfront filtering - Moved IP validation to startup time instead of per-request checking - Extracted validateWhitelist function to filter invalid entries once at initialization - Simplified isIPInWhitelist by removing redundant error handling after validation * fix: correct IP whitelist matching to use parsed CIDR notation --- src/middleware/whitelist.js | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/middleware/whitelist.js b/src/middleware/whitelist.js index 206eab8bb..9e3c149ca 100644 --- a/src/middleware/whitelist.js +++ b/src/middleware/whitelist.js @@ -24,6 +24,29 @@ if (fs.existsSync(whitelistPath)) { } } +/** + * Validates and filters the whitelist, removing any invalid entries. + * @param {string[]} entries - The whitelist entries to validate + * @returns {string[]} The filtered list of valid whitelist entries + */ +function validateWhitelist(entries) { + const validEntries = []; + + for (const entry of entries) { + try { + // This will throw if the entry is not a valid IP or CIDR + ipMatching.getMatch(entry); + validEntries.push(entry); + } catch (e) { + console.warn(`Whitelist ${color.red('Warning')}: Ignoring invalid entry ${color.yellow(entry)} - ${e.message}`); + } + } + + return validEntries; +} + +whitelist = validateWhitelist(whitelist); + /** * Get the client IP address from the request headers. * @param {import('express').Request} req Express request object @@ -91,9 +114,19 @@ export default async function getWhitelistMiddleware() { const forwardedIp = getForwardedIp(req); const userAgent = req.headers['user-agent']; + /** + * Checks if an IP address matches any entry in the whitelist. + * @param {string[]} whitelist - The list of whitelisted IPs/CIDRs + * @param {string} ip - The IP address to check + * @returns {boolean} True if the IP matches any whitelist entry + */ + function isIPInWhitelist(whitelist, ip) { + return whitelist.some(x => ipMatching.matches(ip, ipMatching.getMatch(x))); + } + //clientIp = req.connection.remoteAddress.split(':').pop(); - if (!whitelist.some(x => ipMatching.matches(clientIp, ipMatching.getMatch(x))) - || forwardedIp && !whitelist.some(x => ipMatching.matches(forwardedIp, ipMatching.getMatch(x))) + if (!isIPInWhitelist(whitelist, clientIp) + || forwardedIp && !isIPInWhitelist(whitelist, forwardedIp) ) { // Log the connection attempt with real IP address const ipDetails = forwardedIp