Skip to content

Commit

Permalink
CIDRs support
Browse files Browse the repository at this point in the history
  • Loading branch information
gugu committed Dec 23, 2020
1 parent e0c3243 commit 8da512c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
16 changes: 9 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
'use strict';

const ip6addr = require('ip6addr');
// Simple proxy trusting middleware
// TODO: make proxylist somewhat compatible with https://expressjs.com/ru/guide/behind-proxies.html


// convert comma-separated ip list to array
function listToArray(str) {
return str.split(',').map(x => x.trim());
}

// check if addr is enlisted
// TODO: add check against cidr ranges
function isAddrInList (addr, trustlist) {
return trustlist.some(item => {
return (addr == item) || (addr == '::ffff:' + item);
function isAddrInList (addr, cidrs) {
return cidrs.some(item => {
return item.contains(addr);
});
}

Expand All @@ -25,22 +26,23 @@ function koaTrustProxy (trustlist = ['127.0.0.1', '::1'], trustheader = 'x-forwa
if (typeof trustlist === 'string') {
trustlist = listToArray(trustlist);
}
const cidrs = trustlist.map((ip) => ip.includes('/') ? ip6addr.createCIDR(ip): ip6addr.createAddrRange(ip, ip));

// return middleware async function
return async function (ctx, next) {

let ip = ctx.socket.remoteAddress;

// check if our addr belongs to proxy or there is no ip at all (in case of unix socket)
if (!ctx.socket.remoteAddress || isAddrInList(ctx.socket.remoteAddress, trustlist)) {
if (!ctx.socket.remoteAddress || isAddrInList(ctx.socket.remoteAddress, cidrs)) {
// check for trustheader presence
let header = ctx.request.headers[trustheader];
if (header) {
let ips = listToArray(header);
// find first rightmost untrusted address, or leftmost if all trusted
for (let i = ips.length-1; i >= 0; i--) {
ip = ips[i];
if (!isAddrInList(ip, trustlist)) break;
if (!isAddrInList(ip, cidrs)) break;
}
}
}
Expand All @@ -52,4 +54,4 @@ function koaTrustProxy (trustlist = ['127.0.0.1', '::1'], trustheader = 'x-forwa
}
}

module.exports = koaTrustProxy;
module.exports = koaTrustProxy;
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,8 @@
"mocha": "^6.1.4",
"nyc": "^14.1.0",
"supertest": "^4.0.2"
},
"dependencies": {
"ip6addr": "^0.2.3"
}
}

0 comments on commit 8da512c

Please sign in to comment.