Skip to content

Instantly share code, notes, and snippets.

@ericychoi
Created October 29, 2025 15:47
Show Gist options
  • Select an option

  • Save ericychoi/77251313ca25a6fa8d31641644cbe7cc to your computer and use it in GitHub Desktop.

Select an option

Save ericychoi/77251313ca25a6fa8d31641644cbe7cc to your computer and use it in GitHub Desktop.
a simple webserver that can block on CIDRs
const http = require('http');
const PORT = 80;
const ALLOWED_CIDRS = [
'167.89.0.0/17',
// Add more CIDRs as needed
];
function isIpInCidr(ip, cidr) {
const [range, bits] = cidr.split('/');
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
const ipNum = ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet), 0) >>> 0;
const rangeNum = range.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet), 0) >>> 0;
return (ipNum & mask) === (rangeNum & mask);
}
function isIpInAnyCidr(ip, cidrs) {
return cidrs.some(cidr => isIpInCidr(ip, cidr));
}
const server = http.createServer((req, res) => {
let clientIp = req.socket.remoteAddress;
// Extract IPv4 from x-forwarded-for header or IPv6-mapped address
if (req.headers['x-forwarded-for']) {
clientIp = req.headers['x-forwarded-for'].split(',')[0].trim();
} else if (clientIp.includes('::ffff:')) {
clientIp = clientIp.split('::ffff:')[1];
} else if (clientIp === '::1') {
clientIp = '127.0.0.1';
}
if (req.method === 'POST' && req.url === '/webhook') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
console.log('Headers:', req.headers);
console.log('Body:', body);
try {
const jsonData = JSON.parse(body);
console.log('Parsed JSON:', jsonData);
} catch (e) {
console.log('Body is not JSON');
}
if (!isIpInAnyCidr(clientIp, ALLOWED_CIDRS)) {
console.log(`Blocked request from ${clientIp} - not in allowed CIDR ${ALLOWED_CIDRS}`);
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
console.log('Accepted request from', clientIp);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'success', message: 'Webhook received' }));
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(PORT, () => {
console.log(`Webhook server listening on port ${PORT}`);
console.log(`Send POST requests to http://localhost:${PORT}/webhook`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment