@proxyherd/fingerprint 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/fingerprint.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ set `TRUST_PROXY=true` so the client address is read from `X-Forwarded-For`.
|
|
|
28
28
|
|---|---|
|
|
29
29
|
| `GET /api/json` | `{ ip, useragent, asnName, asnNetwork, continentCode, continentName, countryCode, countryName, cityName, timezone, latitude, longitude }`; every field but `ip` may be `null` |
|
|
30
30
|
| `GET /api/text` | the client IP address as plain text |
|
|
31
|
-
| `GET /health` | provider, database state
|
|
31
|
+
| `GET /health` | provider, database state, last refresh and whether a rate limit is in place (`rateLimit`) |
|
|
32
32
|
| `GET /` | a short description and the GeoIP attribution |
|
|
33
33
|
|
|
34
34
|
## Configuration
|
|
@@ -41,7 +41,8 @@ set `TRUST_PROXY=true` so the client address is read from `X-Forwarded-For`.
|
|
|
41
41
|
| `GEOIP_AUTO_DOWNLOAD` | `true` | Download the databases at start and refresh them |
|
|
42
42
|
| `GEOIP_REFRESH_HOURS` | `168` | Refresh interval |
|
|
43
43
|
| `MAXMIND_LICENSE_KEY` | | Required for `GEOIP_PROVIDER=maxmind` |
|
|
44
|
-
| `TRUST_PROXY` | `false` |
|
|
44
|
+
| `TRUST_PROXY` | `false` | `true` behind one reverse proxy you control, or the number of them. The client address is then read from `X-Forwarded-For`, counted from the right, so an address the caller put in the header itself is never used |
|
|
45
|
+
| `RATE_LIMIT_PER_MINUTE` | `0` (no limit) | Requests per minute accepted from one address (one /64 network for IPv6) on `/api/json` and `/api/text`. Over it the service answers `429` with an explanation |
|
|
45
46
|
|
|
46
47
|
You can also drop your own `city.mmdb` and `asn.mmdb` into `GEOIP_DIR` and
|
|
47
48
|
set `GEOIP_AUTO_DOWNLOAD=false`.
|
package/fingerprint.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
(()=>{"use strict";let e={};require("reflect-metadata");const t=require("@nestjs/common"),n=require("@nestjs/core");var r;!function(e){e.Dbip="dbip",e.Maxmind="maxmind",e.None="none"}(r||(r={}));const o="FINGERPRINT_SERVICE_CONFIG";function i(e,t){return void 0===e||e.length<=0?t:["1","true","yes","on"].includes(e.toLowerCase())}function s(){const e=function(e){switch((e??"dbip").toLowerCase()){case"maxmind":return r.Maxmind;case"none":return r.None;default:return r.Dbip}}(process.env.GEOIP_PROVIDER),t=process.env.MAXMIND_LICENSE_KEY;if(e===r.Maxmind&&!t)throw new Error("GEOIP_PROVIDER=maxmind requires MAXMIND_LICENSE_KEY (free at https://www.maxmind.com/en/geolite2/signup)");return{port:parseInt(process.env.FINGERPRINT_PORT??"3000",10),provider:e,dataDir:process.env.GEOIP_DIR??"geoip",autoDownload:i(process.env.GEOIP_AUTO_DOWNLOAD,!0),refreshIntervalMs:60*parseInt(process.env.GEOIP_REFRESH_HOURS??"168",10)*60*1e3,maxmindLicenseKey:t,trustProxy:i(process.env.TRUST_PROXY,!1),downloadTimeoutMs:parseInt(process.env.GEOIP_DOWNLOAD_TIMEOUT??"600000",10)}}const a=require("fs"),c=require("maxmind"),l=require("child_process"),d=require("http"),u=require("https"),p=require("path"),f=require("stream/promises"),g=require("zlib");function h(e,t){return new Promise((n,r)=>{const o=new URL(e),i=("https:"===o.protocol?u.request:d.request)(o,{method:"GET",headers:{"User-Agent":"ProxyHerd-fingerprint"},timeout:t},e=>{n(e)});i.on("timeout",()=>{i.destroy(new Error(`Timeout while downloading ${e}`))}),i.on("error",r),i.end()})}async function m(e,t,n){await a.promises.mkdir((0,p.dirname)(t),{recursive:!0});const r=`${t}.download`,o=await async function(e,t){let n=e;for(let r=0;r<=5;r++){const e=await h(n,t),r=e.statusCode??0;if(!(r>=300&&r<400&&e.headers.location)){if(200!==r)throw e.resume(),new Error(`Download of ${n} failed with status ${r}`);return e}e.resume(),n=new URL(e.headers.location,n).toString()}throw new Error(`Too many redirects while downloading ${e}`)}(e,n.timeoutMs);try{n.gunzip?await(0,f.pipeline)(o,(0,g.createGunzip)(),(0,a.createWriteStream)(r)):await(0,f.pipeline)(o,(0,a.createWriteStream)(r)),await a.promises.rename(r,t)}catch(i){throw await a.promises.rm(r,{force:!0}),i}}async function y(e,t){const n=await a.promises.readdir(e,{withFileTypes:!0});for(const r of n){const n=(0,p.join)(e,r.name);if(r.isDirectory()){const e=await y(n,t);if(e)return e}else if(r.name===t)return n}return null}async function w(e,t,n){const r=(0,p.dirname)(n),o=(0,p.join)(r,`.extract-${process.pid}`);await a.promises.mkdir(o,{recursive:!0});try{await new Promise((n,r)=>{(0,l.execFile)("tar",["-xzf",e,"-C",o,"--wildcards",t],(e,t,o)=>{e?r(new Error(`tar failed: ${o.length>0?o:e.message}`)):n()})});const r=await y(o,n.split("/").pop());if(!r)throw new Error(`${t} not found in ${e}`);await a.promises.rename(r,n)}finally{await a.promises.rm(o,{recursive:!0,force:!0})}}const v=require("net"),I="::ffff:";function b(e){const t=e.toLowerCase();if(t.startsWith(I)){const e=t.substring(7);if((0,v.isIPv4)(e))return e}return e}function R(e,t){const n=b(e);if((0,v.isIPv4)(n)){if(t<0||t>32)return null;const e=n.split(".").map(e=>parseInt(e,10)),r=((e[0]<<24>>>0)+(e[1]<<16)+(e[2]<<8)+e[3]&(0===t?0:4294967295<<32-t>>>0))>>>0;return`${[r>>>24,r>>>16&255,r>>>8&255,255&r].join(".")}/${t}`}if((0,v.isIPv6)(n)){if(t<0||t>128)return null;const e=function(e){const[t,n]=e.split("::"),r=t.length>0?t.split(":"):[],o=n&&n.length>0?n.split(":"):[],i=8-r.length-o.length,s=[...r,...new Array(Math.max(i,0)).fill("0"),...o];let a=BigInt(0);for(const c of s)a=(a<<BigInt(16))+BigInt(parseInt(c,16));return a}(n.split("%")[0]),r=(BigInt(1)<<BigInt(128))-BigInt(1);return`${function(e){const t=[];for(let s=7;s>=0;s--)t.push(Number(e>>BigInt(16*s)&BigInt(65535)));let n=0,r=-1,o=-1;for(let s=0;s<=t.length;s++)s<t.length&&0===t[s]?o<0&&(o=s):(o>=0&&s-o>n&&(r=o,n=s-o),o=-1);const i=t.map(e=>e.toString(16));if(n>=2)return`${i.slice(0,r).join(":")}::${i.slice(r+n).join(":")}`;return i.join(":")}(e&(0===t?BigInt(0):r<<BigInt(128-t)&r))}/${t}`}return null}var $,P=function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},D=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},O=function(e,t){return function(n,r){t(n,r,e)}};const x={asnName:null,asnNetwork:null,continentCode:null,continentName:null,countryCode:null,countryName:null,cityName:null,timezone:null,latitude:null,longitude:null},E="city.mmdb",M="asn.mmdb";let j=$=class GeoipService{config;logger=new t.Logger($.name);cityReader=void 0;asnReader=void 0;refreshedAt=void 0;lastError=void 0;timer=void 0;constructor(e){this.config=e}async onModuleInit(){if(this.config.provider===r.None)return void this.logger.log('GeoIP provider "none": responses carry the IP address only');await a.promises.mkdir(this.config.dataDir,{recursive:!0});const e=await this.load();!e&&this.config.autoDownload?await this.refresh():e||this.logger.warn(`No GeoIP database found in ${this.config.dataDir} and GEOIP_AUTO_DOWNLOAD is off: responses carry the IP address only`),this.config.autoDownload&&this.config.refreshIntervalMs>0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},this.config.refreshIntervalMs),this.timer.unref())}onModuleDestroy(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get status(){let e;switch(this.config.provider){case r.Dbip:e="IP Geolocation by DB-IP (https://db-ip.com), CC BY 4.0";break;case r.Maxmind:e="This product includes GeoLite2 data created by MaxMind (https://www.maxmind.com)";break;default:e=null}return{provider:this.config.provider,attribution:e,city:!!this.cityReader,asn:!!this.asnReader,refreshedAt:this.refreshedAt?this.refreshedAt.toISOString():null,lastError:this.lastError??null}}lookup(e){const t={...x};if(this.cityReader)try{const n=this.cityReader.get(e);n&&(t.continentCode=n.continent?.code??null,t.continentName=n.continent?.names?.en??null,t.countryCode=n.country?.iso_code??null,t.countryName=n.country?.names?.en??null,t.cityName=n.city?.names?.en??null,t.timezone=n.location?.time_zone??null,t.latitude=n.location?.latitude??null,t.longitude=n.location?.longitude??null)}catch(n){this.logger.debug(`City lookup failed for ${e}: ${n.message}`)}if(this.asnReader)try{const[n,r]=this.asnReader.getWithPrefixLength(e);n&&(t.asnName=n.autonomous_system_organization??null,t.asnNetwork=R(e,r))}catch(n){this.logger.debug(`ASN lookup failed for ${e}: ${n.message}`)}return t}async refresh(){this.logger.log(`Downloading GeoIP databases from ${this.config.provider} into ${this.config.dataDir}`);try{switch(this.config.provider){case r.Dbip:await this.downloadDbip();break;case r.Maxmind:await this.downloadMaxmind();break;default:return}await this.load(),this.refreshedAt=new Date,this.lastError=void 0,this.logger.log("GeoIP databases updated")}catch(e){this.lastError=e.message,this.logger.error(`GeoIP download failed: ${e.message}`)}}async load(){const[e,t]=await Promise.all([this.openReader(E),this.openReader(M)]);return e&&(this.cityReader=e),t&&(this.asnReader=t),(void 0!==e||void 0!==t)&&(this.logger.log(`GeoIP databases loaded (city: ${!!e}, asn: ${!!t})`),!0)}async openReader(e){const t=`${this.config.dataDir}/${e}`;try{await a.promises.access(t)}catch(n){return}try{return await(0,c.open)(t)}catch(n){return void this.logger.warn(`Cannot open ${t}: ${n.message}`)}}async downloadDbip(){const e=new Date,t=[];for(let o=0;o<2;o++){const n=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-o,1));t.push(`${n.getUTCFullYear()}-${String(n.getUTCMonth()+1).padStart(2,"0")}`)}let n;for(const o of t)try{return await m(`https://download.db-ip.com/free/dbip-city-lite-${o}.mmdb.gz`,`${this.config.dataDir}/${E}`,{gunzip:!0,timeoutMs:this.config.downloadTimeoutMs}),void(await m(`https://download.db-ip.com/free/dbip-asn-lite-${o}.mmdb.gz`,`${this.config.dataDir}/${M}`,{gunzip:!0,timeoutMs:this.config.downloadTimeoutMs}))}catch(r){n=r,this.logger.warn(`DB-IP ${o} not available (${r.message}), trying the previous month`)}throw n??new Error("DB-IP download failed")}async downloadMaxmind(){const e=[["GeoLite2-City",E],["GeoLite2-ASN",M]];for(const[t,n]of e){const e=`${this.config.dataDir}/${t}.tar.gz`;await m(`https://download.maxmind.com/app/geoip_download?edition_id=${t}&license_key=${encodeURIComponent(this.config.maxmindLicenseKey)}&suffix=tar.gz`,e,{gunzip:!1,timeoutMs:this.config.downloadTimeoutMs});try{await w(e,`*/${t}.mmdb`,`${this.config.dataDir}/${n}`)}finally{await a.promises.rm(e,{force:!0})}}}};j=$=P([(0,t.Injectable)(),O(0,(0,t.Inject)(o)),D("design:paramtypes",[Object])],j);var G,N=function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},T=function(e,t){return function(n,r){t(n,r,e)}};function C(e){return b(e.ip??e.socket.remoteAddress??"")}let S=class FingerprintController{geoip;constructor(e){this.geoip=e}getRoot(){const e=this.geoip.status,t=["ProxyHerd fingerprint service","GET /api/json -> IP, network and location of the caller as JSON","GET /api/text -> IP of the caller as text","GET /health -> service status"];return e.attribution&&t.push(e.attribution),`${t.join("\n")}\n`}getHealth(){return{status:"ok",...this.geoip.status}}getJson(e){const t=C(e),n=e.headers["user-agent"];return{ip:t,useragent:"string"==typeof n&&n.length>0?n:null,...this.geoip.lookup(t)}}getText(e){return C(e)}};N([(0,t.Get)(),(0,t.Header)("Content-Type","text/plain; charset=utf-8"),_("design:type",Function),_("design:paramtypes",[]),_("design:returntype",String)],S.prototype,"getRoot",null),N([(0,t.Get)("health"),_("design:type",Function),_("design:paramtypes",[]),_("design:returntype",Object)],S.prototype,"getHealth",null),N([(0,t.Get)("api/json"),T(0,(0,t.Req)()),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",Object)],S.prototype,"getJson",null),N([(0,t.Get)("api/text"),(0,t.Header)("Content-Type","text/plain; charset=utf-8"),T(0,(0,t.Req)()),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",String)],S.prototype,"getText",null),S=N([(0,t.Controller)(),_("design:paramtypes",["function"==typeof(G=void 0!==j&&j)?G:Object])],S);var k,A=function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s};let L=k=class AppModule{static forRoot(e){return{module:k,controllers:[S],providers:[{provide:o,useValue:e},j]}}};L=k=A([(0,t.Module)({})],L),(async()=>{const e=s(),r=await n.NestFactory.create(L.forRoot(e),{logger:["log","warn","error"]});r.enableShutdownHooks(),e.trustProxy&&r.set("trust proxy",!0),await r.listen(e.port),new t.Logger("Fingerprint").log(`ProxyHerd fingerprint service listening on port ${e.port} (GeoIP provider: ${e.provider})`)})().catch(e=>{console.error(e.message??e),process.exit(1)});const q=exports;for(var z in e)q[z]=e[z];e.__esModule&&Object.defineProperty(q,"__esModule",{value:!0})})();
|
|
2
|
+
(()=>{"use strict";let e={};require("reflect-metadata");const t=require("@nestjs/common"),n=require("@nestjs/core");var r;!function(e){e.Dbip="dbip",e.Maxmind="maxmind",e.None="none"}(r||(r={}));const i="FINGERPRINT_SERVICE_CONFIG";function o(e,t){return void 0===e||e.length<=0?t:["1","true","yes","on"].includes(e.toLowerCase())}function s(e){const t=parseInt(e??"0",10);return Number.isFinite(t)&&t>0?t:0}function a(){const e=function(e){switch((e??"dbip").toLowerCase()){case"maxmind":return r.Maxmind;case"none":return r.None;default:return r.Dbip}}(process.env.GEOIP_PROVIDER),t=process.env.MAXMIND_LICENSE_KEY;if(e===r.Maxmind&&!t)throw new Error("GEOIP_PROVIDER=maxmind requires MAXMIND_LICENSE_KEY (free at https://www.maxmind.com/en/geolite2/signup)");return{port:parseInt(process.env.FINGERPRINT_PORT??"3000",10),provider:e,dataDir:process.env.GEOIP_DIR??"geoip",autoDownload:o(process.env.GEOIP_AUTO_DOWNLOAD,!0),refreshIntervalMs:60*parseInt(process.env.GEOIP_REFRESH_HOURS??"168",10)*60*1e3,maxmindLicenseKey:t,trustProxy:(n=process.env.TRUST_PROXY,void 0===n||n.length<=0?0:/^\d+$/.test(n)?parseInt(n,10):o(n,!1)?1:0),rateLimitPerMinute:s(process.env.RATE_LIMIT_PER_MINUTE),downloadTimeoutMs:parseInt(process.env.GEOIP_DOWNLOAD_TIMEOUT??"600000",10)};var n}const c=require("net"),l="::ffff:";function d(e){const t=e.toLowerCase();if(t.startsWith(l)){const e=t.substring(7);if((0,c.isIPv4)(e))return e}return e}function u(e,t){const n=d(e);if((0,c.isIPv4)(n)){if(t<0||t>32)return null;const e=n.split(".").map(e=>parseInt(e,10)),r=((e[0]<<24>>>0)+(e[1]<<16)+(e[2]<<8)+e[3]&(0===t?0:4294967295<<32-t>>>0))>>>0;return`${[r>>>24,r>>>16&255,r>>>8&255,255&r].join(".")}/${t}`}if((0,c.isIPv6)(n)){if(t<0||t>128)return null;const e=function(e){const[t,n]=e.split("::"),r=t.length>0?t.split(":"):[],i=n&&n.length>0?n.split(":"):[],o=8-r.length-i.length,s=[...r,...new Array(Math.max(o,0)).fill("0"),...i];let a=BigInt(0);for(const c of s)a=(a<<BigInt(16))+BigInt(parseInt(c,16));return a}(n.split("%")[0]),r=(BigInt(1)<<BigInt(128))-BigInt(1);return`${function(e){const t=[];for(let s=7;s>=0;s--)t.push(Number(e>>BigInt(16*s)&BigInt(65535)));let n=0,r=-1,i=-1;for(let s=0;s<=t.length;s++)s<t.length&&0===t[s]?i<0&&(i=s):(i>=0&&s-i>n&&(r=i,n=s-i),i=-1);const o=t.map(e=>e.toString(16));if(n>=2)return`${o.slice(0,r).join(":")}::${o.slice(r+n).join(":")}`;return o.join(":")}(e&(0===t?BigInt(0):r<<BigInt(128-t)&r))}/${t}`}return null}function p(e){return d(e.ip??e.socket.remoteAddress??"")}const f=require("fs"),h=require("maxmind"),g=require("child_process"),m=require("http"),w=require("https"),y=require("path"),v=require("stream/promises"),I=require("zlib");function R(e,t){return new Promise((n,r)=>{const i=new URL(e),o=("https:"===i.protocol?w.request:m.request)(i,{method:"GET",headers:{"User-Agent":"ProxyHerd-fingerprint"},timeout:t},e=>{n(e)});o.on("timeout",()=>{o.destroy(new Error(`Timeout while downloading ${e}`))}),o.on("error",r),o.end()})}async function b(e,t,n){await f.promises.mkdir((0,y.dirname)(t),{recursive:!0});const r=`${t}.download`,i=await async function(e,t){let n=e;for(let r=0;r<=5;r++){const e=await R(n,t),r=e.statusCode??0;if(!(r>=300&&r<400&&e.headers.location)){if(200!==r)throw e.resume(),new Error(`Download of ${n} failed with status ${r}`);return e}e.resume(),n=new URL(e.headers.location,n).toString()}throw new Error(`Too many redirects while downloading ${e}`)}(e,n.timeoutMs);try{n.gunzip?await(0,v.pipeline)(i,(0,I.createGunzip)(),(0,f.createWriteStream)(r)):await(0,v.pipeline)(i,(0,f.createWriteStream)(r)),await f.promises.rename(r,t)}catch(o){throw await f.promises.rm(r,{force:!0}),o}}async function P(e,t){const n=await f.promises.readdir(e,{withFileTypes:!0});for(const r of n){const n=(0,y.join)(e,r.name);if(r.isDirectory()){const e=await P(n,t);if(e)return e}else if(r.name===t)return n}return null}async function $(e,t,n){const r=(0,y.dirname)(n),i=(0,y.join)(r,`.extract-${process.pid}`);await f.promises.mkdir(i,{recursive:!0});try{await new Promise((n,r)=>{(0,g.execFile)("tar",["-xzf",e,"-C",i,"--wildcards",t],(e,t,i)=>{e?r(new Error(`tar failed: ${i.length>0?i:e.message}`)):n()})});const r=await P(i,n.split("/").pop());if(!r)throw new Error(`${t} not found in ${e}`);await f.promises.rename(r,n)}finally{await f.promises.rm(i,{recursive:!0,force:!0})}}var x,M=function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},D=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},E=function(e,t){return function(n,r){t(n,r,e)}};const O={asnName:null,asnNetwork:null,continentCode:null,continentName:null,countryCode:null,countryName:null,cityName:null,timezone:null,latitude:null,longitude:null},C="city.mmdb",_="asn.mmdb";let j=x=class GeoipService{config;logger=new t.Logger(x.name);cityReader=void 0;asnReader=void 0;refreshedAt=void 0;lastError=void 0;timer=void 0;constructor(e){this.config=e}async onModuleInit(){if(this.config.provider===r.None)return void this.logger.log('GeoIP provider "none": responses carry the IP address only');await f.promises.mkdir(this.config.dataDir,{recursive:!0});const e=await this.load();!e&&this.config.autoDownload?await this.refresh():e||this.logger.warn(`No GeoIP database found in ${this.config.dataDir} and GEOIP_AUTO_DOWNLOAD is off: responses carry the IP address only`),this.config.autoDownload&&this.config.refreshIntervalMs>0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},this.config.refreshIntervalMs),this.timer.unref())}onModuleDestroy(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get status(){let e;switch(this.config.provider){case r.Dbip:e="IP Geolocation by DB-IP (https://db-ip.com), CC BY 4.0";break;case r.Maxmind:e="This product includes GeoLite2 data created by MaxMind (https://www.maxmind.com)";break;default:e=null}return{provider:this.config.provider,attribution:e,city:!!this.cityReader,asn:!!this.asnReader,refreshedAt:this.refreshedAt?this.refreshedAt.toISOString():null,lastError:this.lastError??null}}lookup(e){const t={...O};if(this.cityReader)try{const n=this.cityReader.get(e);n&&(t.continentCode=n.continent?.code??null,t.continentName=n.continent?.names?.en??null,t.countryCode=n.country?.iso_code??null,t.countryName=n.country?.names?.en??null,t.cityName=n.city?.names?.en??null,t.timezone=n.location?.time_zone??null,t.latitude=n.location?.latitude??null,t.longitude=n.location?.longitude??null)}catch(n){this.logger.debug(`City lookup failed for ${e}: ${n.message}`)}if(this.asnReader)try{const[n,r]=this.asnReader.getWithPrefixLength(e);n&&(t.asnName=n.autonomous_system_organization??null,t.asnNetwork=u(e,r))}catch(n){this.logger.debug(`ASN lookup failed for ${e}: ${n.message}`)}return t}async refresh(){this.logger.log(`Downloading GeoIP databases from ${this.config.provider} into ${this.config.dataDir}`);try{switch(this.config.provider){case r.Dbip:await this.downloadDbip();break;case r.Maxmind:await this.downloadMaxmind();break;default:return}await this.load(),this.refreshedAt=new Date,this.lastError=void 0,this.logger.log("GeoIP databases updated")}catch(e){this.lastError=e.message,this.logger.error(`GeoIP download failed: ${e.message}`)}}async load(){const[e,t]=await Promise.all([this.openReader(C),this.openReader(_)]);return e&&(this.cityReader=e),t&&(this.asnReader=t),(void 0!==e||void 0!==t)&&(this.logger.log(`GeoIP databases loaded (city: ${!!e}, asn: ${!!t})`),!0)}async openReader(e){const t=`${this.config.dataDir}/${e}`;try{await f.promises.access(t)}catch(n){return}try{return await(0,h.open)(t)}catch(n){return void this.logger.warn(`Cannot open ${t}: ${n.message}`)}}async downloadDbip(){const e=new Date,t=[];for(let i=0;i<2;i++){const n=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-i,1));t.push(`${n.getUTCFullYear()}-${String(n.getUTCMonth()+1).padStart(2,"0")}`)}let n;for(const i of t)try{return await b(`https://download.db-ip.com/free/dbip-city-lite-${i}.mmdb.gz`,`${this.config.dataDir}/${C}`,{gunzip:!0,timeoutMs:this.config.downloadTimeoutMs}),void(await b(`https://download.db-ip.com/free/dbip-asn-lite-${i}.mmdb.gz`,`${this.config.dataDir}/${_}`,{gunzip:!0,timeoutMs:this.config.downloadTimeoutMs}))}catch(r){n=r,this.logger.warn(`DB-IP ${i} not available (${r.message}), trying the previous month`)}throw n??new Error("DB-IP download failed")}async downloadMaxmind(){const e=[["GeoLite2-City",C],["GeoLite2-ASN",_]];for(const[t,n]of e){const e=`${this.config.dataDir}/${t}.tar.gz`;await b(`https://download.maxmind.com/app/geoip_download?edition_id=${t}&license_key=${encodeURIComponent(this.config.maxmindLicenseKey)}&suffix=tar.gz`,e,{gunzip:!1,timeoutMs:this.config.downloadTimeoutMs});try{await $(e,`*/${t}.mmdb`,`${this.config.dataDir}/${n}`)}finally{await f.promises.rm(e,{force:!0})}}}};j=x=M([(0,t.Injectable)(),E(0,(0,t.Inject)(i)),D("design:paramtypes",[Object])],j);var T,N=function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},G=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},L=function(e,t){return function(n,r){t(n,r,e)}};let S=class FingerprintController{config;geoip;constructor(e,t){this.config=e,this.geoip=t}getRoot(){const e=this.geoip.status,t=["ProxyHerd fingerprint service","GET /api/json -> IP, network and location of the caller as JSON","GET /api/text -> IP of the caller as text","GET /health -> service status"];return e.attribution&&t.push(e.attribution),`${t.join("\n")}\n`}getHealth(){return{status:"ok",...this.geoip.status,rateLimit:this.config.rateLimitPerMinute>0}}getJson(e){const t=p(e),n=e.headers["user-agent"];return{ip:t,useragent:"string"==typeof n&&n.length>0?n:null,...this.geoip.lookup(t)}}getText(e){return p(e)}};N([(0,t.Get)(),(0,t.Header)("Content-Type","text/plain; charset=utf-8"),G("design:type",Function),G("design:paramtypes",[]),G("design:returntype",String)],S.prototype,"getRoot",null),N([(0,t.Get)("health"),G("design:type",Function),G("design:paramtypes",[]),G("design:returntype",Object)],S.prototype,"getHealth",null),N([(0,t.Get)("api/json"),(0,t.Header)("Cache-Control","no-store"),L(0,(0,t.Req)()),G("design:type",Function),G("design:paramtypes",[Object]),G("design:returntype",Object)],S.prototype,"getJson",null),N([(0,t.Get)("api/text"),(0,t.Header)("Content-Type","text/plain; charset=utf-8"),(0,t.Header)("Cache-Control","no-store"),L(0,(0,t.Req)()),G("design:type",Function),G("design:paramtypes",[Object]),G("design:returntype",String)],S.prototype,"getText",null),S=N([(0,t.Controller)(),L(0,(0,t.Inject)(i)),G("design:paramtypes",[Object,"function"==typeof(T=void 0!==j&&j)?T:Object])],S);var A,k=function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};let q=A=class AppModule{static forRoot(e){return{module:A,controllers:[S],providers:[{provide:i,useValue:e},j]}}};q=A=k([(0,t.Module)({})],q);const F=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i,z=/^[0-9a-f]{1,4}$/i;class RateLimiter{limit;windowMs;maxKeys;now;windows=new Map;lastSweep;constructor(e,t=6e4,n=2e5,r=Date.now){this.limit=e,this.windowMs=t,this.maxKeys=n,this.now=r,this.lastSweep=this.now()}get size(){return this.windows.size}take(e){const t=this.now();this.sweep(t);const n=this.windows.get(e);return!n||t-n.start>=this.windowMs?(this.windows.set(e,{start:t,count:1}),!0):(n.count+=1,n.count<=this.limit)}sweep(e){if(this.windows.size>=this.maxKeys)return this.windows.clear(),void(this.lastSweep=e);if(!(e-this.lastSweep<this.windowMs)){this.lastSweep=e;for(const[t,n]of this.windows)e-n.start>=this.windowMs&&this.windows.delete(t)}}}function U(e,t){if(t.trustProxy>0&&e.set("trust proxy",t.trustProxy),t.rateLimitPerMinute>0){const n=new RateLimiter(t.rateLimitPerMinute);e.use(["/api/json","/api/text"],(e,t,r)=>{const i=function(e){if(!e.includes(":"))return e;const t=F.exec(e);if(t)return t[1];const n=e.split("::");if(n.length>2)return e;const r=n[0].length>0?n[0].split(":"):[];let i;if(2===n.length){const t=n[1].length>0?n[1].split(":"):[],o=8-r.length-t.length;if(o<1)return e;const s=Array.from({length:o},()=>"0");i=[...r,...s,...t]}else i=r;const o=i.slice(0,4);return 8===i.length&&o.every(e=>z.test(e))?`${o.map(e=>parseInt(e,16).toString(16)).join(":")}::/64`:e}(p(e));n.take(i)?r():t.status(429).set({"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store","Retry-After":60..toString()}).send(`Too many requests from ${i} to this fingerprint service. Check fewer proxies per IP address, raise PROXY_REFRESH_DELAY, or run your own service: https://proxyherd.github.io/proxyherd/deployment/fingerprint\n`)})}}(async()=>{const e=a(),r=await n.NestFactory.create(q.forRoot(e),{logger:["log","warn","error"]});r.enableShutdownHooks(),U(r,e),await r.listen(e.port);const i=new t.Logger("Fingerprint");i.log(`ProxyHerd fingerprint service listening on port ${e.port} (GeoIP provider: ${e.provider})`),e.trustProxy>0&&i.log(`Caller address read from X-Forwarded-For, behind ${e.trustProxy} trusted reverse proxy(ies)`),e.rateLimitPerMinute>0&&i.log(`Rate limit: ${e.rateLimitPerMinute} requests per minute per address`)})().catch(e=>{console.error(e.message??e),process.exit(1)});const B=exports;for(var H in e)B[H]=e[H];e.__esModule&&Object.defineProperty(B,"__esModule",{value:!0})})();
|
package/package.json
CHANGED