Removed hostname lookup.

This commit is contained in:
Mike Cao 2023-11-28 11:03:55 -08:00
parent 02c9e0115e
commit e074394b13

View File

@ -1,4 +1,3 @@
import { Resolver } from 'dns/promises';
import ipaddr from 'ipaddr.js'; import ipaddr from 'ipaddr.js';
import isbot from 'isbot'; import isbot from 'isbot';
import { COLLECTION_TYPE, HOSTNAME_REGEX } from 'lib/constants'; import { COLLECTION_TYPE, HOSTNAME_REGEX } from 'lib/constants';
@ -78,14 +77,14 @@ export default async (req: NextApiRequestCollect, res: NextApiResponse) => {
return ok(res); return ok(res);
} }
const { type, payload } = req.body;
await useValidate(schema, req, res); await useValidate(schema, req, res);
if (await hasBlockedIp(req)) { if (hasBlockedIp(req)) {
return forbidden(res); return forbidden(res);
} }
const { type, payload } = req.body;
const { url, referrer, name: eventName, data: eventData, title: pageTitle } = payload; const { url, referrer, name: eventName, data: eventData, title: pageTitle } = payload;
await useSession(req, res); await useSession(req, res);
@ -143,28 +142,16 @@ export default async (req: NextApiRequestCollect, res: NextApiResponse) => {
return methodNotAllowed(res); return methodNotAllowed(res);
}; };
async function hasBlockedIp(req: NextApiRequestCollect) { function hasBlockedIp(req: NextApiRequestCollect) {
const ignoreIps = process.env.IGNORE_IP; const ignoreIps = process.env.IGNORE_IP;
const ignoreHostnames = process.env.IGNORE_HOSTNAME;
if (ignoreIps || ignoreHostnames) { if (ignoreIps) {
const ips = []; const ips = [];
if (ignoreIps) { if (ignoreIps) {
ips.push(...ignoreIps.split(',').map(n => n.trim())); ips.push(...ignoreIps.split(',').map(n => n.trim()));
} }
if (ignoreHostnames) {
const resolver = new Resolver();
const promises = ignoreHostnames
.split(',')
.map(n => resolver.resolve4(n.trim()).catch(() => {}));
await Promise.all(promises).then(resolvedIps => {
ips.push(...resolvedIps.filter(n => n).flatMap(n => n as string[]));
});
}
const clientIp = getIpAddress(req); const clientIp = getIpAddress(req);
return ips.find(ip => { return ips.find(ip => {
@ -177,8 +164,8 @@ async function hasBlockedIp(req: NextApiRequestCollect) {
if (addr.kind() === range[0].kind() && addr.match(range)) return true; if (addr.kind() === range[0].kind() && addr.match(range)) return true;
} }
return false;
}); });
} }
return false;
} }