From 92705815ed9157fb676e31e6879bd3b0fc05d8ff Mon Sep 17 00:00:00 2001 From: Mike Cao Date: Sun, 25 Apr 2021 23:57:49 -0700 Subject: [PATCH] Support CIDR notation in IGNORE_IP, closes #544. --- package.json | 1 + pages/api/collect.js | 16 +++++++++++++++- yarn.lock | 5 +++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 626f829f..f05a734a 100644 --- a/package.json +++ b/package.json @@ -70,6 +70,7 @@ "dotenv": "^8.2.0", "formik": "^2.2.6", "immer": "^8.0.1", + "ipaddr.js": "^2.0.0", "is-localhost-ip": "^1.4.0", "isbot": "^3.0.26", "jose": "2.0.5", diff --git a/pages/api/collect.js b/pages/api/collect.js index 98ab54e3..f7ce44b6 100644 --- a/pages/api/collect.js +++ b/pages/api/collect.js @@ -1,4 +1,5 @@ import isbot from 'isbot'; +import ipaddr from 'ipaddr.js'; import { savePageView, saveEvent } from 'lib/queries'; import { useCors, useSession } from 'lib/middleware'; import { getIpAddress } from 'lib/request'; @@ -15,8 +16,21 @@ export default async (req, res) => { if (process.env.IGNORE_IP) { const ips = process.env.IGNORE_IP.split(',').map(n => n.trim()); const ip = getIpAddress(req); + const blocked = ips.find(i => { + if (i === ip) return true; - if (ips.includes(ip)) { + // CIDR notation + if (i.indexOf('/') > 0) { + const addr = ipaddr.parse(ip); + const range = ipaddr.parseCIDR(i); + + if (addr.match(range)) return true; + } + + return false; + }); + + if (blocked) { return ok(res); } } diff --git a/yarn.lock b/yarn.lock index 91422c3e..23af3654 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4301,6 +4301,11 @@ intl-messageformat@9.6.8: fast-memoize "^2.5.2" tslib "^2.1.0" +ipaddr.js@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-2.0.0.tgz#77ccccc8063ae71ab65c55f21b090698e763fc6e" + integrity sha512-S54H9mIj0rbxRIyrDMEuuER86LdlgUg9FSeZ8duQb6CUG2iRrA36MYVQBSprTF/ZeAwvyQ5mDGuNvIPM0BIl3w== + is-alphabetical@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-1.0.4.tgz#9e7d6b94916be22153745d184c298cbf986a686d"