Spaces:
Configuration error
Configuration error
File size: 4,696 Bytes
339aa1f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | import path from 'path';
import { getClientIp } from 'request-ip';
import { browserName, detectOS } from 'detect-browser';
import isLocalhost from 'is-localhost-ip';
import ipaddr from 'ipaddr.js';
import maxmind from 'maxmind';
import { safeDecodeURIComponent } from 'next-basics';
import {
DESKTOP_OS,
MOBILE_OS,
DESKTOP_SCREEN_WIDTH,
LAPTOP_SCREEN_WIDTH,
MOBILE_SCREEN_WIDTH,
} from './constants';
import { NextApiRequestCollect } from 'pages/api/send';
let lookup;
export function getIpAddress(req: NextApiRequestCollect) {
const customHeader = String(process.env.CLIENT_IP_HEADER).toLowerCase();
// Custom header
if (customHeader !== 'undefined' && req.headers[customHeader]) {
return req.headers[customHeader];
}
// Cloudflare
else if (req.headers['cf-connecting-ip']) {
return req.headers['cf-connecting-ip'];
}
return getClientIp(req);
}
export function getDevice(screen: string, os: string) {
if (!screen) return;
const [width] = screen.split('x');
if (DESKTOP_OS.includes(os)) {
if (os === 'Chrome OS' || +width < DESKTOP_SCREEN_WIDTH) {
return 'laptop';
}
return 'desktop';
} else if (MOBILE_OS.includes(os)) {
if (os === 'Amazon OS' || +width > MOBILE_SCREEN_WIDTH) {
return 'tablet';
}
return 'mobile';
}
if (+width >= DESKTOP_SCREEN_WIDTH) {
return 'desktop';
} else if (+width >= LAPTOP_SCREEN_WIDTH) {
return 'laptop';
} else if (+width >= MOBILE_SCREEN_WIDTH) {
return 'tablet';
} else {
return 'mobile';
}
}
function getRegionCode(country: string, region: string) {
if (!country || !region) {
return undefined;
}
return region.includes('-') ? region : `${country}-${region}`;
}
function safeDecodeCfHeader(s: string | undefined | null): string | undefined | null {
if (s === undefined || s === null) {
return s;
}
return Buffer.from(s, 'latin1').toString('utf-8');
}
export async function getLocation(ip: string, req: NextApiRequestCollect) {
// Ignore local ips
if (await isLocalhost(ip)) {
return;
}
// Cloudflare headers
if (req.headers['cf-ipcountry']) {
const country = safeDecodeCfHeader(req.headers['cf-ipcountry']);
const subdivision1 = safeDecodeCfHeader(req.headers['cf-region-code']);
const city = safeDecodeCfHeader(req.headers['cf-ipcity']);
return {
country,
subdivision1: getRegionCode(country, subdivision1),
city,
};
}
// Vercel headers
if (req.headers['x-vercel-ip-country']) {
const country = safeDecodeURIComponent(req.headers['x-vercel-ip-country']);
const subdivision1 = safeDecodeURIComponent(req.headers['x-vercel-ip-country-region']);
const city = safeDecodeURIComponent(req.headers['x-vercel-ip-city']);
return {
country,
subdivision1: getRegionCode(country, subdivision1),
city,
};
}
// Database lookup
if (!lookup) {
const dir = path.join(process.cwd(), 'geo');
lookup = await maxmind.open(path.resolve(dir, 'GeoLite2-City.mmdb'));
}
const result = lookup.get(ip);
if (result) {
const country = result.country?.iso_code ?? result?.registered_country?.iso_code;
const subdivision1 = result.subdivisions?.[0]?.iso_code;
const subdivision2 = result.subdivisions?.[1]?.names?.en;
const city = result.city?.names?.en;
return {
country,
subdivision1: getRegionCode(country, subdivision1),
subdivision2,
city,
};
}
}
export async function getClientInfo(req: NextApiRequestCollect) {
const userAgent = req.headers['user-agent'];
const ip = req.body?.payload?.ip || getIpAddress(req);
const location = await getLocation(ip, req);
const country = location?.country;
const subdivision1 = location?.subdivision1;
const subdivision2 = location?.subdivision2;
const city = location?.city;
const browser = browserName(userAgent);
const os = detectOS(userAgent) as string;
const device = getDevice(req.body?.payload?.screen, os);
return { userAgent, browser, os, ip, country, subdivision1, subdivision2, city, device };
}
export function hasBlockedIp(req: NextApiRequestCollect) {
const ignoreIps = process.env.IGNORE_IP;
if (ignoreIps) {
const ips = [];
if (ignoreIps) {
ips.push(...ignoreIps.split(',').map(n => n.trim()));
}
const clientIp = getIpAddress(req);
return ips.find(ip => {
if (ip === clientIp) return true;
// CIDR notation
if (ip.indexOf('/') > 0) {
const addr = ipaddr.parse(clientIp);
const range = ipaddr.parseCIDR(ip);
if (addr.kind() === range[0].kind() && addr.match(range)) return true;
}
});
}
return false;
}
|