|
| 1 | +import fetch from "node-fetch"; |
| 2 | +import type { RequestInit, Response } from "node-fetch"; |
| 3 | +import { |
| 4 | + defaultContinents, |
| 5 | + defaultCountriesCurrencies, |
| 6 | + defaultCountriesFlags, |
| 7 | + defaultCountries, |
| 8 | + defaultEuCountries |
| 9 | +} from "../config/utils"; |
| 10 | +import Cache from "./cache/cache"; |
| 11 | +import LruCache from "./cache/lruCache"; |
| 12 | +import ApiLimitError from "./errors/apiLimitError"; |
| 13 | +import { isInSubnet } from "subnet-check"; |
| 14 | +import { |
| 15 | + REQUEST_TIMEOUT_DEFAULT, |
| 16 | + CACHE_VSN, |
| 17 | + HOST_PLUS, |
| 18 | + BOGON_NETWORKS, |
| 19 | + IPinfoPlus, |
| 20 | + IPBogon |
| 21 | +} from "./common"; |
| 22 | +import VERSION from "./version"; |
| 23 | + |
| 24 | +const clientUserAgent = `IPinfoClient/nodejs/${VERSION}`; |
| 25 | +const countryFlagURL = "https://cdn.ipinfo.io/static/images/countries-flags/"; |
| 26 | + |
| 27 | +export default class IPinfoPlusWrapper { |
| 28 | + private token: string; |
| 29 | + private baseUrl: string; |
| 30 | + private countries: any; |
| 31 | + private countriesFlags: any; |
| 32 | + private countriesCurrencies: any; |
| 33 | + private continents: any; |
| 34 | + private euCountries: Array<string>; |
| 35 | + private cache: Cache; |
| 36 | + private timeout: number; |
| 37 | + |
| 38 | + /** |
| 39 | + * Creates IPinfoPlusWrapper object to communicate with the IPinfo Plus API. |
| 40 | + * |
| 41 | + * @param token Token string provided by IPinfo for registered user. |
| 42 | + * @param cache An implementation of IPCache interface. If it is not provided |
| 43 | + * then LruCache is used as default. |
| 44 | + * @param timeout Timeout in milliseconds that controls the timeout of requests. |
| 45 | + * It defaults to 5000 i.e. 5 seconds. A timeout of 0 disables the timeout feature. |
| 46 | + * @param i18nData Internationalization data for customizing countries-related information. |
| 47 | + * @param i18nData.countries Custom countries data. If not provided, default countries data will be used. |
| 48 | + * @param i18nData.countriesFlags Custom countries flags data. If not provided, default countries flags data will be used. |
| 49 | + * @param i18nData.countriesCurrencies Custom countries currencies data. If not provided, default countries currencies data will be used. |
| 50 | + * @param i18nData.continents Custom continents data. If not provided, default continents data will be used. |
| 51 | + * @param i18nData.euCountries Custom EU countries data. If not provided or an empty array, default EU countries data will be used. |
| 52 | + */ |
| 53 | + constructor( |
| 54 | + token: string, |
| 55 | + cache?: Cache, |
| 56 | + timeout?: number, |
| 57 | + i18nData?: { |
| 58 | + countries?: any; |
| 59 | + countriesFlags?: any; |
| 60 | + countriesCurrencies?: any; |
| 61 | + continents?: any; |
| 62 | + euCountries?: Array<string>; |
| 63 | + }, |
| 64 | + baseUrl?: string |
| 65 | + ) { |
| 66 | + this.token = token; |
| 67 | + this.countries = i18nData?.countries |
| 68 | + ? i18nData.countries |
| 69 | + : defaultCountries; |
| 70 | + this.countriesFlags = i18nData?.countriesFlags |
| 71 | + ? i18nData.countriesFlags |
| 72 | + : defaultCountriesFlags; |
| 73 | + this.countriesCurrencies = i18nData?.countriesCurrencies |
| 74 | + ? i18nData.countriesCurrencies |
| 75 | + : defaultCountriesCurrencies; |
| 76 | + this.continents = i18nData?.continents |
| 77 | + ? i18nData.continents |
| 78 | + : defaultContinents; |
| 79 | + this.euCountries = |
| 80 | + i18nData?.euCountries && i18nData?.euCountries.length !== 0 |
| 81 | + ? i18nData.euCountries |
| 82 | + : defaultEuCountries; |
| 83 | + this.cache = cache ? cache : new LruCache(); |
| 84 | + this.timeout = |
| 85 | + timeout === null || timeout === undefined |
| 86 | + ? REQUEST_TIMEOUT_DEFAULT |
| 87 | + : timeout; |
| 88 | + this.baseUrl = baseUrl || `https://${HOST_PLUS}`; |
| 89 | + } |
| 90 | + |
| 91 | + public static cacheKey(k: string) { |
| 92 | + return `${k}:${CACHE_VSN}`; |
| 93 | + } |
| 94 | + |
| 95 | + public async fetchApi( |
| 96 | + path: string, |
| 97 | + init: RequestInit = {} |
| 98 | + ): Promise<Response> { |
| 99 | + const headers = { |
| 100 | + Accept: "application/json", |
| 101 | + Authorization: `Bearer ${this.token}`, |
| 102 | + "Content-Type": "application/json", |
| 103 | + "User-Agent": clientUserAgent |
| 104 | + }; |
| 105 | + |
| 106 | + const request = Object.assign( |
| 107 | + { |
| 108 | + timeout: this.timeout, |
| 109 | + method: "GET", |
| 110 | + compress: false |
| 111 | + }, |
| 112 | + init, |
| 113 | + { headers: Object.assign(headers, init.headers) } |
| 114 | + ); |
| 115 | + |
| 116 | + const url = [this.baseUrl, path].join( |
| 117 | + !this.baseUrl.endsWith("/") && !path.startsWith("/") ? "/" : "" |
| 118 | + ); |
| 119 | + |
| 120 | + return fetch(url, request).then((response: Response) => { |
| 121 | + if (response.status === 429) { |
| 122 | + throw new ApiLimitError(); |
| 123 | + } |
| 124 | + |
| 125 | + if (response.status >= 400) { |
| 126 | + throw new Error( |
| 127 | + `Received an error from the IPinfo API ` + |
| 128 | + `(using authorization ${headers["Authorization"]}) ` + |
| 129 | + `${response.status} ${response.statusText} ${response.url}` |
| 130 | + ); |
| 131 | + } |
| 132 | + |
| 133 | + return response; |
| 134 | + }); |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Lookup IP information using the IP. |
| 139 | + * |
| 140 | + * @param ip IP address against which the location information is required. |
| 141 | + * @return Response containing location information. |
| 142 | + */ |
| 143 | + public async lookupIp( |
| 144 | + ip: string | undefined = undefined |
| 145 | + ): Promise<IPinfoPlus | IPBogon> { |
| 146 | + if (ip && this.isBogon(ip)) { |
| 147 | + return { |
| 148 | + ip, |
| 149 | + bogon: true |
| 150 | + }; |
| 151 | + } |
| 152 | + |
| 153 | + if (!ip) { |
| 154 | + ip = "me"; |
| 155 | + } |
| 156 | + |
| 157 | + const data = await this.cache.get(IPinfoPlusWrapper.cacheKey(ip)); |
| 158 | + |
| 159 | + if (data) { |
| 160 | + return data; |
| 161 | + } |
| 162 | + |
| 163 | + return this.fetchApi(ip).then(async (response) => { |
| 164 | + const ipinfo = (await response.json()) as IPinfoPlus; |
| 165 | + |
| 166 | + // Format geo object |
| 167 | + const countryCode = ipinfo.geo.country_code; |
| 168 | + ipinfo.geo.country_name = this.countries[countryCode]; |
| 169 | + ipinfo.geo.isEU = this.euCountries.includes(countryCode); |
| 170 | + ipinfo.geo.country_flag = this.countriesFlags[countryCode]; |
| 171 | + ipinfo.geo.country_currency = |
| 172 | + this.countriesCurrencies[countryCode]; |
| 173 | + ipinfo.geo.continent = this.continents[countryCode]; |
| 174 | + ipinfo.geo.country_flag_url = |
| 175 | + countryFlagURL + countryCode + ".svg"; |
| 176 | + |
| 177 | + this.cache.set(IPinfoPlusWrapper.cacheKey(ip), ipinfo); |
| 178 | + |
| 179 | + return ipinfo; |
| 180 | + }); |
| 181 | + } |
| 182 | + |
| 183 | + private isBogon(ip: string): boolean { |
| 184 | + if (ip != "") { |
| 185 | + for (var network of BOGON_NETWORKS) { |
| 186 | + if (isInSubnet(ip, network)) { |
| 187 | + return true; |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + return false; |
| 192 | + } |
| 193 | +} |
0 commit comments