Skip to content

Commit

Permalink
feat: Node.js 版支持 MMDB, 通过环境变量或在脚本中传入数据库文件路径, 可使用 ipaso 和 geoip 方法
Browse files Browse the repository at this point in the history
  • Loading branch information
xream committed May 12, 2024
1 parent d073dfe commit b083d2d
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 2 deletions.
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.14.308",
"version": "2.14.309",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and ShadowRocket.",
"main": "src/main.js",
"scripts": {
Expand All @@ -17,6 +17,7 @@
"author": "Peng-YM",
"license": "GPL-3.0",
"dependencies": {
"@maxmind/geoip2-node": "^5.0.0",
"automerge": "1.0.1-preview.7",
"body-parser": "^1.19.0",
"connect-history-api-fallback": "^2.0.0",
Expand Down
63 changes: 63 additions & 0 deletions backend/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/src/core/proxy-utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import $ from '@/core/app';
import { FILES_KEY, MODULES_KEY } from '@/constants';
import { findByName } from '@/utils/database';
import { produceArtifact } from '@/restful/sync';
import { getFlag, getISO } from '@/utils/geo';
import { getFlag, getISO, MMDB } from '@/utils/geo';
import Gist from '@/utils/gist';

function preprocess(raw) {
Expand Down Expand Up @@ -273,6 +273,7 @@ export const ProxyUtils = {
yaml: YAML,
getFlag,
getISO,
MMDB,
Gist,
};

Expand Down
30 changes: 30 additions & 0 deletions backend/src/utils/geo.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import $ from '@/core/app';

const ISOFlags = {
'🏳️‍🌈': ['EXP', 'BAND'],
'🇸🇱': ['TEST', 'SOS'],
Expand Down Expand Up @@ -427,3 +429,31 @@ export function getFlag(name) {
export function getISO(name) {
return ISOFlags[getFlag(name)]?.[0];
}

export class MMDB {
constructor({ country, asn } = {}) {
if ($.env.isNode) {
const Reader = eval(`require("@maxmind/geoip2-node")`).Reader;
const fs = eval("require('fs')");
const countryFile =
country || eval('process.env.SUB_STORE_MMDB_COUNTRY_PATH');
const asnFile = asn || eval('process.env.SUB_STORE_MMDB_ASN_PATH');
if (countryFile) {
this.countryReader = Reader.openBuffer(
fs.readFileSync(countryFile),
);
}
if (asnFile) {
if (!fs.existsSync(asnFile))
throw new Error('GeoLite2 ASN MMDB does not exist');
this.asnReader = Reader.openBuffer(fs.readFileSync(asnFile));
}
}
}
geoip(ip) {
return this.countryReader?.country(ip)?.country?.isoCode;
}
ipaso(ip) {
return this.asnReader?.asn(ip)?.autonomousSystemOrganization;
}
}

0 comments on commit b083d2d

Please sign in to comment.