mirror of
https://git.mirrors.martin98.com/https://github.com/sub-store-org/Sub-Store.git
synced 2025-08-23 06:49:11 +08:00
Compare commits
No commits in common. "master" and "2.14.441" have entirely different histories.
19
.github/workflows/main.yml
vendored
19
.github/workflows/main.yml
vendored
@ -1,6 +1,5 @@
|
||||
name: build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
@ -27,18 +26,18 @@ jobs:
|
||||
run: |
|
||||
npm install -g pnpm
|
||||
cd backend && pnpm i --no-frozen-lockfile
|
||||
# - name: Test
|
||||
# run: |
|
||||
# cd backend
|
||||
# pnpm test
|
||||
# - name: Build
|
||||
# run: |
|
||||
# cd backend
|
||||
# pnpm run build
|
||||
- name: Test
|
||||
run: |
|
||||
cd backend
|
||||
pnpm test
|
||||
- name: Build
|
||||
run: |
|
||||
cd backend
|
||||
pnpm run build
|
||||
- name: Bundle
|
||||
run: |
|
||||
cd backend
|
||||
pnpm bundle:esbuild
|
||||
pnpm run bundle
|
||||
- id: tag
|
||||
name: Generate release tag
|
||||
run: |
|
||||
|
24
README.md
24
README.md
@ -26,24 +26,17 @@ Core functionalities:
|
||||
|
||||
### Supported Input Formats
|
||||
|
||||
> ⚠️ Do not use `Shadowrocket` or `NekoBox` to export URI and then import it as input. The URIs exported in this way may not be standard URIs.
|
||||
> ⚠️ Do not use `Shadowrocket` to export URI and then import it as input. It is not a standard URI.
|
||||
|
||||
- [x] Proxy URI Scheme(`socks5`, `socks5+tls`, `http`, `https`(it's ok))
|
||||
|
||||
example: `socks5+tls://user:pass@ip:port#name`
|
||||
|
||||
- [x] URI(AnyTLS, SOCKS, SS, SSR, VMess, VLESS, Trojan, Hysteria, Hysteria 2, TUIC v5, WireGuard)
|
||||
- [x] URI(SS, SSR, VMess, VLESS, Trojan, Hysteria, Hysteria 2, TUIC v5, WireGuard)
|
||||
- [x] Clash Proxies YAML
|
||||
- [x] Clash Proxy JSON(single line)
|
||||
- [x] QX (SS, SSR, VMess, Trojan, HTTP, SOCKS5, VLESS)
|
||||
- [x] Loon (SS, SSR, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard, VLESS, Hysteria 2)
|
||||
- [x] Surge (Direct, SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, TUIC, Snell, Hysteria 2, SSH(Password authentication only), External Proxy Program(only for macOS), WireGuard(Surge to Surge))
|
||||
- [x] Surfboard (SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard(Surfboard to Surfboard))
|
||||
- [x] Clash.Meta (Direct, SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC, SSH, mieru, AnyTLS)
|
||||
- [x] Clash.Meta (Direct, SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC)
|
||||
- [x] Stash (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, TUIC, Juicity, SSH)
|
||||
|
||||
Deprecated(The frontend doesn't show it, but the backend still supports it, with the query parameter `target=Clash`):
|
||||
|
||||
- [x] Clash (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard)
|
||||
|
||||
### Supported Target Platforms
|
||||
@ -51,6 +44,7 @@ Deprecated(The frontend doesn't show it, but the backend still supports it, with
|
||||
- [x] Plain JSON
|
||||
- [x] Stash
|
||||
- [x] Clash.Meta(mihomo)
|
||||
- [x] Clash
|
||||
- [x] Surfboard
|
||||
- [x] Surge
|
||||
- [x] SurgeMac(Use mihomo to support protocols that are not supported by Surge itself)
|
||||
@ -62,10 +56,6 @@ Deprecated(The frontend doesn't show it, but the backend still supports it, with
|
||||
- [x] V2Ray
|
||||
- [x] V2Ray URI
|
||||
|
||||
Deprecated:
|
||||
|
||||
- [x] Clash
|
||||
|
||||
## 2. Subscription Formatting
|
||||
|
||||
### Filtering
|
||||
@ -128,9 +118,3 @@ This project is under the GPL V3 LICENSE.
|
||||
|
||||
- Special thanks to @KOP-XIAO for his awesome resource-parser. Please give a [star](https://github.com/KOP-XIAO/QuantumultX) for his great work!
|
||||
- Special thanks to @Orz-3 and @58xinian for their awesome icons.
|
||||
|
||||
## Sponsors
|
||||
|
||||
[](https://yxvm.com)
|
||||
|
||||
[NodeSupport](https://github.com/NodeSeekDev/NodeSupport) sponsored this project.
|
||||
|
@ -5,7 +5,7 @@
|
||||
* ╚════██║██║ ██║██╔══██╗╚════╝╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝
|
||||
* ███████║╚██████╔╝██████╔╝ ███████║ ██║ ╚██████╔╝██║ ██║███████╗
|
||||
* ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝
|
||||
* Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket!
|
||||
* Advanced Subscription Manager for QX, Loon, Surge, Stash and ShadowRocket!
|
||||
* @updated: <%= updated %>
|
||||
* @version: <%= pkg.version %>
|
||||
* @author: Peng-YM
|
||||
|
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "sub-store",
|
||||
"version": "2.19.60",
|
||||
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
|
||||
"version": "2.14.441",
|
||||
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and ShadowRocket.",
|
||||
"main": "src/main.js",
|
||||
"scripts": {
|
||||
"preinstall": "npx only-allow pnpm",
|
||||
@ -12,37 +12,28 @@
|
||||
"dev:run": "nodemon -w sub-store.min.js sub-store.min.js",
|
||||
"build": "gulp",
|
||||
"bundle": "node bundle.js",
|
||||
"bundle:esbuild": "node bundle-esbuild.js",
|
||||
"changelog": "conventional-changelog -p cli -i CHANGELOG.md -s"
|
||||
},
|
||||
"author": "Peng-YM",
|
||||
"license": "GPL-3.0",
|
||||
"pnpm": {
|
||||
"patchedDependencies": {
|
||||
"http-proxy@1.18.1": "patches/http-proxy@1.18.1.patch"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@maxmind/geoip2-node": "^5.0.0",
|
||||
"automerge": "1.0.1-preview.7",
|
||||
"body-parser": "^1.19.0",
|
||||
"buffer": "^6.0.3",
|
||||
"dotenv": "^16.4.7",
|
||||
"connect-history-api-fallback": "^2.0.0",
|
||||
"cron": "^3.1.6",
|
||||
"dns-packet": "^5.6.1",
|
||||
"express": "^4.17.1",
|
||||
"mime-types": "^2.1.35",
|
||||
"http-proxy-middleware": "^3.0.3",
|
||||
"http-proxy-middleware": "^2.0.6",
|
||||
"ip-address": "^9.0.5",
|
||||
"js-base64": "^3.7.2",
|
||||
"jsrsasign": "^11.1.0",
|
||||
"lodash": "^4.17.21",
|
||||
"ms": "^2.1.3",
|
||||
"nanoid": "^3.3.3",
|
||||
"semver": "^7.6.3",
|
||||
"static-js-yaml": "^1.0.0",
|
||||
"undici": "^7.4.0"
|
||||
"request": "^2.88.2",
|
||||
"static-js-yaml": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.18.0",
|
||||
|
@ -1,46 +0,0 @@
|
||||
diff --git a/lib/http-proxy/common.js b/lib/http-proxy/common.js
|
||||
index 6513e81d80d5250ea249ea833f819ece67897c7e..486d4c896d65a3bb7cf63307af68facb3ddb886b 100644
|
||||
--- a/lib/http-proxy/common.js
|
||||
+++ b/lib/http-proxy/common.js
|
||||
@@ -1,6 +1,5 @@
|
||||
var common = exports,
|
||||
url = require('url'),
|
||||
- extend = require('util')._extend,
|
||||
required = require('requires-port');
|
||||
|
||||
var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
|
||||
@@ -40,10 +39,10 @@ common.setupOutgoing = function(outgoing, options, req, forward) {
|
||||
);
|
||||
|
||||
outgoing.method = options.method || req.method;
|
||||
- outgoing.headers = extend({}, req.headers);
|
||||
+ outgoing.headers = Object.assign({}, req.headers);
|
||||
|
||||
if (options.headers){
|
||||
- extend(outgoing.headers, options.headers);
|
||||
+ Object.assign(outgoing.headers, options.headers);
|
||||
}
|
||||
|
||||
if (options.auth) {
|
||||
diff --git a/lib/http-proxy/index.js b/lib/http-proxy/index.js
|
||||
index 977a4b3622b9eaac27689f06347ea4c5173a96cd..88b2d0fcfa03c3aafa47c7e6d38e64412c45a7cc 100644
|
||||
--- a/lib/http-proxy/index.js
|
||||
+++ b/lib/http-proxy/index.js
|
||||
@@ -1,5 +1,4 @@
|
||||
var httpProxy = module.exports,
|
||||
- extend = require('util')._extend,
|
||||
parse_url = require('url').parse,
|
||||
EE3 = require('eventemitter3'),
|
||||
http = require('http'),
|
||||
@@ -47,9 +46,9 @@ function createRightProxy(type) {
|
||||
args[cntr] !== res
|
||||
) {
|
||||
//Copy global options
|
||||
- requestOptions = extend({}, options);
|
||||
+ requestOptions = Object.assign({}, options);
|
||||
//Overwrite with request options
|
||||
- extend(requestOptions, args[cntr]);
|
||||
+ Object.assign(requestOptions, args[cntr]);
|
||||
|
||||
cntr--;
|
||||
}
|
13645
backend/pnpm-lock.yaml
generated
13645
backend/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@ -1,13 +1,11 @@
|
||||
import { Base64 } from 'js-base64';
|
||||
import { Buffer } from 'buffer';
|
||||
import rs from '@/utils/rs';
|
||||
import YAML from '@/utils/yaml';
|
||||
import download, { downloadFile } from '@/utils/download';
|
||||
import download from '@/utils/download';
|
||||
import {
|
||||
isIPv4,
|
||||
isIPv6,
|
||||
isValidPortNumber,
|
||||
isValidUUID,
|
||||
isNotBlank,
|
||||
ipAddress,
|
||||
getRandomPort,
|
||||
@ -23,8 +21,6 @@ import { findByName } from '@/utils/database';
|
||||
import { produceArtifact } from '@/restful/sync';
|
||||
import { getFlag, removeFlag, getISO, MMDB } from '@/utils/geo';
|
||||
import Gist from '@/utils/gist';
|
||||
import { isPresent } from './producers/utils';
|
||||
import { doh } from '@/utils/dns';
|
||||
|
||||
function preprocess(raw) {
|
||||
for (const processor of PROXY_PREPROCESSORS) {
|
||||
@ -79,16 +75,7 @@ function parse(raw) {
|
||||
$.error(`Failed to parse line: ${line}`);
|
||||
}
|
||||
}
|
||||
return proxies.filter((proxy) => {
|
||||
if (['vless', 'vmess'].includes(proxy.type)) {
|
||||
const isProxyUUIDValid = isValidUUID(proxy.uuid);
|
||||
if (!isProxyUUIDValid) {
|
||||
$.error(`UUID may be invalid: ${proxy.name} ${proxy.uuid}`);
|
||||
}
|
||||
// return isProxyUUIDValid;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return proxies;
|
||||
}
|
||||
|
||||
async function processFn(
|
||||
@ -115,7 +102,12 @@ async function processFn(
|
||||
if (item.type.indexOf('Script') !== -1) {
|
||||
const { mode, content } = item.args;
|
||||
if (mode === 'link') {
|
||||
let noCache;
|
||||
let url = content || '';
|
||||
if (url.endsWith('#noCache')) {
|
||||
url = url.replace(/#noCache$/, '');
|
||||
noCache = true;
|
||||
}
|
||||
// extract link arguments
|
||||
const rawArgs = url.split('#');
|
||||
if (rawArgs.length > 1) {
|
||||
@ -134,17 +126,10 @@ async function processFn(
|
||||
}
|
||||
}
|
||||
}
|
||||
url = `${url.split('#')[0]}${
|
||||
rawArgs[2]
|
||||
? `#${rawArgs[2]}`
|
||||
: $arguments?.noCache != null ||
|
||||
$arguments?.insecure != null
|
||||
? `#${rawArgs[1]}`
|
||||
: ''
|
||||
}`;
|
||||
const downloadUrlMatch = url
|
||||
.split('#')[0]
|
||||
.match(/^\/api\/(file|module)\/(.+)/);
|
||||
url = `${url.split('#')[0]}${noCache ? '#noCache' : ''}`;
|
||||
const downloadUrlMatch = url.match(
|
||||
/^\/api\/(file|module)\/(.+)/,
|
||||
);
|
||||
if (downloadUrlMatch) {
|
||||
let type = '';
|
||||
try {
|
||||
@ -174,17 +159,6 @@ async function processFn(
|
||||
);
|
||||
throw new Error(`无法加载 ${type}: ${url}`);
|
||||
}
|
||||
} else if (url?.startsWith('/')) {
|
||||
try {
|
||||
const fs = eval(`require("fs")`);
|
||||
script = fs.readFileSync(url.split('#')[0], 'utf8');
|
||||
// $.info(`Script loaded: >>>\n ${script}`);
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when reading local script: ${item.args.content}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法从该路径读取脚本文件: ${url}`);
|
||||
}
|
||||
} else {
|
||||
// if this is a remote script, download it
|
||||
try {
|
||||
@ -199,7 +173,6 @@ async function processFn(
|
||||
}
|
||||
} else {
|
||||
script = content;
|
||||
$arguments = item.args.arguments || {};
|
||||
}
|
||||
}
|
||||
|
||||
@ -241,22 +214,10 @@ function produce(proxies, targetPlatform, type, opts = {}) {
|
||||
);
|
||||
|
||||
// filter unsupported proxies
|
||||
proxies = proxies.filter((proxy) => {
|
||||
// 检查代理是否支持目标平台
|
||||
if (proxy.supported && proxy.supported[targetPlatform] === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 对于 vless 和 vmess 代理,需要额外验证 UUID
|
||||
if (['vless', 'vmess'].includes(proxy.type)) {
|
||||
const isProxyUUIDValid = isValidUUID(proxy.uuid);
|
||||
if (!isProxyUUIDValid)
|
||||
$.error(`UUID may be invalid: ${proxy.name} ${proxy.uuid}`);
|
||||
// return isProxyUUIDValid;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
proxies = proxies.filter(
|
||||
(proxy) =>
|
||||
!(proxy.supported && proxy.supported[targetPlatform] === false),
|
||||
);
|
||||
|
||||
proxies = proxies.map((proxy) => {
|
||||
proxy._resolved = proxy.resolved;
|
||||
@ -342,11 +303,6 @@ export const ProxyUtils = {
|
||||
MMDB,
|
||||
Gist,
|
||||
download,
|
||||
downloadFile,
|
||||
isValidUUID,
|
||||
doh,
|
||||
Buffer,
|
||||
Base64,
|
||||
};
|
||||
|
||||
function tryParse(parser, line) {
|
||||
@ -387,14 +343,6 @@ function lastParse(proxy) {
|
||||
if (typeof proxy.password === 'number') {
|
||||
proxy.password = numberToString(proxy.password);
|
||||
}
|
||||
if (
|
||||
['ss'].includes(proxy.type) &&
|
||||
proxy.cipher === 'none' &&
|
||||
!proxy.password
|
||||
) {
|
||||
// https://github.com/MetaCubeX/mihomo/issues/1677
|
||||
proxy.password = '';
|
||||
}
|
||||
if (proxy.interface) {
|
||||
proxy['interface-name'] = proxy.interface;
|
||||
delete proxy.interface;
|
||||
@ -444,14 +392,9 @@ function lastParse(proxy) {
|
||||
}
|
||||
}
|
||||
if (
|
||||
[
|
||||
'trojan',
|
||||
'tuic',
|
||||
'hysteria',
|
||||
'hysteria2',
|
||||
'juicity',
|
||||
'anytls',
|
||||
].includes(proxy.type)
|
||||
['trojan', 'tuic', 'hysteria', 'hysteria2', 'juicity'].includes(
|
||||
proxy.type,
|
||||
)
|
||||
) {
|
||||
proxy.tls = true;
|
||||
}
|
||||
@ -535,14 +478,6 @@ function lastParse(proxy) {
|
||||
proxy['obfs-password'] = proxy.obfs;
|
||||
proxy.obfs = 'salamander';
|
||||
}
|
||||
if (
|
||||
['hysteria2'].includes(proxy.type) &&
|
||||
!proxy['obfs-password'] &&
|
||||
proxy['obfs_password']
|
||||
) {
|
||||
proxy['obfs-password'] = proxy['obfs_password'];
|
||||
delete proxy['obfs_password'];
|
||||
}
|
||||
if (['vless'].includes(proxy.type)) {
|
||||
// 删除 reality-opts: {}
|
||||
if (
|
||||
@ -629,20 +564,6 @@ function lastParse(proxy) {
|
||||
if (!proxy['tls-fingerprint'] && caStr) {
|
||||
proxy['tls-fingerprint'] = rs.generateFingerprint(caStr);
|
||||
}
|
||||
if (
|
||||
['ss'].includes(proxy.type) &&
|
||||
isPresent(proxy, 'shadow-tls-password')
|
||||
) {
|
||||
proxy.plugin = 'shadow-tls';
|
||||
proxy['plugin-opts'] = {
|
||||
host: proxy['shadow-tls-sni'],
|
||||
password: proxy['shadow-tls-password'],
|
||||
version: proxy['shadow-tls-version'],
|
||||
};
|
||||
delete proxy['shadow-tls-sni'];
|
||||
delete proxy['shadow-tls-password'];
|
||||
delete proxy['shadow-tls-version'];
|
||||
}
|
||||
return proxy;
|
||||
}
|
||||
|
||||
|
@ -11,7 +11,6 @@ import getSurgeParser from './peggy/surge';
|
||||
import getLoonParser from './peggy/loon';
|
||||
import getQXParser from './peggy/qx';
|
||||
import getTrojanURIParser from './peggy/trojan-uri';
|
||||
import $ from '@/core/app';
|
||||
|
||||
import { Base64 } from 'js-base64';
|
||||
|
||||
@ -28,94 +27,6 @@ function surge_port_hopping(raw) {
|
||||
};
|
||||
}
|
||||
|
||||
function URI_PROXY() {
|
||||
// socks5+tls
|
||||
// socks5
|
||||
// http, https(可以这么写)
|
||||
const name = 'URI PROXY Parser';
|
||||
const test = (line) => {
|
||||
return /^(socks5\+tls|socks5|http|https):\/\//.test(line);
|
||||
};
|
||||
const parse = (line) => {
|
||||
// parse url
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
let [__, type, tls, username, password, server, port, query, name] =
|
||||
line.match(
|
||||
/^(socks5|http|http)(\+tls|s)?:\/\/(?:(.*?):(.*?)@)?(.*?)(?::(\d+?))?(\?.*?)?(?:#(.*?))?$/,
|
||||
);
|
||||
if (port) {
|
||||
port = parseInt(port, 10);
|
||||
} else {
|
||||
if (tls) {
|
||||
port = 443;
|
||||
} else if (type === 'http') {
|
||||
port = 80;
|
||||
} else {
|
||||
$.error(`port is not present in line: ${line}`);
|
||||
throw new Error(`port is not present in line: ${line}`);
|
||||
}
|
||||
$.info(`port is not present in line: ${line}, set to ${port}`);
|
||||
}
|
||||
|
||||
const proxy = {
|
||||
name:
|
||||
name != null
|
||||
? decodeURIComponent(name)
|
||||
: `${type} ${server}:${port}`,
|
||||
type,
|
||||
tls: tls ? true : false,
|
||||
server,
|
||||
port,
|
||||
username:
|
||||
username != null ? decodeURIComponent(username) : undefined,
|
||||
password:
|
||||
password != null ? decodeURIComponent(password) : undefined,
|
||||
};
|
||||
|
||||
return proxy;
|
||||
};
|
||||
return { name, test, parse };
|
||||
}
|
||||
function URI_SOCKS() {
|
||||
const name = 'URI SOCKS Parser';
|
||||
const test = (line) => {
|
||||
return /^socks:\/\//.test(line);
|
||||
};
|
||||
const parse = (line) => {
|
||||
// parse url
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
let [__, type, auth, server, port, query, name] = line.match(
|
||||
/^(socks)?:\/\/(?:(.*)@)?(.*?)(?::(\d+?))?(\?.*?)?(?:#(.*?))?$/,
|
||||
);
|
||||
if (port) {
|
||||
port = parseInt(port, 10);
|
||||
} else {
|
||||
$.error(`port is not present in line: ${line}`);
|
||||
throw new Error(`port is not present in line: ${line}`);
|
||||
}
|
||||
let username, password;
|
||||
if (auth) {
|
||||
const parsed = Base64.decode(decodeURIComponent(auth)).split(':');
|
||||
username = parsed[0];
|
||||
password = parsed[1];
|
||||
}
|
||||
|
||||
const proxy = {
|
||||
name:
|
||||
name != null
|
||||
? decodeURIComponent(name)
|
||||
: `${type} ${server}:${port}`,
|
||||
type: 'socks5',
|
||||
server,
|
||||
port,
|
||||
username,
|
||||
password,
|
||||
};
|
||||
|
||||
return proxy;
|
||||
};
|
||||
return { name, test, parse };
|
||||
}
|
||||
// Parse SS URI format (only supports new SIP002, legacy format is depreciated).
|
||||
// reference: https://github.com/shadowsocks/shadowsocks-org/wiki/SIP002-URI-Scheme
|
||||
function URI_SS() {
|
||||
@ -128,22 +39,16 @@ function URI_SS() {
|
||||
// parse url
|
||||
let content = line.split('ss://')[1];
|
||||
|
||||
let name = line.split('#')[1];
|
||||
const proxy = {
|
||||
name: decodeURIComponent(line.split('#')[1]),
|
||||
type: 'ss',
|
||||
};
|
||||
content = content.split('#')[0]; // strip proxy name
|
||||
// handle IPV4 and IPV6
|
||||
let serverAndPortArray = content.match(/@([^/?]*)(\/|\?|$)/);
|
||||
|
||||
let rawUserInfoStr = decodeURIComponent(content.split('@')[0]); // 其实应该分隔之后, 用户名和密码再 decodeURIComponent. 但是问题不大
|
||||
let userInfoStr;
|
||||
if (rawUserInfoStr?.startsWith('2022-blake3-')) {
|
||||
userInfoStr = rawUserInfoStr;
|
||||
} else {
|
||||
userInfoStr = Base64.decode(rawUserInfoStr);
|
||||
}
|
||||
|
||||
let serverAndPortArray = content.match(/@([^/]*)(\/|$)/);
|
||||
let userInfoStr = Base64.decode(
|
||||
decodeURIComponent(content.split('@')[0]),
|
||||
);
|
||||
let query = '';
|
||||
if (!serverAndPortArray) {
|
||||
if (content.includes('?')) {
|
||||
@ -152,7 +57,6 @@ function URI_SS() {
|
||||
query = parsed[2];
|
||||
}
|
||||
content = Base64.decode(content);
|
||||
|
||||
if (query) {
|
||||
if (/(&|\?)v2ray-plugin=/.test(query)) {
|
||||
const parsed = query.match(/(&|\?)v2ray-plugin=(.*?)(&|$)/);
|
||||
@ -166,35 +70,25 @@ function URI_SS() {
|
||||
}
|
||||
content = `${content}${query}`;
|
||||
}
|
||||
userInfoStr = content.match(/(^.*)@/)?.[1];
|
||||
serverAndPortArray = content.match(/@([^/@]*)(\/|$)/);
|
||||
} else if (content.includes('?')) {
|
||||
const parsed = content.match(/(\?.*)$/);
|
||||
query = parsed[1];
|
||||
userInfoStr = content.split('@')[0];
|
||||
serverAndPortArray = content.match(/@([^/]*)(\/|$)/);
|
||||
}
|
||||
|
||||
const serverAndPort = serverAndPortArray[1];
|
||||
const portIdx = serverAndPort.lastIndexOf(':');
|
||||
proxy.server = serverAndPort.substring(0, portIdx);
|
||||
proxy.port = `${serverAndPort.substring(portIdx + 1)}`.match(
|
||||
/\d+/,
|
||||
)?.[0];
|
||||
let userInfo = userInfoStr.match(/(^.*?):(.*$)/);
|
||||
proxy.cipher = userInfo?.[1];
|
||||
proxy.password = userInfo?.[2];
|
||||
// if (!proxy.cipher || !proxy.password) {
|
||||
// userInfo = rawUserInfoStr.match(/(^.*?):(.*$)/);
|
||||
// proxy.cipher = userInfo?.[1];
|
||||
// proxy.password = userInfo?.[2];
|
||||
// }
|
||||
const userInfo = userInfoStr.match(/(^.*?):(.*$)/);
|
||||
proxy.cipher = userInfo[1];
|
||||
proxy.password = userInfo[2];
|
||||
|
||||
// handle obfs
|
||||
const pluginMatch = content.match(/[?&]plugin=([^&]+)/);
|
||||
const shadowTlsMatch = content.match(/[?&]shadow-tls=([^&]+)/);
|
||||
|
||||
if (pluginMatch) {
|
||||
const idx = content.indexOf('?plugin=');
|
||||
if (idx !== -1) {
|
||||
const pluginInfo = (
|
||||
'plugin=' + decodeURIComponent(pluginMatch[1])
|
||||
'plugin=' +
|
||||
decodeURIComponent(content.split('?plugin=')[1].split('&')[0])
|
||||
).split(';');
|
||||
const params = {};
|
||||
for (const item of pluginInfo) {
|
||||
@ -219,51 +113,18 @@ function URI_SS() {
|
||||
tls: getIfPresent(params.tls),
|
||||
};
|
||||
break;
|
||||
case 'shadow-tls': {
|
||||
proxy.plugin = 'shadow-tls';
|
||||
const version = getIfNotBlank(params['version']);
|
||||
proxy['plugin-opts'] = {
|
||||
host: getIfNotBlank(params['host']),
|
||||
password: getIfNotBlank(params['password']),
|
||||
version: version ? parseInt(version, 10) : undefined,
|
||||
};
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported plugin option: ${params.plugin}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Shadowrocket
|
||||
if (shadowTlsMatch) {
|
||||
const params = JSON.parse(Base64.decode(shadowTlsMatch[1]));
|
||||
const version = getIfNotBlank(params['version']);
|
||||
const address = getIfNotBlank(params['address']);
|
||||
const port = getIfNotBlank(params['port']);
|
||||
proxy.plugin = 'shadow-tls';
|
||||
proxy['plugin-opts'] = {
|
||||
host: getIfNotBlank(params['host']),
|
||||
password: getIfNotBlank(params['password']),
|
||||
version: version ? parseInt(version, 10) : undefined,
|
||||
};
|
||||
if (address) {
|
||||
proxy.server = address;
|
||||
}
|
||||
if (port) {
|
||||
proxy.port = parseInt(port, 10);
|
||||
}
|
||||
}
|
||||
if (/(&|\?)uot=(1|true)/i.test(query)) {
|
||||
proxy['udp-over-tcp'] = true;
|
||||
}
|
||||
if (/(&|\?)tfo=(1|true)/i.test(query)) {
|
||||
proxy.tfo = true;
|
||||
}
|
||||
if (name != null) {
|
||||
name = decodeURIComponent(name);
|
||||
}
|
||||
proxy.name = name ?? `SS ${proxy.server}:${proxy.port}`;
|
||||
return proxy;
|
||||
};
|
||||
return { name, test, parse };
|
||||
@ -346,7 +207,7 @@ function URI_VMess() {
|
||||
};
|
||||
const parse = (line) => {
|
||||
line = line.split('vmess://')[1];
|
||||
let content = Base64.decode(line.replace(/\?.*?$/, ''));
|
||||
let content = Base64.decode(line);
|
||||
if (/=\s*vmess/.test(content)) {
|
||||
// Quantumult VMess URI format
|
||||
const partitions = content.split(',').map((p) => p.trim());
|
||||
@ -439,16 +300,7 @@ function URI_VMess() {
|
||||
type: 'vmess',
|
||||
server,
|
||||
port,
|
||||
// https://github.com/2dust/v2rayN/wiki/Description-of-VMess-share-link
|
||||
// https://github.com/XTLS/Xray-core/issues/91
|
||||
cipher: [
|
||||
'auto',
|
||||
'aes-128-gcm',
|
||||
'chacha20-poly1305',
|
||||
'none',
|
||||
].includes(params.scy)
|
||||
? params.scy
|
||||
: 'auto',
|
||||
cipher: getIfPresent(params.scy, 'auto'),
|
||||
uuid: params.id,
|
||||
alterId: parseInt(
|
||||
getIfPresent(params.aid ?? params.alterId, 0),
|
||||
@ -465,12 +317,8 @@ function URI_VMess() {
|
||||
);
|
||||
}
|
||||
// https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
|
||||
if (proxy.tls) {
|
||||
if (params.sni && params.sni !== '') {
|
||||
proxy.sni = params.sni;
|
||||
} else if (params.peer && params.peer !== '') {
|
||||
proxy.sni = params.peer;
|
||||
}
|
||||
if (proxy.tls && params.sni && params.sni !== '') {
|
||||
proxy.sni = params.sni;
|
||||
}
|
||||
let httpupgrade = false;
|
||||
// handle obfs
|
||||
@ -482,8 +330,8 @@ function URI_VMess() {
|
||||
['http'].includes(params.type)
|
||||
) {
|
||||
proxy.network = 'http';
|
||||
} else if (['grpc', 'kcp', 'quic'].includes(params.net)) {
|
||||
proxy.network = params.net;
|
||||
} else if (['grpc'].includes(params.net)) {
|
||||
proxy.network = 'grpc';
|
||||
} else if (
|
||||
params.net === 'httpupgrade' ||
|
||||
proxy.network === 'httpupgrade'
|
||||
@ -509,11 +357,6 @@ function URI_VMess() {
|
||||
} catch (e) {}
|
||||
let transportPath = params.path;
|
||||
|
||||
// 补上默认 path
|
||||
if (['ws'].includes(proxy.network)) {
|
||||
transportPath = transportPath || '/';
|
||||
}
|
||||
|
||||
if (proxy.network === 'http') {
|
||||
if (transportHost) {
|
||||
// 1)http(tcp)->host中间逗号(,)隔开
|
||||
@ -533,28 +376,13 @@ function URI_VMess() {
|
||||
}
|
||||
}
|
||||
// 传输层应该有配置, 暂时不考虑兼容不给配置的节点
|
||||
if (
|
||||
transportPath ||
|
||||
transportHost ||
|
||||
['kcp', 'quic'].includes(proxy.network)
|
||||
) {
|
||||
if (transportPath || transportHost) {
|
||||
if (['grpc'].includes(proxy.network)) {
|
||||
proxy[`${proxy.network}-opts`] = {
|
||||
'grpc-service-name': getIfNotBlank(transportPath),
|
||||
'_grpc-type': getIfNotBlank(params.type),
|
||||
'_grpc-authority': getIfNotBlank(params.authority),
|
||||
};
|
||||
} else if (['kcp', 'quic'].includes(proxy.network)) {
|
||||
proxy[`${proxy.network}-opts`] = {
|
||||
[`_${proxy.network}-type`]: getIfNotBlank(
|
||||
params.type,
|
||||
),
|
||||
[`_${proxy.network}-host`]: getIfNotBlank(
|
||||
getIfNotBlank(transportHost),
|
||||
),
|
||||
[`_${proxy.network}-path`]:
|
||||
getIfNotBlank(transportPath),
|
||||
};
|
||||
} else {
|
||||
const opts = {
|
||||
path: getIfNotBlank(transportPath),
|
||||
@ -570,12 +398,6 @@ function URI_VMess() {
|
||||
delete proxy.network;
|
||||
}
|
||||
}
|
||||
|
||||
proxy['client-fingerprint'] = params.fp;
|
||||
proxy.alpn = params.alpn ? params.alpn.split(',') : undefined;
|
||||
// 然而 wiki 和 app 实测中都没有字段表示这个
|
||||
// proxy['skip-cert-verify'] = /(TRUE)|1/i.test(params.allowInsecure);
|
||||
|
||||
return proxy;
|
||||
}
|
||||
};
|
||||
@ -659,9 +481,6 @@ function URI_VLESS() {
|
||||
if (params.sid) {
|
||||
opts['short-id'] = params.sid;
|
||||
}
|
||||
if (params.spx) {
|
||||
opts['_spider-x'] = params.spx;
|
||||
}
|
||||
if (Object.keys(opts).length > 0) {
|
||||
// proxy[`${params.security}-opts`] = opts;
|
||||
proxy[`${params.security}-opts`] = opts;
|
||||
@ -677,9 +496,6 @@ function URI_VLESS() {
|
||||
}
|
||||
if (!proxy.network && isShadowrocket && params.obfs) {
|
||||
proxy.network = params.obfs;
|
||||
if (['none'].includes(proxy.network)) {
|
||||
proxy.network = 'tcp';
|
||||
}
|
||||
}
|
||||
if (['websocket'].includes(proxy.network)) {
|
||||
proxy.network = 'ws';
|
||||
@ -732,61 +548,6 @@ function URI_VLESS() {
|
||||
// mKCP 的伪装头部类型。当前可选值有 none / srtp / utp / wechat-video / dtls / wireguard。省略时默认值为 none,即不使用伪装头部,但不可以为空字符串。
|
||||
proxy.headerType = params.headerType || 'none';
|
||||
}
|
||||
|
||||
if (params.mode) {
|
||||
proxy._mode = params.mode;
|
||||
}
|
||||
if (params.extra) {
|
||||
proxy._extra = params.extra;
|
||||
}
|
||||
}
|
||||
|
||||
return proxy;
|
||||
};
|
||||
return { name, test, parse };
|
||||
}
|
||||
function URI_AnyTLS() {
|
||||
const name = 'URI AnyTLS Parser';
|
||||
const test = (line) => {
|
||||
return /^anytls:\/\//.test(line);
|
||||
};
|
||||
const parse = (line) => {
|
||||
line = line.split(/anytls:\/\//)[1];
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
let [__, password, server, port, addons = '', name] =
|
||||
/^(.*?)@(.*?)(?::(\d+))?\/?(?:\?(.*?))?(?:#(.*?))?$/.exec(line);
|
||||
password = decodeURIComponent(password);
|
||||
port = parseInt(`${port}`, 10);
|
||||
if (isNaN(port)) {
|
||||
port = 443;
|
||||
}
|
||||
password = decodeURIComponent(password);
|
||||
if (name != null) {
|
||||
name = decodeURIComponent(name);
|
||||
}
|
||||
name = name ?? `AnyTLS ${server}:${port}`;
|
||||
|
||||
const proxy = {
|
||||
type: 'anytls',
|
||||
name,
|
||||
server,
|
||||
port,
|
||||
password,
|
||||
};
|
||||
|
||||
for (const addon of addons.split('&')) {
|
||||
let [key, value] = addon.split('=');
|
||||
key = key.replace(/_/g, '-');
|
||||
value = decodeURIComponent(value);
|
||||
if (['alpn'].includes(key)) {
|
||||
proxy[key] = value ? value.split(',') : undefined;
|
||||
} else if (['insecure'].includes(key)) {
|
||||
proxy['skip-cert-verify'] = /(TRUE)|1/i.test(value);
|
||||
} else if (['udp'].includes(key)) {
|
||||
proxy[key] = /(TRUE)|1/i.test(value);
|
||||
} else {
|
||||
proxy[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return proxy;
|
||||
@ -823,7 +584,6 @@ function URI_Hysteria2() {
|
||||
] = /^(.*?)@(.*?)(:((\d+(-\d+)?)([,;]\d+(-\d+)?)*))?\/?(\?(.*?))?(?:#(.*?))?$/.exec(
|
||||
line,
|
||||
);
|
||||
|
||||
/* eslint-enable no-unused-vars */
|
||||
if (/^\d+$/.test(port)) {
|
||||
port = parseInt(`${port}`, 10);
|
||||
@ -867,23 +627,12 @@ function URI_Hysteria2() {
|
||||
if (params.obfs && params.obfs !== 'none') {
|
||||
proxy.obfs = params.obfs;
|
||||
}
|
||||
if (params.mport) {
|
||||
proxy.ports = params.mport;
|
||||
}
|
||||
|
||||
proxy.ports = params.mport;
|
||||
proxy['obfs-password'] = params['obfs-password'];
|
||||
proxy['skip-cert-verify'] = /(TRUE)|1/i.test(params.insecure);
|
||||
proxy.tfo = /(TRUE)|1/i.test(params.fastopen);
|
||||
proxy['tls-fingerprint'] = params.pinSHA256;
|
||||
let hop_interval = params['hop-interval'] || params['hop_interval'];
|
||||
|
||||
if (/^\d+$/.test(hop_interval)) {
|
||||
proxy['hop-interval'] = parseInt(`${hop_interval}`, 10);
|
||||
}
|
||||
let keepalive = params['keepalive'];
|
||||
|
||||
if (/^\d+$/.test(keepalive)) {
|
||||
proxy['keepalive'] = parseInt(`${keepalive}`, 10);
|
||||
}
|
||||
|
||||
return proxy;
|
||||
};
|
||||
@ -966,11 +715,8 @@ function URI_TUIC() {
|
||||
const parse = (line) => {
|
||||
line = line.split(/tuic:\/\//)[1];
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
let [__, auth, server, port, addons = '', name] =
|
||||
/^(.*?)@(.*?)(?::(\d+))?\/?(?:\?(.*?))?(?:#(.*?))?$/.exec(line);
|
||||
auth = decodeURIComponent(auth);
|
||||
let [uuid, ...passwordParts] = auth.split(':');
|
||||
let password = passwordParts.join(':');
|
||||
let [__, uuid, password, server, ___, port, ____, addons = '', name] =
|
||||
/^(.*?):(.*?)@(.*?)(:(\d+))?\/?(\?(.*?))?(?:#(.*?))?$/.exec(line);
|
||||
port = parseInt(`${port}`, 10);
|
||||
if (isNaN(port)) {
|
||||
port = 443;
|
||||
@ -992,19 +738,14 @@ function URI_TUIC() {
|
||||
|
||||
for (const addon of addons.split('&')) {
|
||||
let [key, value] = addon.split('=');
|
||||
key = key.replace(/_/g, '-');
|
||||
key = key.replace(/_/, '-');
|
||||
value = decodeURIComponent(value);
|
||||
if (['alpn'].includes(key)) {
|
||||
proxy[key] = value ? value.split(',') : undefined;
|
||||
} else if (['allow-insecure'].includes(key)) {
|
||||
proxy['skip-cert-verify'] = /(TRUE)|1/i.test(value);
|
||||
} else if (['fast-open'].includes(key)) {
|
||||
proxy.tfo = true;
|
||||
} else if (['disable-sni', 'reduce-rtt'].includes(key)) {
|
||||
proxy[key] = /(TRUE)|1/i.test(value);
|
||||
} else if (key === 'congestion-control') {
|
||||
proxy['congestion-controller'] = value;
|
||||
delete proxy[key];
|
||||
} else {
|
||||
proxy[key] = value;
|
||||
}
|
||||
@ -1140,9 +881,6 @@ function Clash_All() {
|
||||
const proxy = JSON.parse(line);
|
||||
if (
|
||||
![
|
||||
'anytls',
|
||||
'mieru',
|
||||
'juicity',
|
||||
'ss',
|
||||
'ssr',
|
||||
'vmess',
|
||||
@ -1642,8 +1380,6 @@ function isIP(ip) {
|
||||
}
|
||||
|
||||
export default [
|
||||
URI_PROXY(),
|
||||
URI_SOCKS(),
|
||||
URI_SS(),
|
||||
URI_SSR(),
|
||||
URI_VMess(),
|
||||
@ -1653,7 +1389,6 @@ export default [
|
||||
URI_Hysteria(),
|
||||
URI_Hysteria2(),
|
||||
URI_Trojan(),
|
||||
URI_AnyTLS(),
|
||||
Clash_All(),
|
||||
Surge_Direct(),
|
||||
Surge_SSH(),
|
||||
|
@ -39,12 +39,12 @@ start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2
|
||||
return proxy;
|
||||
}
|
||||
|
||||
shadowsocksr = tag equals "shadowsocksr"i address method password (ssr_protocol/ssr_protocol_param/obfs_ssr/obfs_ssr_param/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/others)*{
|
||||
shadowsocksr = tag equals "shadowsocksr"i address method password (ssr_protocol/ssr_protocol_param/obfs_ssr/obfs_ssr_param/obfs_host/obfs_uri/fast_open/udp_relay/others)*{
|
||||
proxy.type = "ssr";
|
||||
// handle ssr obfs
|
||||
proxy.obfs = obfs.type;
|
||||
}
|
||||
shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs_hostv)? (obfs_ss/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/others)* {
|
||||
shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs_hostv)? (obfs_ss/obfs_host/obfs_uri/fast_open/udp_relay/others)* {
|
||||
proxy.type = "ss";
|
||||
// handle ss obfs
|
||||
if (obfs.type == "http" || obfs.type === "tls") {
|
||||
@ -54,31 +54,31 @@ shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs
|
||||
$set(proxy, "plugin-opts.path", obfs.path);
|
||||
}
|
||||
}
|
||||
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* {
|
||||
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/others)* {
|
||||
proxy.type = "vmess";
|
||||
proxy.cipher = proxy.cipher || "none";
|
||||
proxy.alterId = proxy.alterId || 0;
|
||||
handleTransport();
|
||||
}
|
||||
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/flow/public_key/short_id/block_quic/others)* {
|
||||
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "vless";
|
||||
handleTransport();
|
||||
}
|
||||
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "trojan";
|
||||
handleTransport();
|
||||
}
|
||||
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/ip_mode/block_quic/others)* {
|
||||
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/others)* {
|
||||
proxy.type = "hysteria2";
|
||||
}
|
||||
https = tag equals "https"i address (username password)? (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
https = tag equals "https"i address (username password)? (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "http";
|
||||
proxy.tls = true;
|
||||
}
|
||||
http = tag equals "http"i address (username password)? (fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
http = tag equals "http"i address (username password)? (fast_open/udp_relay/others)* {
|
||||
proxy.type = "http";
|
||||
}
|
||||
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "socks5";
|
||||
}
|
||||
|
||||
@ -169,31 +169,19 @@ ssr_protocol_param = comma "protocol-param" equals param:$[^=,]+ { proxy["protoc
|
||||
|
||||
vmess_alterId = comma "alterId" equals alterId:$[0-9]+ { proxy.alterId = parseInt(alterId); }
|
||||
|
||||
udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
|
||||
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
||||
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
||||
|
||||
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
||||
tls_host = comma sni:("tls-name"/"sni") equals host:domain { proxy.sni = host; }
|
||||
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
|
||||
tls_cert_sha256 = comma "tls-cert-sha256" equals match:[^,]+ { proxy["tls-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals match:[^,]+ { proxy["tls-pubkey-sha256"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
|
||||
flow = comma "flow" equals match:[^,]+ { proxy["flow"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
public_key = comma "public-key" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["public-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
short_id = comma "short-id" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["short-id"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
|
||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
||||
ip_mode = comma "ip-mode" equals match:[^,]+ { proxy["ip-version"] = match.join(""); }
|
||||
|
||||
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
||||
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
|
||||
salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join(""); proxy.obfs = 'salamander'; }
|
||||
|
||||
block_quic = comma "block-quic" equals flag:bool { if(flag) proxy["block-quic"] = "on"; else proxy["block-quic"] = "off"; }
|
||||
|
||||
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
|
||||
comma = _ "," _
|
||||
equals = _ "=" _
|
||||
|
@ -37,12 +37,12 @@ start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2
|
||||
return proxy;
|
||||
}
|
||||
|
||||
shadowsocksr = tag equals "shadowsocksr"i address method password (ssr_protocol/ssr_protocol_param/obfs_ssr/obfs_ssr_param/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/others)*{
|
||||
shadowsocksr = tag equals "shadowsocksr"i address method password (ssr_protocol/ssr_protocol_param/obfs_ssr/obfs_ssr_param/obfs_host/obfs_uri/fast_open/udp_relay/others)*{
|
||||
proxy.type = "ssr";
|
||||
// handle ssr obfs
|
||||
proxy.obfs = obfs.type;
|
||||
}
|
||||
shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs_hostv)? (obfs_ss/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/others)* {
|
||||
shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs_hostv)? (obfs_ss/obfs_host/obfs_uri/fast_open/udp_relay/others)* {
|
||||
proxy.type = "ss";
|
||||
// handle ss obfs
|
||||
if (obfs.type == "http" || obfs.type === "tls") {
|
||||
@ -52,31 +52,31 @@ shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs
|
||||
$set(proxy, "plugin-opts.path", obfs.path);
|
||||
}
|
||||
}
|
||||
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* {
|
||||
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/others)* {
|
||||
proxy.type = "vmess";
|
||||
proxy.cipher = proxy.cipher || "none";
|
||||
proxy.alterId = proxy.alterId || 0;
|
||||
handleTransport();
|
||||
}
|
||||
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/flow/public_key/short_id/block_quic/others)* {
|
||||
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "vless";
|
||||
handleTransport();
|
||||
}
|
||||
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "trojan";
|
||||
handleTransport();
|
||||
}
|
||||
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/ip_mode/block_quic/others)* {
|
||||
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/others)* {
|
||||
proxy.type = "hysteria2";
|
||||
}
|
||||
https = tag equals "https"i address (username password)? (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
https = tag equals "https"i address (username password)? (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "http";
|
||||
proxy.tls = true;
|
||||
}
|
||||
http = tag equals "http"i address (username password)? (fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
http = tag equals "http"i address (username password)? (fast_open/udp_relay/others)* {
|
||||
proxy.type = "http";
|
||||
}
|
||||
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
|
||||
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||
proxy.type = "socks5";
|
||||
}
|
||||
|
||||
@ -167,31 +167,19 @@ ssr_protocol_param = comma "protocol-param" equals param:$[^=,]+ { proxy["protoc
|
||||
|
||||
vmess_alterId = comma "alterId" equals alterId:$[0-9]+ { proxy.alterId = parseInt(alterId); }
|
||||
|
||||
udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
|
||||
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
||||
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
||||
|
||||
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
||||
tls_host = comma sni:("tls-name"/"sni") equals host:domain { proxy.sni = host; }
|
||||
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
|
||||
tls_cert_sha256 = comma "tls-cert-sha256" equals match:[^,]+ { proxy["tls-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals match:[^,]+ { proxy["tls-pubkey-sha256"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
|
||||
flow = comma "flow" equals match:[^,]+ { proxy["flow"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
public_key = comma "public-key" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["public-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
short_id = comma "short-id" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["short-id"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||
|
||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
||||
ip_mode = comma "ip-mode" equals match:[^,]+ { proxy["ip-version"] = match.join(""); }
|
||||
|
||||
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
||||
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
|
||||
salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join(""); proxy.obfs = 'salamander'; }
|
||||
|
||||
block_quic = comma "block-quic" equals flag:bool { if(flag) proxy["block-quic"] = "on"; else proxy["block-quic"] = "off"; }
|
||||
|
||||
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
|
||||
comma = _ "," _
|
||||
equals = _ "=" _
|
||||
|
@ -49,7 +49,7 @@ trojan = "trojan" equals address
|
||||
}
|
||||
|
||||
shadowsocks = "shadowsocks" equals address
|
||||
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp_new/fast_open/tag/server_check_url/others)* {
|
||||
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp/fast_open/tag/server_check_url/others)* {
|
||||
if (proxy.protocol || proxy.type === "ssr") {
|
||||
proxy.type = "ssr";
|
||||
if (!proxy.protocol) {
|
||||
@ -86,10 +86,10 @@ vmess = "vmess" equals address
|
||||
(uuid/method/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/obfs/obfs_host/obfs_uri/udp_relay/udp_over_tcp/fast_open/aead/server_check_url/others)* {
|
||||
proxy.type = "vmess";
|
||||
proxy.cipher = proxy.cipher || "none";
|
||||
if (proxy.aead === false) {
|
||||
proxy.alterId = 1;
|
||||
} else {
|
||||
if (proxy.aead) {
|
||||
proxy.alterId = 0;
|
||||
} else {
|
||||
proxy.alterId = proxy.alterId || 0;
|
||||
}
|
||||
handleObfs();
|
||||
}
|
||||
@ -145,20 +145,18 @@ port = digits:[0-9]+ {
|
||||
}
|
||||
}
|
||||
|
||||
username = comma "username" equals username:[^,]+ { proxy.username = username.join("").trim(); }
|
||||
password = comma "password" equals password:[^,]+ { proxy.password = password.join("").trim(); }
|
||||
uuid = comma "password" equals uuid:[^,]+ { proxy.uuid = uuid.join("").trim(); }
|
||||
username = comma "username" equals username:[^=,]+ { proxy.username = username.join("").trim(); }
|
||||
password = comma "password" equals password:[^=,]+ { proxy.password = password.join("").trim(); }
|
||||
uuid = comma "password" equals uuid:[^=,]+ { proxy.uuid = uuid.join("").trim(); }
|
||||
|
||||
method = comma "method" equals cipher:cipher {
|
||||
proxy.cipher = cipher;
|
||||
};
|
||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"none"/"rc2-cfb"/"rc4-md5-6"/"rc4-md5"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
|
||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"none"/"rc2-cfb"/"rc4-md5-6"/"rc4-md5"/"salsa20"/"xchacha20-ietf-poly1305");
|
||||
aead = comma "aead" equals flag:bool { proxy.aead = flag; }
|
||||
|
||||
udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
|
||||
udp_over_tcp = comma "udp-over-tcp" equals flag:bool { throw new Error("UDP over TCP is not supported"); }
|
||||
udp_over_tcp_new = comma "udp-over-tcp" equals param:$[^=,]+ { if (param === "sp.v1") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 1; } else if (param === "sp.v2") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 2; } else if (param === "true") { proxy["_ssr_python_uot"] = true; } else { throw new Error("Invalid value for udp-over-tcp"); } }
|
||||
|
||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||
|
||||
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
||||
|
@ -47,7 +47,7 @@ trojan = "trojan" equals address
|
||||
}
|
||||
|
||||
shadowsocks = "shadowsocks" equals address
|
||||
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp_new/fast_open/tag/server_check_url/others)* {
|
||||
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp/fast_open/tag/server_check_url/others)* {
|
||||
if (proxy.protocol || proxy.type === "ssr") {
|
||||
proxy.type = "ssr";
|
||||
if (!proxy.protocol) {
|
||||
@ -84,10 +84,10 @@ vmess = "vmess" equals address
|
||||
(uuid/method/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/obfs/obfs_host/obfs_uri/udp_relay/udp_over_tcp/fast_open/aead/server_check_url/others)* {
|
||||
proxy.type = "vmess";
|
||||
proxy.cipher = proxy.cipher || "none";
|
||||
if (proxy.aead === false) {
|
||||
proxy.alterId = 1;
|
||||
} else {
|
||||
if (proxy.aead) {
|
||||
proxy.alterId = 0;
|
||||
} else {
|
||||
proxy.alterId = proxy.alterId || 0;
|
||||
}
|
||||
handleObfs();
|
||||
}
|
||||
@ -143,20 +143,18 @@ port = digits:[0-9]+ {
|
||||
}
|
||||
}
|
||||
|
||||
username = comma "username" equals username:[^,]+ { proxy.username = username.join("").trim(); }
|
||||
password = comma "password" equals password:[^,]+ { proxy.password = password.join("").trim(); }
|
||||
uuid = comma "password" equals uuid:[^,]+ { proxy.uuid = uuid.join("").trim(); }
|
||||
username = comma "username" equals username:[^=,]+ { proxy.username = username.join("").trim(); }
|
||||
password = comma "password" equals password:[^=,]+ { proxy.password = password.join("").trim(); }
|
||||
uuid = comma "password" equals uuid:[^=,]+ { proxy.uuid = uuid.join("").trim(); }
|
||||
|
||||
method = comma "method" equals cipher:cipher {
|
||||
proxy.cipher = cipher;
|
||||
};
|
||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"none"/"rc2-cfb"/"rc4-md5-6"/"rc4-md5"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
|
||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"none"/"rc2-cfb"/"rc4-md5-6"/"rc4-md5"/"salsa20"/"xchacha20-ietf-poly1305");
|
||||
aead = comma "aead" equals flag:bool { proxy.aead = flag; }
|
||||
|
||||
udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
|
||||
udp_over_tcp = comma "udp-over-tcp" equals flag:bool { throw new Error("UDP over TCP is not supported"); }
|
||||
udp_over_tcp_new = comma "udp-over-tcp" equals param:$[^=,]+ { if (param === "sp.v1") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 1; } else if (param === "sp.v2") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 2; } else if (param === "true") { proxy["_ssr_python_uot"] = true; } else { throw new Error("Invalid value for udp-over-tcp"); } }
|
||||
|
||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||
|
||||
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
||||
|
@ -41,7 +41,7 @@ start = (shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v
|
||||
return proxy;
|
||||
}
|
||||
|
||||
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/udp_port/others)* {
|
||||
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/udp_port/others)* {
|
||||
proxy.type = "ss";
|
||||
// handle obfs
|
||||
if (obfs.type == "http" || obfs.type === "tls") {
|
||||
@ -52,37 +52,36 @@ shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/
|
||||
}
|
||||
handleShadowTLS();
|
||||
}
|
||||
vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_path/ws_headers/method/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/tls_fingerprint/tls_verification/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_path/ws_headers/method/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/tls_fingerprint/tls_verification/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "vmess";
|
||||
proxy.cipher = proxy.cipher || "none";
|
||||
// Surfboard 与 Surge 默认不一致, 不管 Surfboard https://getsurfboard.com/docs/profile-format/proxy/external-proxy/vmess
|
||||
if (proxy.aead) {
|
||||
proxy.alterId = 0;
|
||||
} else {
|
||||
proxy.alterId = 1;
|
||||
proxy.alterId = proxy.alterId || 0;
|
||||
}
|
||||
handleWebsocket();
|
||||
handleShadowTLS();
|
||||
}
|
||||
trojan = tag equals "trojan" address (passwordk/ws/ws_path/ws_headers/tls/sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
trojan = tag equals "trojan" address (passwordk/ws/ws_path/ws_headers/tls/sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "trojan";
|
||||
handleWebsocket();
|
||||
handleShadowTLS();
|
||||
}
|
||||
https = tag equals "https" address (username password)? (usernamek passwordk)? (sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
https = tag equals "https" address (username password)? (usernamek passwordk)? (sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "http";
|
||||
proxy.tls = true;
|
||||
handleShadowTLS();
|
||||
}
|
||||
http = tag equals "http" address (username password)? (usernamek passwordk)? (ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
http = tag equals "http" address (username password)? (usernamek passwordk)? (ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "http";
|
||||
handleShadowTLS();
|
||||
}
|
||||
ssh = tag equals "ssh" address (username password)? (usernamek passwordk)? (server_fingerprint/idle_timeout/private_key/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
ssh = tag equals "ssh" address (username password)? (usernamek passwordk)? (server_fingerprint/idle_timeout/private_key/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "ssh";
|
||||
handleShadowTLS();
|
||||
}
|
||||
snell = tag equals "snell" address (snell_version/snell_psk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/reuse/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
snell = tag equals "snell" address (snell_version/snell_psk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/reuse/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "snell";
|
||||
// handle obfs
|
||||
if (obfs.type == "http" || obfs.type === "tls") {
|
||||
@ -105,20 +104,20 @@ wireguard = tag equals "wireguard" (section_name/no_error_alert/ip_version/under
|
||||
proxy.type = "wireguard-surge";
|
||||
handleShadowTLS();
|
||||
}
|
||||
hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/fast_open/tfo/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||
hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||
proxy.type = "hysteria2";
|
||||
handleShadowTLS();
|
||||
}
|
||||
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "socks5";
|
||||
handleShadowTLS();
|
||||
}
|
||||
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "socks5";
|
||||
proxy.tls = true;
|
||||
handleShadowTLS();
|
||||
}
|
||||
direct = tag equals "direct" (udp_relay/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/block_quic/others)* {
|
||||
direct = tag equals "direct" (ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/block_quic/others)* {
|
||||
proxy.type = "direct";
|
||||
}
|
||||
|
||||
@ -247,7 +246,7 @@ block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match
|
||||
udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
|
||||
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
||||
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
|
||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
||||
token = comma "token" equals match:[^,]+ { proxy.token = match.join(""); }
|
||||
alpn = comma "alpn" equals match:[^,]+ { proxy.alpn = match.join(""); }
|
||||
uuidk = comma "uuid" equals match:[^,]+ { proxy.uuid = match.join(""); }
|
||||
|
@ -39,7 +39,7 @@ start = (shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v
|
||||
return proxy;
|
||||
}
|
||||
|
||||
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/udp_port/others)* {
|
||||
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/udp_port/others)* {
|
||||
proxy.type = "ss";
|
||||
// handle obfs
|
||||
if (obfs.type == "http" || obfs.type === "tls") {
|
||||
@ -50,37 +50,36 @@ shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/
|
||||
}
|
||||
handleShadowTLS();
|
||||
}
|
||||
vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_path/ws_headers/method/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/tls_fingerprint/tls_verification/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_path/ws_headers/method/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/tls_fingerprint/tls_verification/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "vmess";
|
||||
proxy.cipher = proxy.cipher || "none";
|
||||
// Surfboard 与 Surge 默认不一致, 不管 Surfboard https://getsurfboard.com/docs/profile-format/proxy/external-proxy/vmess
|
||||
if (proxy.aead) {
|
||||
proxy.alterId = 0;
|
||||
} else {
|
||||
proxy.alterId = 1;
|
||||
proxy.alterId = proxy.alterId || 0;
|
||||
}
|
||||
handleWebsocket();
|
||||
handleShadowTLS();
|
||||
}
|
||||
trojan = tag equals "trojan" address (passwordk/ws/ws_path/ws_headers/tls/sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
trojan = tag equals "trojan" address (passwordk/ws/ws_path/ws_headers/tls/sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "trojan";
|
||||
handleWebsocket();
|
||||
handleShadowTLS();
|
||||
}
|
||||
https = tag equals "https" address (username password)? (usernamek passwordk)? (sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
https = tag equals "https" address (username password)? (usernamek passwordk)? (sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "http";
|
||||
proxy.tls = true;
|
||||
handleShadowTLS();
|
||||
}
|
||||
http = tag equals "http" address (username password)? (usernamek passwordk)? (ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
http = tag equals "http" address (username password)? (usernamek passwordk)? (ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "http";
|
||||
handleShadowTLS();
|
||||
}
|
||||
ssh = tag equals "ssh" address (username password)? (usernamek passwordk)? (server_fingerprint/idle_timeout/private_key/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
ssh = tag equals "ssh" address (username password)? (usernamek passwordk)? (server_fingerprint/idle_timeout/private_key/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "ssh";
|
||||
handleShadowTLS();
|
||||
}
|
||||
snell = tag equals "snell" address (snell_version/snell_psk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/reuse/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
snell = tag equals "snell" address (snell_version/snell_psk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/reuse/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "snell";
|
||||
// handle obfs
|
||||
if (obfs.type == "http" || obfs.type === "tls") {
|
||||
@ -107,16 +106,16 @@ hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying
|
||||
proxy.type = "hysteria2";
|
||||
handleShadowTLS();
|
||||
}
|
||||
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "socks5";
|
||||
handleShadowTLS();
|
||||
}
|
||||
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||
proxy.type = "socks5";
|
||||
proxy.tls = true;
|
||||
handleShadowTLS();
|
||||
}
|
||||
direct = tag equals "direct" (udp_relay/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/block_quic/others)* {
|
||||
direct = tag equals "direct" (ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/block_quic/others)* {
|
||||
proxy.type = "direct";
|
||||
}
|
||||
address = comma server:server comma port:port {
|
||||
@ -244,7 +243,7 @@ block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match
|
||||
udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
|
||||
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
||||
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
|
||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
||||
token = comma "token" equals match:[^,]+ { proxy.token = match.join(""); }
|
||||
alpn = comma "alpn" equals match:[^,]+ { proxy.alpn = match.join(""); }
|
||||
uuidk = comma "uuid" equals match:[^,]+ { proxy.uuid = match.join(""); }
|
||||
|
@ -80,9 +80,6 @@ port = digits:[0-9]+ {
|
||||
}
|
||||
|
||||
params = "?" head:param tail:("&"@param)* {
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
params[key] = decodeURIComponent(value);
|
||||
}
|
||||
proxy["skip-cert-verify"] = toBool(params["allowInsecure"]);
|
||||
proxy.sni = params["sni"] || params["peer"];
|
||||
proxy['client-fingerprint'] = params.fp;
|
||||
@ -118,27 +115,6 @@ params = "?" head:param tail:("&"@param)* {
|
||||
$set(proxy, proxy.network+"-opts.v2ray-http-upgrade-fast-open", true);
|
||||
}
|
||||
}
|
||||
if (['reality'].includes(params.security)) {
|
||||
const opts = {};
|
||||
if (params.pbk) {
|
||||
opts['public-key'] = params.pbk;
|
||||
}
|
||||
if (params.sid) {
|
||||
opts['short-id'] = params.sid;
|
||||
}
|
||||
if (params.spx) {
|
||||
opts['_spider-x'] = params.spx;
|
||||
}
|
||||
if (params.mode) {
|
||||
proxy._mode = params.mode;
|
||||
}
|
||||
if (params.extra) {
|
||||
proxy._extra = params.extra;
|
||||
}
|
||||
if (Object.keys(opts).length > 0) {
|
||||
$set(proxy, params.security+"-opts", opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proxy.udp = toBool(params["udp"]);
|
||||
|
@ -78,9 +78,6 @@ port = digits:[0-9]+ {
|
||||
}
|
||||
|
||||
params = "?" head:param tail:("&"@param)* {
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
params[key] = decodeURIComponent(value);
|
||||
}
|
||||
proxy["skip-cert-verify"] = toBool(params["allowInsecure"]);
|
||||
proxy.sni = params["sni"] || params["peer"];
|
||||
proxy['client-fingerprint'] = params.fp;
|
||||
@ -116,27 +113,6 @@ params = "?" head:param tail:("&"@param)* {
|
||||
$set(proxy, proxy.network+"-opts.v2ray-http-upgrade-fast-open", true);
|
||||
}
|
||||
}
|
||||
if (['reality'].includes(params.security)) {
|
||||
const opts = {};
|
||||
if (params.pbk) {
|
||||
opts['public-key'] = params.pbk;
|
||||
}
|
||||
if (params.sid) {
|
||||
opts['short-id'] = params.sid;
|
||||
}
|
||||
if (params.spx) {
|
||||
opts['_spider-x'] = params.spx;
|
||||
}
|
||||
if (params.mode) {
|
||||
proxy._mode = params.mode;
|
||||
}
|
||||
if (params.extra) {
|
||||
proxy._extra = params.extra;
|
||||
}
|
||||
if (Object.keys(opts).length > 0) {
|
||||
$set(proxy, params.security+"-opts", opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proxy.udp = toBool(params["udp"]);
|
||||
|
@ -1,6 +1,5 @@
|
||||
import { safeLoad } from '@/utils/yaml';
|
||||
import { Base64 } from 'js-base64';
|
||||
import $ from '@/core/app';
|
||||
|
||||
function HTML() {
|
||||
const name = 'HTML';
|
||||
@ -16,7 +15,6 @@ function Base64Encoded() {
|
||||
const keys = [
|
||||
'dm1lc3M', // vmess
|
||||
'c3NyOi8v', // ssr://
|
||||
'c29ja3M6Ly', // socks://
|
||||
'dHJvamFu', // trojan
|
||||
'c3M6Ly', // ss:/
|
||||
'c3NkOi8v', // ssd://
|
||||
@ -37,35 +35,8 @@ function Base64Encoded() {
|
||||
);
|
||||
};
|
||||
const parse = function (raw) {
|
||||
const decoded = Base64.decode(raw);
|
||||
if (!/^\w+(:\/\/|\s*?=\s*?)\w+/m.test(decoded)) {
|
||||
$.error(
|
||||
`Base64 Pre-processor error: decoded line does not start with protocol`,
|
||||
);
|
||||
return raw;
|
||||
}
|
||||
|
||||
return decoded;
|
||||
};
|
||||
return { name, test, parse };
|
||||
}
|
||||
|
||||
function fallbackBase64Encoded() {
|
||||
const name = 'Fallback Base64 Pre-processor';
|
||||
|
||||
const test = function (raw) {
|
||||
return true;
|
||||
};
|
||||
const parse = function (raw) {
|
||||
const decoded = Base64.decode(raw);
|
||||
if (!/^\w+(:\/\/|\s*?=\s*?)\w+/m.test(decoded)) {
|
||||
$.error(
|
||||
`Fallback Base64 Pre-processor error: decoded line does not start with protocol`,
|
||||
);
|
||||
return raw;
|
||||
}
|
||||
|
||||
return decoded;
|
||||
raw = Base64.decode(raw);
|
||||
return raw;
|
||||
};
|
||||
return { name, test, parse };
|
||||
}
|
||||
@ -77,50 +48,43 @@ function Clash() {
|
||||
const content = safeLoad(raw);
|
||||
return content.proxies && Array.isArray(content.proxies);
|
||||
};
|
||||
const parse = function (raw, includeProxies) {
|
||||
const parse = function (raw) {
|
||||
// Clash YAML format
|
||||
|
||||
// 防止 VLESS节点 reality-opts 选项中的 short-id 被解析成 Infinity
|
||||
// 匹配 short-id 冒号后面的值(包含空格和引号)
|
||||
const afterReplace = raw.replace(
|
||||
/short-id:([ \t]*[^#\n,}]*)/g,
|
||||
/short-id:([ ]*[^,\n}]*)/g,
|
||||
(matched, value) => {
|
||||
const afterTrim = value.trim();
|
||||
|
||||
// 为空
|
||||
if (!afterTrim || afterTrim === '') {
|
||||
return 'short-id: ""';
|
||||
}
|
||||
|
||||
// 是否被引号包裹
|
||||
if (/^(['"]).*\1$/.test(afterTrim)) {
|
||||
return `short-id: ${afterTrim}`;
|
||||
} else if (['null'].includes(afterTrim)) {
|
||||
return `short-id: ${afterTrim}`;
|
||||
} else {
|
||||
return `short-id: "${afterTrim}"`;
|
||||
}
|
||||
},
|
||||
const afterTrim = value.trim();
|
||||
|
||||
// 为空
|
||||
if (!afterTrim || afterTrim === '') {
|
||||
return 'short-id: ""'
|
||||
}
|
||||
|
||||
// 是否被引号包裹
|
||||
if (/^(['"]).*\1$/.test(afterTrim)) {
|
||||
return `short-id: ${afterTrim}`;
|
||||
} else {
|
||||
return `short-id: "${afterTrim}"`
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const {
|
||||
proxies,
|
||||
'global-client-fingerprint': globalClientFingerprint,
|
||||
} = safeLoad(afterReplace);
|
||||
return (
|
||||
(includeProxies ? 'proxies:\n' : '') +
|
||||
proxies
|
||||
.map((p) => {
|
||||
// https://github.com/MetaCubeX/mihomo/blob/Alpha/docs/config.yaml#L73C1-L73C26
|
||||
if (globalClientFingerprint && !p['client-fingerprint']) {
|
||||
p['client-fingerprint'] = globalClientFingerprint;
|
||||
}
|
||||
return `${includeProxies ? ' - ' : ''}${JSON.stringify(
|
||||
p,
|
||||
)}\n`;
|
||||
})
|
||||
.join('')
|
||||
);
|
||||
return proxies
|
||||
.map((p) => {
|
||||
// https://github.com/MetaCubeX/mihomo/blob/Alpha/docs/config.yaml#L73C1-L73C26
|
||||
if (globalClientFingerprint && !p['client-fingerprint']) {
|
||||
p['client-fingerprint'] = globalClientFingerprint;
|
||||
}
|
||||
return JSON.stringify(p);
|
||||
})
|
||||
.join('\n');
|
||||
};
|
||||
return { name, test, parse };
|
||||
}
|
||||
@ -183,11 +147,4 @@ function FullConfig() {
|
||||
return { name, test, parse };
|
||||
}
|
||||
|
||||
export default [
|
||||
HTML(),
|
||||
Clash(),
|
||||
Base64Encoded(),
|
||||
SSD(),
|
||||
FullConfig(),
|
||||
fallbackBase64Encoded(),
|
||||
];
|
||||
export default [HTML(), Clash(), Base64Encoded(), SSD(), FullConfig()];
|
||||
|
@ -10,7 +10,6 @@ import { hex_md5 } from '@/vendor/md5';
|
||||
import { ProxyUtils } from '@/core/proxy-utils';
|
||||
import { produceArtifact } from '@/restful/sync';
|
||||
import { SETTINGS_KEY } from '@/constants';
|
||||
import YAML from '@/utils/yaml';
|
||||
|
||||
import env from '@/utils/env';
|
||||
import {
|
||||
@ -20,49 +19,8 @@ import {
|
||||
validCheck,
|
||||
flowTransfer,
|
||||
getRmainingDays,
|
||||
normalizeFlowHeader,
|
||||
} from '@/utils/flow';
|
||||
|
||||
function isObject(item) {
|
||||
return item && typeof item === 'object' && !Array.isArray(item);
|
||||
}
|
||||
function trimWrap(str) {
|
||||
if (str.startsWith('<') && str.endsWith('>')) {
|
||||
return str.slice(1, -1);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
function deepMerge(target, _other) {
|
||||
const other = typeof _other === 'string' ? JSON.parse(_other) : _other;
|
||||
for (const key in other) {
|
||||
if (isObject(other[key])) {
|
||||
if (key.endsWith('!')) {
|
||||
const k = trimWrap(key.slice(0, -1));
|
||||
target[k] = other[key];
|
||||
} else {
|
||||
const k = trimWrap(key);
|
||||
if (!target[k]) Object.assign(target, { [k]: {} });
|
||||
deepMerge(target[k], other[k]);
|
||||
}
|
||||
} else if (Array.isArray(other[key])) {
|
||||
if (key.startsWith('+')) {
|
||||
const k = trimWrap(key.slice(1));
|
||||
if (!target[k]) Object.assign(target, { [k]: [] });
|
||||
target[k] = [...other[key], ...target[k]];
|
||||
} else if (key.endsWith('+')) {
|
||||
const k = trimWrap(key.slice(0, -1));
|
||||
if (!target[k]) Object.assign(target, { [k]: [] });
|
||||
target[k] = [...target[k], ...other[key]];
|
||||
} else {
|
||||
const k = trimWrap(key);
|
||||
Object.assign(target, { [k]: other[key] });
|
||||
}
|
||||
} else {
|
||||
Object.assign(target, { [key]: other[key] });
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
/**
|
||||
The rule "(name CONTAINS "🇨🇳") AND (port IN [80, 443])" can be expressed as follows:
|
||||
{
|
||||
@ -284,15 +242,7 @@ function SortOperator(order = 'asc') {
|
||||
}
|
||||
|
||||
// sort by regex
|
||||
function RegexSortOperator(input) {
|
||||
const order = input.order || 'asc';
|
||||
let expressions = input.expressions;
|
||||
if (Array.isArray(input)) {
|
||||
expressions = input;
|
||||
}
|
||||
if (!Array.isArray(expressions)) {
|
||||
expressions = [];
|
||||
}
|
||||
function RegexSortOperator(expressions) {
|
||||
return {
|
||||
name: 'Regex Sort Operator',
|
||||
func: (proxies) => {
|
||||
@ -303,13 +253,8 @@ function RegexSortOperator(input) {
|
||||
if (oA && !oB) return -1;
|
||||
if (oB && !oA) return 1;
|
||||
if (oA && oB) return oA < oB ? -1 : 1;
|
||||
if (order === 'original') {
|
||||
return 0;
|
||||
} else if (order === 'desc') {
|
||||
return a.name < b.name ? 1 : -1;
|
||||
} else {
|
||||
return a.name < b.name ? -1 : 1;
|
||||
}
|
||||
if ((!oA && !oB) || (oA && oB && oA === oB))
|
||||
return a.name < b.name ? -1 : 1; // fallback to normal sort
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -376,46 +321,6 @@ function ScriptOperator(script, targetPlatform, $arguments, source, $options) {
|
||||
name: 'Script Operator',
|
||||
func: async (proxies) => {
|
||||
let output = proxies;
|
||||
if (output?.$file?.type === 'mihomoProfile') {
|
||||
try {
|
||||
let patch = YAML.safeLoad(script);
|
||||
let config;
|
||||
if (output?.$content) {
|
||||
try {
|
||||
config = YAML.safeLoad(output?.$content);
|
||||
} catch (e) {
|
||||
$.error(e.message ?? e);
|
||||
}
|
||||
}
|
||||
// if (typeof patch !== 'object') patch = {};
|
||||
if (typeof patch !== 'object')
|
||||
throw new Error('patch is not an object');
|
||||
output.$content = ProxyUtils.yaml.safeDump(
|
||||
deepMerge(
|
||||
config ||
|
||||
(output?.$file?.sourceType === 'none'
|
||||
? {}
|
||||
: {
|
||||
proxies: await produceArtifact({
|
||||
type:
|
||||
output?.$file?.sourceType ||
|
||||
'collection',
|
||||
name: output?.$file?.sourceName,
|
||||
platform: 'mihomo',
|
||||
produceType: 'internal',
|
||||
produceOpts: {
|
||||
'delete-underscore-fields': true,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
patch,
|
||||
),
|
||||
);
|
||||
return output;
|
||||
} catch (e) {
|
||||
// console.log(e);
|
||||
}
|
||||
}
|
||||
await (async function () {
|
||||
const operator = createDynamicFunction(
|
||||
'operator',
|
||||
@ -434,34 +339,9 @@ function ScriptOperator(script, targetPlatform, $arguments, source, $options) {
|
||||
'operator',
|
||||
`async function operator(input = []) {
|
||||
if (input && (input.$files || input.$content)) {
|
||||
let { $content, $files, $options, $file } = input
|
||||
if($file.type === 'mihomoProfile') {
|
||||
${script}
|
||||
if(typeof main === 'function') {
|
||||
let config;
|
||||
if ($content) {
|
||||
try {
|
||||
config = ProxyUtils.yaml.safeLoad($content);
|
||||
} catch (e) {
|
||||
console.log(e.message ?? e);
|
||||
}
|
||||
}
|
||||
$content = ProxyUtils.yaml.safeDump(await main(config || ($file.sourceType === 'none' ? {} : {
|
||||
proxies: await produceArtifact({
|
||||
type: $file.sourceType || 'collection',
|
||||
name: $file.sourceName,
|
||||
platform: 'mihomo',
|
||||
produceType: 'internal',
|
||||
produceOpts: {
|
||||
'delete-underscore-fields': true
|
||||
}
|
||||
}),
|
||||
})))
|
||||
}
|
||||
} else {
|
||||
${script}
|
||||
}
|
||||
return { $content, $files, $options, $file }
|
||||
let { $content, $files, $options } = input
|
||||
${script}
|
||||
return { $content, $files, $options }
|
||||
} else {
|
||||
let proxies = input
|
||||
let list = []
|
||||
@ -862,12 +742,7 @@ function UselessFilter() {
|
||||
}
|
||||
|
||||
// filter by regions
|
||||
function RegionFilter(input) {
|
||||
let regions = input?.value || input;
|
||||
if (!Array.isArray(regions)) {
|
||||
regions = [];
|
||||
}
|
||||
const keep = input?.keep ?? true;
|
||||
function RegionFilter(regions) {
|
||||
const REGION_MAP = {
|
||||
HK: '🇭🇰',
|
||||
TW: '🇹🇼',
|
||||
@ -884,8 +759,7 @@ function RegionFilter(input) {
|
||||
// this would be high memory usage
|
||||
return proxies.map((proxy) => {
|
||||
const flag = getFlag(proxy.name);
|
||||
const selected = regions.some((r) => REGION_MAP[r] === flag);
|
||||
return keep ? selected : !selected;
|
||||
return regions.some((r) => REGION_MAP[r] === flag);
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -917,19 +791,11 @@ function buildRegex(str, ...options) {
|
||||
}
|
||||
|
||||
// filter by proxy types
|
||||
function TypeFilter(input) {
|
||||
let types = input?.value || input;
|
||||
if (!Array.isArray(types)) {
|
||||
types = [];
|
||||
}
|
||||
const keep = input?.keep ?? true;
|
||||
function TypeFilter(types) {
|
||||
return {
|
||||
name: 'Type Filter',
|
||||
func: (proxies) => {
|
||||
return proxies.map((proxy) => {
|
||||
const selected = types.some((t) => proxy.type === t);
|
||||
return keep ? selected : !selected;
|
||||
});
|
||||
return proxies.map((proxy) => types.some((t) => proxy.type === t));
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -1129,7 +995,6 @@ function createDynamicFunction(name, script, $arguments, $options) {
|
||||
flowTransfer,
|
||||
validCheck,
|
||||
getRmainingDays,
|
||||
normalizeFlowHeader,
|
||||
};
|
||||
if ($.env.isLoon) {
|
||||
return new Function(
|
||||
@ -1141,10 +1006,6 @@ function createDynamicFunction(name, script, $arguments, $options) {
|
||||
'$httpClient',
|
||||
'$notification',
|
||||
'ProxyUtils',
|
||||
'yaml',
|
||||
'Buffer',
|
||||
'b64d',
|
||||
'b64e',
|
||||
'scriptResourceCache',
|
||||
'flowUtils',
|
||||
'produceArtifact',
|
||||
@ -1162,10 +1023,6 @@ function createDynamicFunction(name, script, $arguments, $options) {
|
||||
// eslint-disable-next-line no-undef
|
||||
$notification,
|
||||
ProxyUtils,
|
||||
ProxyUtils.yaml,
|
||||
ProxyUtils.Buffer,
|
||||
ProxyUtils.Base64.decode,
|
||||
ProxyUtils.Base64.encode,
|
||||
scriptResourceCache,
|
||||
flowUtils,
|
||||
produceArtifact,
|
||||
@ -1178,10 +1035,6 @@ function createDynamicFunction(name, script, $arguments, $options) {
|
||||
'$substore',
|
||||
'lodash',
|
||||
'ProxyUtils',
|
||||
'yaml',
|
||||
'Buffer',
|
||||
'b64d',
|
||||
'b64e',
|
||||
'scriptResourceCache',
|
||||
'flowUtils',
|
||||
'produceArtifact',
|
||||
@ -1193,10 +1046,6 @@ function createDynamicFunction(name, script, $arguments, $options) {
|
||||
$,
|
||||
lodash,
|
||||
ProxyUtils,
|
||||
ProxyUtils.yaml,
|
||||
ProxyUtils.Buffer,
|
||||
ProxyUtils.Base64.decode,
|
||||
ProxyUtils.Base64.encode,
|
||||
scriptResourceCache,
|
||||
flowUtils,
|
||||
produceArtifact,
|
||||
|
@ -1,5 +1,4 @@
|
||||
import { isPresent } from '@/core/proxy-utils/producers/utils';
|
||||
import $ from '@/core/app';
|
||||
|
||||
export default function Clash_Producer() {
|
||||
const type = 'ALL';
|
||||
@ -47,11 +46,6 @@ export default function Clash_Producer() {
|
||||
proxy['reality-opts']))
|
||||
) {
|
||||
return false;
|
||||
} else if (proxy['underlying-proxy'] || proxy['dialer-proxy']) {
|
||||
$.error(
|
||||
`Clash 不支持前置代理字段. 已过滤节点 ${proxy.name}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
@ -87,8 +81,6 @@ export default function Clash_Producer() {
|
||||
proxy['preshared-key'] =
|
||||
proxy['preshared-key'] ?? proxy['pre-shared-key'];
|
||||
proxy['pre-shared-key'] = proxy['preshared-key'];
|
||||
} else if (proxy.type === 'snell' && proxy.version < 3) {
|
||||
delete proxy.udp;
|
||||
} else if (proxy.type === 'vless') {
|
||||
if (isPresent(proxy, 'sni')) {
|
||||
proxy.servername = proxy.sni;
|
||||
@ -147,7 +139,6 @@ export default function Clash_Producer() {
|
||||
'hysteria',
|
||||
'hysteria2',
|
||||
'juicity',
|
||||
'anytls',
|
||||
].includes(proxy.type)
|
||||
) {
|
||||
delete proxy.tls;
|
||||
@ -158,6 +149,11 @@ export default function Clash_Producer() {
|
||||
}
|
||||
delete proxy['tls-fingerprint'];
|
||||
|
||||
if (proxy['underlying-proxy']) {
|
||||
proxy['dialer-proxy'] = proxy['underlying-proxy'];
|
||||
}
|
||||
delete proxy['underlying-proxy'];
|
||||
|
||||
if (isPresent(proxy, 'tls') && typeof proxy.tls !== 'boolean') {
|
||||
delete proxy.tls;
|
||||
}
|
||||
|
@ -8,49 +8,6 @@ export default function ClashMeta_Producer() {
|
||||
if (opts['include-unsupported-proxy']) return true;
|
||||
if (proxy.type === 'snell' && String(proxy.version) === '4') {
|
||||
return false;
|
||||
} else if (['juicity'].includes(proxy.type)) {
|
||||
return false;
|
||||
} else if (
|
||||
['ss'].includes(proxy.type) &&
|
||||
![
|
||||
'aes-128-ctr',
|
||||
'aes-192-ctr',
|
||||
'aes-256-ctr',
|
||||
'aes-128-cfb',
|
||||
'aes-192-cfb',
|
||||
'aes-256-cfb',
|
||||
'aes-128-gcm',
|
||||
'aes-192-gcm',
|
||||
'aes-256-gcm',
|
||||
'aes-128-ccm',
|
||||
'aes-192-ccm',
|
||||
'aes-256-ccm',
|
||||
'aes-128-gcm-siv',
|
||||
'aes-256-gcm-siv',
|
||||
'chacha20-ietf',
|
||||
'chacha20',
|
||||
'xchacha20',
|
||||
'chacha20-ietf-poly1305',
|
||||
'xchacha20-ietf-poly1305',
|
||||
'chacha8-ietf-poly1305',
|
||||
'xchacha8-ietf-poly1305',
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
'2022-blake3-chacha20-poly1305',
|
||||
'lea-128-gcm',
|
||||
'lea-192-gcm',
|
||||
'lea-256-gcm',
|
||||
'rabbit128-poly1305',
|
||||
'aegis-128l',
|
||||
'aegis-256',
|
||||
'aez-384',
|
||||
'deoxys-ii-256-128',
|
||||
'rc4-md5',
|
||||
'none',
|
||||
].includes(proxy.cipher)
|
||||
) {
|
||||
// https://wiki.metacubex.one/config/proxies/ss/#cipher
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
@ -73,10 +30,9 @@ export default function ClashMeta_Producer() {
|
||||
isPresent(proxy, 'cipher') &&
|
||||
![
|
||||
'auto',
|
||||
'none',
|
||||
'zero',
|
||||
'aes-128-gcm',
|
||||
'chacha20-poly1305',
|
||||
'none',
|
||||
].includes(proxy.cipher)
|
||||
) {
|
||||
proxy.cipher = 'auto';
|
||||
@ -128,8 +84,6 @@ export default function ClashMeta_Producer() {
|
||||
proxy['preshared-key'] =
|
||||
proxy['preshared-key'] ?? proxy['pre-shared-key'];
|
||||
proxy['pre-shared-key'] = proxy['preshared-key'];
|
||||
} else if (proxy.type === 'snell' && proxy.version < 3) {
|
||||
delete proxy.udp;
|
||||
} else if (proxy.type === 'vless') {
|
||||
if (isPresent(proxy, 'sni')) {
|
||||
proxy.servername = proxy.sni;
|
||||
@ -146,9 +100,6 @@ export default function ClashMeta_Producer() {
|
||||
password: proxy['shadow-tls-password'],
|
||||
version: proxy['shadow-tls-version'],
|
||||
};
|
||||
delete proxy['shadow-tls-password'];
|
||||
delete proxy['shadow-tls-sni'];
|
||||
delete proxy['shadow-tls-version'];
|
||||
}
|
||||
}
|
||||
|
||||
@ -204,7 +155,6 @@ export default function ClashMeta_Producer() {
|
||||
'hysteria',
|
||||
'hysteria2',
|
||||
'juicity',
|
||||
'anytls',
|
||||
].includes(proxy.type)
|
||||
) {
|
||||
delete proxy.tls;
|
||||
@ -228,7 +178,7 @@ export default function ClashMeta_Producer() {
|
||||
delete proxy.id;
|
||||
delete proxy.resolved;
|
||||
delete proxy['no-resolve'];
|
||||
if (type !== 'internal' || opts['delete-underscore-fields']) {
|
||||
if (type !== 'internal') {
|
||||
for (const key in proxy) {
|
||||
if (proxy[key] == null || /^_/i.test(key)) {
|
||||
delete proxy[key];
|
||||
|
@ -1,12 +1,10 @@
|
||||
import { isPresent } from './utils';
|
||||
|
||||
export default function Egern_Producer() {
|
||||
const type = 'ALL';
|
||||
const produce = (proxies, type) => {
|
||||
const produce = (proxies, type, opts = {}) => {
|
||||
// https://egernapp.com/zh-CN/docs/configuration/proxies
|
||||
const list = proxies
|
||||
.filter((proxy) => {
|
||||
// if (opts['include-unsupported-proxy']) return true;
|
||||
if (opts['include-unsupported-proxy']) return true;
|
||||
if (
|
||||
![
|
||||
'http',
|
||||
@ -16,7 +14,6 @@ export default function Egern_Producer() {
|
||||
'hysteria2',
|
||||
'vless',
|
||||
'vmess',
|
||||
'tuic',
|
||||
].includes(proxy.type) ||
|
||||
(proxy.type === 'ss' &&
|
||||
((proxy.plugin === 'obfs' &&
|
||||
@ -50,12 +47,17 @@ export default function Egern_Producer() {
|
||||
'salsa20',
|
||||
'chacha20',
|
||||
'chacha20-ietf',
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
].includes(proxy.cipher))) ||
|
||||
(proxy.type === 'vmess' &&
|
||||
!['http', 'ws', 'tcp'].includes(proxy.network) &&
|
||||
proxy.network) ||
|
||||
(![
|
||||
'auto',
|
||||
'aes-128-gcm',
|
||||
'chacha20-poly1305',
|
||||
'none',
|
||||
'zero',
|
||||
].includes(proxy.cipher) ||
|
||||
(!['http', 'ws', 'tcp'].includes(proxy.network) &&
|
||||
proxy.network))) ||
|
||||
(proxy.type === 'trojan' &&
|
||||
!['http', 'ws', 'tcp'].includes(proxy.network) &&
|
||||
proxy.network) ||
|
||||
@ -63,26 +65,13 @@ export default function Egern_Producer() {
|
||||
(typeof proxy.flow !== 'undefined' ||
|
||||
proxy['reality-opts'] ||
|
||||
(!['http', 'ws', 'tcp'].includes(proxy.network) &&
|
||||
proxy.network))) ||
|
||||
(proxy.type === 'tuic' &&
|
||||
proxy.token &&
|
||||
proxy.token.length !== 0)
|
||||
proxy.network)))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((proxy) => {
|
||||
const original = { ...proxy };
|
||||
if (proxy.tls && !proxy.sni) {
|
||||
proxy.sni = proxy.server;
|
||||
}
|
||||
const prev_hop =
|
||||
proxy.prev_hop ||
|
||||
proxy['underlying-proxy'] ||
|
||||
proxy['dialer-proxy'] ||
|
||||
proxy.detour;
|
||||
|
||||
if (proxy.type === 'http') {
|
||||
proxy = {
|
||||
type: 'http',
|
||||
@ -123,10 +112,10 @@ export default function Egern_Producer() {
|
||||
proxy.udp || proxy.udp_relay || proxy.udp_relay,
|
||||
next_hop: proxy.next_hop,
|
||||
};
|
||||
if (original.plugin === 'obfs') {
|
||||
proxy.obfs = original['plugin-opts'].mode;
|
||||
proxy.obfs_host = original['plugin-opts'].host;
|
||||
proxy.obfs_uri = original['plugin-opts'].path;
|
||||
if (proxy.plugin === 'obfs') {
|
||||
proxy.obfs = proxy['plugin-opts'].mode;
|
||||
proxy.obfs_host = proxy['plugin-opts'].host;
|
||||
proxy.obfs_uri = proxy['plugin-opts'].path;
|
||||
}
|
||||
} else if (proxy.type === 'hysteria2') {
|
||||
proxy = {
|
||||
@ -141,33 +130,11 @@ export default function Egern_Producer() {
|
||||
next_hop: proxy.next_hop,
|
||||
sni: proxy.sni,
|
||||
skip_tls_verify: proxy['skip-cert-verify'],
|
||||
port_hopping: proxy.ports,
|
||||
port_hopping_interval: proxy['hop-interval'],
|
||||
};
|
||||
if (
|
||||
original['obfs-password'] &&
|
||||
original.obfs == 'salamander'
|
||||
) {
|
||||
if (proxy['obfs-password'] && proxy.obfs == 'salamander') {
|
||||
proxy.obfs = 'salamander';
|
||||
proxy.obfs_password = original['obfs-password'];
|
||||
proxy.obfs_password = proxy['obfs-password'];
|
||||
}
|
||||
} else if (proxy.type === 'tuic') {
|
||||
proxy = {
|
||||
type: 'tuic',
|
||||
name: proxy.name,
|
||||
server: proxy.server,
|
||||
port: proxy.port,
|
||||
uuid: proxy.uuid,
|
||||
password: proxy.password,
|
||||
next_hop: proxy.next_hop,
|
||||
sni: proxy.sni,
|
||||
alpn: Array.isArray(proxy.alpn)
|
||||
? proxy.alpn
|
||||
: [proxy.alpn || 'h3'],
|
||||
skip_tls_verify: proxy['skip-cert-verify'],
|
||||
port_hopping: proxy.ports,
|
||||
port_hopping_interval: proxy['hop-interval'],
|
||||
};
|
||||
} else if (proxy.type === 'trojan') {
|
||||
if (proxy.network === 'ws') {
|
||||
proxy.websocket = {
|
||||
@ -190,20 +157,6 @@ export default function Egern_Producer() {
|
||||
websocket: proxy.websocket,
|
||||
};
|
||||
} else if (proxy.type === 'vmess') {
|
||||
// Egern:传输层,支持 ws/wss/http1/http2/tls,不配置则为 tcp
|
||||
let security = proxy.cipher;
|
||||
if (
|
||||
security &&
|
||||
![
|
||||
'auto',
|
||||
'none',
|
||||
'zero',
|
||||
'aes-128-gcm',
|
||||
'chacha20-poly1305',
|
||||
].includes(security)
|
||||
) {
|
||||
security = 'auto';
|
||||
}
|
||||
if (proxy.network === 'ws') {
|
||||
proxy.transport = {
|
||||
[proxy.tls ? 'wss' : 'ws']: {
|
||||
@ -219,11 +172,9 @@ export default function Egern_Producer() {
|
||||
};
|
||||
} else if (proxy.network === 'http') {
|
||||
proxy.transport = {
|
||||
http1: {
|
||||
http: {
|
||||
method: proxy['http-opts']?.method,
|
||||
path: Array.isArray(proxy['http-opts']?.path)
|
||||
? proxy['http-opts']?.path[0]
|
||||
: proxy['http-opts']?.path,
|
||||
path: proxy['http-opts']?.path,
|
||||
headers: {
|
||||
Host: Array.isArray(
|
||||
proxy['http-opts']?.headers?.Host,
|
||||
@ -234,29 +185,9 @@ export default function Egern_Producer() {
|
||||
skip_tls_verify: proxy['skip-cert-verify'],
|
||||
},
|
||||
};
|
||||
} else if (proxy.network === 'h2') {
|
||||
} else if (proxy.network === 'tcp' || !proxy.network) {
|
||||
proxy.transport = {
|
||||
http2: {
|
||||
method: proxy['h2-opts']?.method,
|
||||
path: Array.isArray(proxy['h2-opts']?.path)
|
||||
? proxy['h2-opts']?.path[0]
|
||||
: proxy['h2-opts']?.path,
|
||||
headers: {
|
||||
Host: Array.isArray(
|
||||
proxy['h2-opts']?.headers?.Host,
|
||||
)
|
||||
? proxy['h2-opts']?.headers?.Host[0]
|
||||
: proxy['h2-opts']?.headers?.Host,
|
||||
},
|
||||
skip_tls_verify: proxy['skip-cert-verify'],
|
||||
},
|
||||
};
|
||||
} else if (
|
||||
(proxy.network === 'tcp' || !proxy.network) &&
|
||||
proxy.tls
|
||||
) {
|
||||
proxy.transport = {
|
||||
tls: {
|
||||
[proxy.tls ? 'tls' : 'tcp']: {
|
||||
sni: proxy.tls ? proxy.sni : undefined,
|
||||
skip_tls_verify: proxy.tls
|
||||
? proxy['skip-cert-verify']
|
||||
@ -270,7 +201,7 @@ export default function Egern_Producer() {
|
||||
server: proxy.server,
|
||||
port: proxy.port,
|
||||
user_id: proxy.uuid,
|
||||
security,
|
||||
security: proxy.cipher,
|
||||
tfo: proxy.tfo || proxy['fast-open'],
|
||||
legacy: proxy.legacy,
|
||||
udp_relay:
|
||||
@ -298,9 +229,7 @@ export default function Egern_Producer() {
|
||||
proxy.transport = {
|
||||
http: {
|
||||
method: proxy['http-opts']?.method,
|
||||
path: Array.isArray(proxy['http-opts']?.path)
|
||||
? proxy['http-opts']?.path[0]
|
||||
: proxy['http-opts']?.path,
|
||||
path: proxy['http-opts']?.path,
|
||||
headers: {
|
||||
Host: Array.isArray(
|
||||
proxy['http-opts']?.headers?.Host,
|
||||
@ -338,39 +267,6 @@ export default function Egern_Producer() {
|
||||
// skip_tls_verify: proxy['skip-cert-verify'],
|
||||
};
|
||||
}
|
||||
if (
|
||||
[
|
||||
'http',
|
||||
'socks5',
|
||||
'ss',
|
||||
'trojan',
|
||||
'vless',
|
||||
'vmess',
|
||||
].includes(original.type)
|
||||
) {
|
||||
if (isPresent(original, 'shadow-tls-password')) {
|
||||
if (original['shadow-tls-version'] != 3)
|
||||
throw new Error(
|
||||
`shadow-tls version ${original['shadow-tls-version']} is not supported`,
|
||||
);
|
||||
proxy.shadow_tls = {
|
||||
password: original['shadow-tls-password'],
|
||||
sni: original['shadow-tls-sni'],
|
||||
};
|
||||
} else if (
|
||||
['shadow-tls'].includes(original.plugin) &&
|
||||
original['plugin-opts']
|
||||
) {
|
||||
if (original['plugin-opts'].version != 3)
|
||||
throw new Error(
|
||||
`shadow-tls version ${original['plugin-opts'].version} is not supported`,
|
||||
);
|
||||
proxy.shadow_tls = {
|
||||
password: original['plugin-opts'].password,
|
||||
sni: original['plugin-opts'].host,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
delete proxy.subName;
|
||||
delete proxy.collectionName;
|
||||
@ -388,7 +284,6 @@ export default function Egern_Producer() {
|
||||
[proxy.type]: {
|
||||
...proxy,
|
||||
type: undefined,
|
||||
prev_hop,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
@ -20,37 +20,20 @@ function JSON_Producer() {
|
||||
}
|
||||
|
||||
export default {
|
||||
qx: QX_Producer(),
|
||||
QX: QX_Producer(),
|
||||
QuantumultX: QX_Producer(),
|
||||
surge: Surge_Producer(),
|
||||
Surge: Surge_Producer(),
|
||||
SurgeMac: SurgeMac_Producer(),
|
||||
Loon: Loon_Producer(),
|
||||
Clash: Clash_Producer(),
|
||||
meta: ClashMeta_Producer(),
|
||||
clashmeta: ClashMeta_Producer(),
|
||||
'clash.meta': ClashMeta_Producer(),
|
||||
'Clash.Meta': ClashMeta_Producer(),
|
||||
ClashMeta: ClashMeta_Producer(),
|
||||
mihomo: ClashMeta_Producer(),
|
||||
Mihomo: ClashMeta_Producer(),
|
||||
uri: URI_Producer(),
|
||||
URI: URI_Producer(),
|
||||
v2: V2Ray_Producer(),
|
||||
v2ray: V2Ray_Producer(),
|
||||
V2Ray: V2Ray_Producer(),
|
||||
json: JSON_Producer(),
|
||||
JSON: JSON_Producer(),
|
||||
stash: Stash_Producer(),
|
||||
Stash: Stash_Producer(),
|
||||
shadowrocket: Shadowrocket_Producer(),
|
||||
Shadowrocket: Shadowrocket_Producer(),
|
||||
ShadowRocket: Shadowrocket_Producer(),
|
||||
surfboard: Surfboard_Producer(),
|
||||
Surfboard: Surfboard_Producer(),
|
||||
singbox: singbox_Producer(),
|
||||
'sing-box': singbox_Producer(),
|
||||
egern: Egern_Producer(),
|
||||
Egern: Egern_Producer(),
|
||||
};
|
||||
|
@ -3,27 +3,19 @@ const targetPlatform = 'Loon';
|
||||
import { isPresent, Result } from './utils';
|
||||
import { isIPv4, isIPv6 } from '@/utils';
|
||||
|
||||
const ipVersions = {
|
||||
dual: 'dual',
|
||||
ipv4: 'v4-only',
|
||||
ipv6: 'v6-only',
|
||||
'ipv4-prefer': 'prefer-v4',
|
||||
'ipv6-prefer': 'prefer-v6',
|
||||
};
|
||||
|
||||
export default function Loon_Producer() {
|
||||
const produce = (proxy, type, opts = {}) => {
|
||||
switch (proxy.type) {
|
||||
case 'ss':
|
||||
return shadowsocks(proxy);
|
||||
return shadowsocks(proxy, opts['include-unsupported-proxy']);
|
||||
case 'ssr':
|
||||
return shadowsocksr(proxy);
|
||||
case 'trojan':
|
||||
return trojan(proxy);
|
||||
case 'vmess':
|
||||
return vmess(proxy, opts['include-unsupported-proxy']);
|
||||
return vmess(proxy);
|
||||
case 'vless':
|
||||
return vless(proxy, opts['include-unsupported-proxy']);
|
||||
return vless(proxy);
|
||||
case 'http':
|
||||
return http(proxy);
|
||||
case 'socks5':
|
||||
@ -40,7 +32,7 @@ export default function Loon_Producer() {
|
||||
return { produce };
|
||||
}
|
||||
|
||||
function shadowsocks(proxy) {
|
||||
function shadowsocks(proxy, includeUnsupportedProxy) {
|
||||
const result = new Result(proxy);
|
||||
if (
|
||||
![
|
||||
@ -64,8 +56,9 @@ function shadowsocks(proxy) {
|
||||
'aes-256-gcm',
|
||||
'chacha20-ietf-poly1305',
|
||||
'xchacha20-ietf-poly1305',
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
...(includeUnsupportedProxy
|
||||
? ['2022-blake3-aes-128-gcm', '2022-blake3-aes-256-gcm']
|
||||
: []),
|
||||
].includes(proxy.cipher)
|
||||
) {
|
||||
throw new Error(`cipher ${proxy.cipher} is not supported`);
|
||||
@ -86,68 +79,19 @@ function shadowsocks(proxy) {
|
||||
`,obfs-uri=${proxy['plugin-opts'].path}`,
|
||||
'plugin-opts.path',
|
||||
);
|
||||
} else if (!['shadow-tls'].includes(proxy.plugin)) {
|
||||
} else {
|
||||
throw new Error(`plugin ${proxy.plugin} is not supported`);
|
||||
}
|
||||
}
|
||||
|
||||
// shadow-tls
|
||||
if (isPresent(proxy, 'shadow-tls-password')) {
|
||||
result.append(`,shadow-tls-password=${proxy['shadow-tls-password']}`);
|
||||
|
||||
result.appendIfPresent(
|
||||
`,shadow-tls-version=${proxy['shadow-tls-version']}`,
|
||||
'shadow-tls-version',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,shadow-tls-sni=${proxy['shadow-tls-sni']}`,
|
||||
'shadow-tls-sni',
|
||||
);
|
||||
// udp-port
|
||||
result.appendIfPresent(`,udp-port=${proxy['udp-port']}`, 'udp-port');
|
||||
} else if (['shadow-tls'].includes(proxy.plugin) && proxy['plugin-opts']) {
|
||||
const password = proxy['plugin-opts'].password;
|
||||
const host = proxy['plugin-opts'].host;
|
||||
const version = proxy['plugin-opts'].version;
|
||||
if (password) {
|
||||
result.append(`,shadow-tls-password=${password}`);
|
||||
if (host) {
|
||||
result.append(`,shadow-tls-sni=${host}`);
|
||||
}
|
||||
if (version) {
|
||||
if (version < 2) {
|
||||
throw new Error(
|
||||
`shadow-tls version ${version} is not supported`,
|
||||
);
|
||||
}
|
||||
result.append(`,shadow-tls-version=${version}`);
|
||||
}
|
||||
// udp-port
|
||||
result.appendIfPresent(
|
||||
`,udp-port=${proxy['udp-port']}`,
|
||||
'udp-port',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// tfo
|
||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
// udp
|
||||
if (proxy.udp) {
|
||||
result.append(`,udp=true`);
|
||||
}
|
||||
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
@ -168,63 +112,14 @@ function shadowsocksr(proxy) {
|
||||
result.appendIfPresent(`,obfs=${proxy.obfs}`, 'obfs');
|
||||
result.appendIfPresent(`,obfs-param=${proxy['obfs-param']}`, 'obfs-param');
|
||||
|
||||
// shadow-tls
|
||||
if (isPresent(proxy, 'shadow-tls-password')) {
|
||||
result.append(`,shadow-tls-password=${proxy['shadow-tls-password']}`);
|
||||
|
||||
result.appendIfPresent(
|
||||
`,shadow-tls-version=${proxy['shadow-tls-version']}`,
|
||||
'shadow-tls-version',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,shadow-tls-sni=${proxy['shadow-tls-sni']}`,
|
||||
'shadow-tls-sni',
|
||||
);
|
||||
// udp-port
|
||||
result.appendIfPresent(`,udp-port=${proxy['udp-port']}`, 'udp-port');
|
||||
} else if (['shadow-tls'].includes(proxy.plugin) && proxy['plugin-opts']) {
|
||||
const password = proxy['plugin-opts'].password;
|
||||
const host = proxy['plugin-opts'].host;
|
||||
const version = proxy['plugin-opts'].version;
|
||||
if (password) {
|
||||
result.append(`,shadow-tls-password=${password}`);
|
||||
if (host) {
|
||||
result.append(`,shadow-tls-sni=${host}`);
|
||||
}
|
||||
if (version) {
|
||||
if (version < 2) {
|
||||
throw new Error(
|
||||
`shadow-tls version ${version} is not supported`,
|
||||
);
|
||||
}
|
||||
result.append(`,shadow-tls-version=${version}`);
|
||||
}
|
||||
// udp-port
|
||||
result.appendIfPresent(
|
||||
`,udp-port=${proxy['udp-port']}`,
|
||||
'udp-port',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// tfo
|
||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
// udp
|
||||
if (proxy.udp) {
|
||||
result.append(`,udp=true`);
|
||||
}
|
||||
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
@ -273,26 +168,15 @@ function trojan(proxy) {
|
||||
// tfo
|
||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
// udp
|
||||
if (proxy.udp) {
|
||||
result.append(`,udp=true`);
|
||||
}
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
function vmess(proxy) {
|
||||
const isReality = !!proxy['reality-opts'];
|
||||
|
||||
const result = new Result(proxy);
|
||||
result.append(
|
||||
`${proxy.name}=vmess,${proxy.server},${proxy.port},${proxy.cipher},"${proxy.uuid}"`,
|
||||
@ -340,32 +224,20 @@ function vmess(proxy) {
|
||||
'skip-cert-verify',
|
||||
);
|
||||
|
||||
if (isReality) {
|
||||
result.appendIfPresent(`,sni=${proxy.sni}`, 'sni');
|
||||
result.appendIfPresent(
|
||||
`,public-key="${proxy['reality-opts']['public-key']}"`,
|
||||
'reality-opts.public-key',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,short-id=${proxy['reality-opts']['short-id']}`,
|
||||
'reality-opts.short-id',
|
||||
);
|
||||
} else {
|
||||
// sni
|
||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||
result.appendIfPresent(
|
||||
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||
'tls-fingerprint',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||
'tls-pubkey-sha256',
|
||||
);
|
||||
}
|
||||
// sni
|
||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||
result.appendIfPresent(
|
||||
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||
'tls-fingerprint',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||
'tls-pubkey-sha256',
|
||||
);
|
||||
|
||||
// AEAD
|
||||
if (isPresent(proxy, 'aead')) {
|
||||
result.append(`,alterId=${proxy.aead ? 0 : 1}`);
|
||||
result.append(`,alterId=0`);
|
||||
} else {
|
||||
result.append(`,alterId=${proxy.alterId}`);
|
||||
}
|
||||
@ -373,34 +245,17 @@ function vmess(proxy) {
|
||||
// tfo
|
||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
// udp
|
||||
if (proxy.udp) {
|
||||
result.append(`,udp=true`);
|
||||
}
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
function vless(proxy) {
|
||||
let isXtls = false;
|
||||
const isReality = !!proxy['reality-opts'];
|
||||
|
||||
if (typeof proxy.flow !== 'undefined') {
|
||||
if (['xtls-rprx-vision'].includes(proxy.flow)) {
|
||||
isXtls = true;
|
||||
} else {
|
||||
throw new Error(`VLESS flow(${proxy.flow}) is not supported`);
|
||||
}
|
||||
if (proxy['reality-opts']) {
|
||||
throw new Error(`VLESS REALITY is unsupported`);
|
||||
}
|
||||
|
||||
const result = new Result(proxy);
|
||||
result.append(
|
||||
`${proxy.name}=vless,${proxy.server},${proxy.port},"${proxy.uuid}"`,
|
||||
@ -448,48 +303,24 @@ function vless(proxy) {
|
||||
'skip-cert-verify',
|
||||
);
|
||||
|
||||
if (isXtls) {
|
||||
result.appendIfPresent(`,flow=${proxy.flow}`, 'flow');
|
||||
}
|
||||
if (isReality) {
|
||||
result.appendIfPresent(`,sni=${proxy.sni}`, 'sni');
|
||||
result.appendIfPresent(
|
||||
`,public-key="${proxy['reality-opts']['public-key']}"`,
|
||||
'reality-opts.public-key',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,short-id=${proxy['reality-opts']['short-id']}`,
|
||||
'reality-opts.short-id',
|
||||
);
|
||||
} else {
|
||||
// sni
|
||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||
result.appendIfPresent(
|
||||
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||
'tls-fingerprint',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||
'tls-pubkey-sha256',
|
||||
);
|
||||
}
|
||||
// sni
|
||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||
result.appendIfPresent(
|
||||
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||
'tls-fingerprint',
|
||||
);
|
||||
result.appendIfPresent(
|
||||
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||
'tls-pubkey-sha256',
|
||||
);
|
||||
|
||||
// tfo
|
||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
// udp
|
||||
if (proxy.udp) {
|
||||
result.append(`,udp=true`);
|
||||
}
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
@ -512,16 +343,6 @@ function http(proxy) {
|
||||
// tfo
|
||||
result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
function socks5(proxy) {
|
||||
@ -545,19 +366,10 @@ function socks5(proxy) {
|
||||
// tfo
|
||||
result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
// udp
|
||||
if (proxy.udp) {
|
||||
result.append(`,udp=true`);
|
||||
}
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
@ -623,15 +435,6 @@ function wireguard(proxy) {
|
||||
presharedKey ?? ''
|
||||
}}]`,
|
||||
);
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
@ -667,13 +470,6 @@ function hysteria2(proxy) {
|
||||
// tfo
|
||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||
|
||||
// block-quic
|
||||
if (proxy['block-quic'] === 'on') {
|
||||
result.append(',block-quic=true');
|
||||
} else if (proxy['block-quic'] === 'off') {
|
||||
result.append(',block-quic=false');
|
||||
}
|
||||
|
||||
// udp
|
||||
if (proxy.udp) {
|
||||
result.append(`,udp=true`);
|
||||
@ -686,8 +482,6 @@ function hysteria2(proxy) {
|
||||
);
|
||||
|
||||
result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn');
|
||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||
result.appendIfPresent(`,ip-mode=${ip_version}`, 'ip-version');
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
@ -58,8 +58,6 @@ function shadowsocks(proxy) {
|
||||
'aes-256-gcm',
|
||||
'chacha20-ietf-poly1305',
|
||||
'xchacha20-ietf-poly1305',
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
].includes(proxy.cipher)
|
||||
) {
|
||||
throw new Error(`cipher ${proxy.cipher} is not supported`);
|
||||
@ -130,20 +128,6 @@ function shadowsocks(proxy) {
|
||||
// udp
|
||||
appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp');
|
||||
|
||||
// udp over tcp
|
||||
if (proxy['_ssr_python_uot']) {
|
||||
append(`,udp-over-tcp=true`);
|
||||
} else if (proxy['udp-over-tcp']) {
|
||||
if (
|
||||
!proxy['udp-over-tcp-version'] ||
|
||||
proxy['udp-over-tcp-version'] === 1
|
||||
) {
|
||||
append(`,udp-over-tcp=sp.v1`);
|
||||
} else if (proxy['udp-over-tcp-version'] === 2) {
|
||||
append(`,udp-over-tcp=sp.v2`);
|
||||
}
|
||||
}
|
||||
|
||||
// server_check_url
|
||||
result.appendIfPresent(
|
||||
`,server_check_url=${proxy['test-url']}`,
|
||||
@ -405,8 +389,6 @@ function vless(proxy) {
|
||||
else append(`,obfs=ws`);
|
||||
} else if (proxy.network === 'http') {
|
||||
append(`,obfs=http`);
|
||||
} else if (['tcp'].includes(proxy.network)) {
|
||||
if (proxy.tls) append(`,obfs=over-tls`);
|
||||
} else if (!['tcp'].includes(proxy.network)) {
|
||||
throw new Error(`network ${proxy.network} is unsupported`);
|
||||
}
|
||||
|
@ -1,7 +1,6 @@
|
||||
import { isPresent } from '@/core/proxy-utils/producers/utils';
|
||||
import $ from '@/core/app';
|
||||
|
||||
export default function Shadowrocket_Producer() {
|
||||
export default function ShadowRocket_Producer() {
|
||||
const type = 'ALL';
|
||||
const produce = (proxies, type, opts = {}) => {
|
||||
const list = proxies
|
||||
@ -9,8 +8,6 @@ export default function Shadowrocket_Producer() {
|
||||
if (opts['include-unsupported-proxy']) return true;
|
||||
if (proxy.type === 'snell' && String(proxy.version) === '4') {
|
||||
return false;
|
||||
} else if (['mieru'].includes(proxy.type)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
@ -33,10 +30,9 @@ export default function Shadowrocket_Producer() {
|
||||
isPresent(proxy, 'cipher') &&
|
||||
![
|
||||
'auto',
|
||||
'none',
|
||||
'zero',
|
||||
'aes-128-gcm',
|
||||
'chacha20-poly1305',
|
||||
'none',
|
||||
].includes(proxy.cipher)
|
||||
) {
|
||||
proxy.cipher = 'auto';
|
||||
@ -104,28 +100,11 @@ export default function Shadowrocket_Producer() {
|
||||
proxy['preshared-key'] =
|
||||
proxy['preshared-key'] ?? proxy['pre-shared-key'];
|
||||
proxy['pre-shared-key'] = proxy['preshared-key'];
|
||||
} else if (proxy.type === 'snell' && proxy.version < 3) {
|
||||
delete proxy.udp;
|
||||
} else if (proxy.type === 'vless') {
|
||||
if (isPresent(proxy, 'sni')) {
|
||||
proxy.servername = proxy.sni;
|
||||
delete proxy.sni;
|
||||
}
|
||||
} else if (proxy.type === 'ss') {
|
||||
if (
|
||||
isPresent(proxy, 'shadow-tls-password') &&
|
||||
!isPresent(proxy, 'plugin')
|
||||
) {
|
||||
proxy.plugin = 'shadow-tls';
|
||||
proxy['plugin-opts'] = {
|
||||
host: proxy['shadow-tls-sni'],
|
||||
password: proxy['shadow-tls-password'],
|
||||
version: proxy['shadow-tls-version'],
|
||||
};
|
||||
delete proxy['shadow-tls-password'];
|
||||
delete proxy['shadow-tls-sni'];
|
||||
delete proxy['shadow-tls-version'];
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
@ -179,7 +158,6 @@ export default function Shadowrocket_Producer() {
|
||||
'hysteria',
|
||||
'hysteria2',
|
||||
'juicity',
|
||||
'anytls',
|
||||
].includes(proxy.type)
|
||||
) {
|
||||
delete proxy.tls;
|
||||
|
@ -3,11 +3,7 @@ import $ from '@/core/app';
|
||||
import { isIPv4, isIPv6 } from '@/utils';
|
||||
|
||||
const detourParser = (proxy, parsedProxy) => {
|
||||
parsedProxy.detour = proxy['dialer-proxy'] || proxy.detour;
|
||||
};
|
||||
const networkParser = (proxy, parsedProxy) => {
|
||||
if (['tcp', 'udp'].includes(proxy._network))
|
||||
parsedProxy.network = proxy._network;
|
||||
if (proxy['dialer-proxy']) parsedProxy.detour = proxy['dialer-proxy'];
|
||||
};
|
||||
const tfoParser = (proxy, parsedProxy) => {
|
||||
parsedProxy.tcp_fast_open = false;
|
||||
@ -31,21 +27,6 @@ const smuxParser = (smux, proxy) => {
|
||||
if (smux['min-streams'])
|
||||
proxy.multiplex.min_streams = parseInt(`${smux['min-streams']}`, 10);
|
||||
if (smux.padding) proxy.multiplex.padding = true;
|
||||
if (smux['brutal-opts']?.up || smux['brutal-opts']?.down) {
|
||||
proxy.multiplex.brutal = {
|
||||
enabled: true,
|
||||
};
|
||||
if (smux['brutal-opts']?.up)
|
||||
proxy.multiplex.brutal.up_mbps = parseInt(
|
||||
`${smux['brutal-opts']?.up}`,
|
||||
10,
|
||||
);
|
||||
if (smux['brutal-opts']?.down)
|
||||
proxy.multiplex.brutal.down_mbps = parseInt(
|
||||
`${smux['brutal-opts']?.down}`,
|
||||
10,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const wsParser = (proxy, parsedProxy) => {
|
||||
@ -233,11 +214,7 @@ const tlsParser = (proxy, parsedProxy) => {
|
||||
proxy['reality-opts']['short-id'];
|
||||
parsedProxy.tls.utls = { enabled: true };
|
||||
}
|
||||
if (
|
||||
!['hysteria', 'hysteria2', 'tuic'].includes(proxy.type) &&
|
||||
proxy['client-fingerprint'] &&
|
||||
proxy['client-fingerprint'] !== ''
|
||||
)
|
||||
if (proxy['client-fingerprint'] && proxy['client-fingerprint'] !== '')
|
||||
parsedProxy.tls.utls = {
|
||||
enabled: true,
|
||||
fingerprint: proxy['client-fingerprint'],
|
||||
@ -324,7 +301,6 @@ const socks5Parser = (proxy = {}) => {
|
||||
if (proxy.uot) parsedProxy.udp_over_tcp = true;
|
||||
if (proxy['udp-over-tcp']) parsedProxy.udp_over_tcp = true;
|
||||
if (proxy['fast-open']) parsedProxy.udp_fragment = true;
|
||||
networkParser(proxy, parsedProxy);
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
return parsedProxy;
|
||||
@ -374,18 +350,8 @@ const ssParser = (proxy = {}) => {
|
||||
if (parsedProxy.server_port < 0 || parsedProxy.server_port > 65535)
|
||||
throw 'invalid port';
|
||||
if (proxy.uot) parsedProxy.udp_over_tcp = true;
|
||||
if (proxy['udp-over-tcp']) {
|
||||
parsedProxy.udp_over_tcp = {
|
||||
enabled: true,
|
||||
version:
|
||||
!proxy['udp-over-tcp-version'] ||
|
||||
proxy['udp-over-tcp-version'] === 1
|
||||
? 1
|
||||
: 2,
|
||||
};
|
||||
}
|
||||
if (proxy['udp-over-tcp']) parsedProxy.udp_over_tcp = true;
|
||||
if (proxy['fast-open']) parsedProxy.udp_fragment = true;
|
||||
networkParser(proxy, parsedProxy);
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
smuxParser(proxy.smux, parsedProxy);
|
||||
@ -500,7 +466,7 @@ const vmessParser = (proxy = {}) => {
|
||||
if (proxy.network === 'h2') h2Parser(proxy, parsedProxy);
|
||||
if (proxy.network === 'http') h1Parser(proxy, parsedProxy);
|
||||
if (proxy.network === 'grpc') grpcParser(proxy, parsedProxy);
|
||||
networkParser(proxy, parsedProxy);
|
||||
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
tlsParser(proxy, parsedProxy);
|
||||
@ -519,12 +485,11 @@ const vlessParser = (proxy = {}) => {
|
||||
};
|
||||
if (parsedProxy.server_port < 0 || parsedProxy.server_port > 65535)
|
||||
throw 'invalid port';
|
||||
if (proxy.xudp) parsedProxy.packet_encoding = 'xudp';
|
||||
if (proxy['fast-open']) parsedProxy.udp_fragment = true;
|
||||
if (proxy.flow === 'xtls-rprx-vision') parsedProxy.flow = proxy.flow;
|
||||
if (proxy.network === 'ws') wsParser(proxy, parsedProxy);
|
||||
if (proxy.network === 'grpc') grpcParser(proxy, parsedProxy);
|
||||
networkParser(proxy, parsedProxy);
|
||||
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
smuxParser(proxy.smux, parsedProxy);
|
||||
@ -545,7 +510,7 @@ const trojanParser = (proxy = {}) => {
|
||||
if (proxy['fast-open']) parsedProxy.udp_fragment = true;
|
||||
if (proxy.network === 'grpc') grpcParser(proxy, parsedProxy);
|
||||
if (proxy.network === 'ws') wsParser(proxy, parsedProxy);
|
||||
networkParser(proxy, parsedProxy);
|
||||
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
tlsParser(proxy, parsedProxy);
|
||||
@ -568,13 +533,12 @@ const hysteriaParser = (proxy = {}) => {
|
||||
if (proxy['fast-open']) parsedProxy.udp_fragment = true;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const reg = new RegExp('^[0-9]+[ \t]*[KMGT]*[Bb]ps$');
|
||||
// sing-box 跟文档不一致, 但是懒得全转, 只处理最常见的 Mbps
|
||||
if (reg.test(`${proxy.up}`) && !`${proxy.up}`.endsWith('Mbps')) {
|
||||
if (reg.test(`${proxy.up}`)) {
|
||||
parsedProxy.up = `${proxy.up}`;
|
||||
} else {
|
||||
parsedProxy.up_mbps = parseInt(`${proxy.up}`, 10);
|
||||
}
|
||||
if (reg.test(`${proxy.down}`) && !`${proxy.down}`.endsWith('Mbps')) {
|
||||
if (reg.test(`${proxy.down}`)) {
|
||||
parsedProxy.down = `${proxy.down}`;
|
||||
} else {
|
||||
parsedProxy.down_mbps = parseInt(`${proxy.down}`, 10);
|
||||
@ -594,7 +558,6 @@ const hysteriaParser = (proxy = {}) => {
|
||||
parsedProxy.disable_mtu_discovery = true;
|
||||
}
|
||||
}
|
||||
networkParser(proxy, parsedProxy);
|
||||
tlsParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
tfoParser(proxy, parsedProxy);
|
||||
@ -613,21 +576,12 @@ const hysteria2Parser = (proxy = {}) => {
|
||||
};
|
||||
if (parsedProxy.server_port < 0 || parsedProxy.server_port > 65535)
|
||||
throw 'invalid port';
|
||||
if (proxy['hop-interval'])
|
||||
parsedProxy.hop_interval = /^\d+$/.test(proxy['hop-interval'])
|
||||
? `${proxy['hop-interval']}s`
|
||||
: proxy['hop-interval'];
|
||||
if (proxy['ports'])
|
||||
parsedProxy.server_ports = proxy['ports']
|
||||
.split(/\s*,\s*/)
|
||||
.map((p) => p.replace(/\s*-\s*/g, ':'));
|
||||
if (proxy.up) parsedProxy.up_mbps = parseInt(`${proxy.up}`, 10);
|
||||
if (proxy.down) parsedProxy.down_mbps = parseInt(`${proxy.down}`, 10);
|
||||
if (proxy.obfs === 'salamander') parsedProxy.obfs.type = 'salamander';
|
||||
if (proxy['obfs-password'])
|
||||
parsedProxy.obfs.password = proxy['obfs-password'];
|
||||
if (!parsedProxy.obfs.type) delete parsedProxy.obfs;
|
||||
networkParser(proxy, parsedProxy);
|
||||
tlsParser(proxy, parsedProxy);
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
@ -658,30 +612,12 @@ const tuic5Parser = (proxy = {}) => {
|
||||
if (proxy['udp-over-stream']) parsedProxy.udp_over_stream = true;
|
||||
if (proxy['heartbeat-interval'])
|
||||
parsedProxy.heartbeat = `${proxy['heartbeat-interval']}ms`;
|
||||
networkParser(proxy, parsedProxy);
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
tlsParser(proxy, parsedProxy);
|
||||
smuxParser(proxy.smux, parsedProxy);
|
||||
return parsedProxy;
|
||||
};
|
||||
const anytlsParser = (proxy = {}) => {
|
||||
const parsedProxy = {
|
||||
tag: proxy.name,
|
||||
type: 'anytls',
|
||||
server: proxy.server,
|
||||
server_port: parseInt(`${proxy.port}`, 10),
|
||||
password: proxy.password,
|
||||
tls: { enabled: true, server_name: proxy.server, insecure: false },
|
||||
};
|
||||
if (/^\d+$/.test(proxy['idle-session-check-interval']))
|
||||
parsedProxy.idle_session_check_interval = `${proxy['idle-session-check-interval']}s`;
|
||||
if (/^\d+$/.test(proxy['idle-session-timeout']))
|
||||
parsedProxy.idle_session_timeout = `${proxy['idle-session-timeout']}s`;
|
||||
detourParser(proxy, parsedProxy);
|
||||
tlsParser(proxy, parsedProxy);
|
||||
return parsedProxy;
|
||||
};
|
||||
|
||||
const wireguardParser = (proxy = {}) => {
|
||||
const local_address = ['ip', 'ipv6']
|
||||
@ -733,7 +669,6 @@ const wireguardParser = (proxy = {}) => {
|
||||
parsedProxy.peers.push(peer);
|
||||
}
|
||||
}
|
||||
networkParser(proxy, parsedProxy);
|
||||
tfoParser(proxy, parsedProxy);
|
||||
detourParser(proxy, parsedProxy);
|
||||
smuxParser(proxy.smux, parsedProxy);
|
||||
@ -851,12 +786,7 @@ export default function singbox_Producer() {
|
||||
list.push(hysteriaParser(proxy));
|
||||
break;
|
||||
case 'hysteria2':
|
||||
list.push(
|
||||
hysteria2Parser(
|
||||
proxy,
|
||||
opts['include-unsupported-proxy'],
|
||||
),
|
||||
);
|
||||
list.push(hysteria2Parser(proxy));
|
||||
break;
|
||||
case 'tuic':
|
||||
if (!proxy.token || proxy.token.length === 0) {
|
||||
@ -870,9 +800,6 @@ export default function singbox_Producer() {
|
||||
case 'wireguard':
|
||||
list.push(wireguardParser(proxy));
|
||||
break;
|
||||
case 'anytls':
|
||||
list.push(anytlsParser(proxy));
|
||||
break;
|
||||
default:
|
||||
throw new Error(
|
||||
`Platform sing-box does not support proxy type: ${proxy.type}`,
|
||||
|
@ -1,5 +1,4 @@
|
||||
import { isPresent } from '@/core/proxy-utils/producers/utils';
|
||||
import $ from '@/core/app';
|
||||
|
||||
export default function Stash_Producer() {
|
||||
const type = 'ALL';
|
||||
@ -40,20 +39,17 @@ export default function Stash_Producer() {
|
||||
'xchacha20',
|
||||
'chacha20-ietf-poly1305',
|
||||
'xchacha20-ietf-poly1305',
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
...(opts['include-unsupported-proxy']
|
||||
? [
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
]
|
||||
: []),
|
||||
].includes(proxy.cipher)) ||
|
||||
(proxy.type === 'snell' && String(proxy.version) === '4') ||
|
||||
(proxy.type === 'vless' &&
|
||||
proxy['reality-opts'] &&
|
||||
!['xtls-rprx-vision'].includes(proxy.flow))
|
||||
(proxy.type === 'vless' && proxy['reality-opts'])
|
||||
) {
|
||||
return false;
|
||||
} else if (proxy['underlying-proxy'] || proxy['dialer-proxy']) {
|
||||
$.error(
|
||||
`Stash 暂不支持前置代理字段. 已过滤节点 ${proxy.name}. 请使用 代理的转发链 https://stash.wiki/proxy-protocols/proxy-groups#relay`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
@ -191,8 +187,6 @@ export default function Stash_Producer() {
|
||||
proxy['preshared-key'] =
|
||||
proxy['preshared-key'] ?? proxy['pre-shared-key'];
|
||||
proxy['pre-shared-key'] = proxy['preshared-key'];
|
||||
} else if (proxy.type === 'snell' && proxy.version < 3) {
|
||||
delete proxy.udp;
|
||||
} else if (proxy.type === 'vless') {
|
||||
if (isPresent(proxy, 'sni')) {
|
||||
proxy.servername = proxy.sni;
|
||||
@ -251,7 +245,6 @@ export default function Stash_Producer() {
|
||||
'hysteria',
|
||||
'hysteria2',
|
||||
'juicity',
|
||||
'anytls',
|
||||
].includes(proxy.type)
|
||||
) {
|
||||
delete proxy.tls;
|
||||
@ -261,6 +254,11 @@ export default function Stash_Producer() {
|
||||
}
|
||||
delete proxy['tls-fingerprint'];
|
||||
|
||||
if (proxy['underlying-proxy']) {
|
||||
proxy['dialer-proxy'] = proxy['underlying-proxy'];
|
||||
}
|
||||
delete proxy['underlying-proxy'];
|
||||
|
||||
if (isPresent(proxy, 'tls') && typeof proxy.tls !== 'boolean') {
|
||||
delete proxy.tls;
|
||||
}
|
||||
|
@ -53,7 +53,7 @@ export default function Surge_Producer() {
|
||||
return { produce };
|
||||
}
|
||||
|
||||
function shadowsocks(proxy) {
|
||||
function shadowsocks(proxy, includeUnsupportedProxy) {
|
||||
const result = new Result(proxy);
|
||||
result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`);
|
||||
if (!proxy.cipher) {
|
||||
@ -87,8 +87,9 @@ function shadowsocks(proxy) {
|
||||
'chacha20',
|
||||
'chacha20-ietf',
|
||||
'none',
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
...(includeUnsupportedProxy
|
||||
? ['2022-blake3-aes-128-gcm', '2022-blake3-aes-256-gcm']
|
||||
: []),
|
||||
].includes(proxy.cipher)
|
||||
) {
|
||||
throw new Error(`cipher ${proxy.cipher} is not supported`);
|
||||
@ -126,6 +127,8 @@ function shadowsocks(proxy) {
|
||||
|
||||
// udp
|
||||
result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp');
|
||||
// udp-port
|
||||
result.appendIfPresent(`,udp-port=${proxy['udp-port']}`, 'udp-port');
|
||||
|
||||
// test-url
|
||||
result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url');
|
||||
@ -157,8 +160,6 @@ function shadowsocks(proxy) {
|
||||
`,shadow-tls-sni=${proxy['shadow-tls-sni']}`,
|
||||
'shadow-tls-sni',
|
||||
);
|
||||
// udp-port
|
||||
result.appendIfPresent(`,udp-port=${proxy['udp-port']}`, 'udp-port');
|
||||
} else if (['shadow-tls'].includes(proxy.plugin) && proxy['plugin-opts']) {
|
||||
const password = proxy['plugin-opts'].password;
|
||||
const host = proxy['plugin-opts'].host;
|
||||
@ -176,11 +177,6 @@ function shadowsocks(proxy) {
|
||||
}
|
||||
result.append(`,shadow-tls-version=${version}`);
|
||||
}
|
||||
// udp-port
|
||||
result.appendIfPresent(
|
||||
`,udp-port=${proxy['udp-port']}`,
|
||||
'udp-port',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -433,9 +429,6 @@ function ssh(proxy) {
|
||||
return result.toString();
|
||||
}
|
||||
function http(proxy) {
|
||||
if (proxy.headers && Object.keys(proxy.headers).length > 0) {
|
||||
throw new Error(`headers is unsupported`);
|
||||
}
|
||||
const result = new Result(proxy);
|
||||
const type = proxy.tls ? 'https' : 'http';
|
||||
result.append(`${proxy.name}=${type},${proxy.server},${proxy.port}`);
|
||||
|
@ -141,19 +141,10 @@ function mihomo(proxy, type, opts) {
|
||||
dns: {
|
||||
enable: true,
|
||||
ipv6,
|
||||
'default-nameserver': opts?.defaultNameserver ||
|
||||
proxy._defaultNameserver || [
|
||||
'180.76.76.76',
|
||||
'52.80.52.52',
|
||||
'119.28.28.28',
|
||||
'223.6.6.6',
|
||||
],
|
||||
nameserver: opts?.nameserver ||
|
||||
proxy._nameserver || [
|
||||
'https://doh.pub/dns-query',
|
||||
'https://dns.alidns.com/dns-query',
|
||||
'https://doh-pure.onedns.net/dns-query',
|
||||
],
|
||||
nameserver: [
|
||||
'https://223.6.6.6/dns-query',
|
||||
'https://120.53.53.53/dns-query',
|
||||
],
|
||||
},
|
||||
proxies: [
|
||||
{
|
||||
|
@ -12,7 +12,7 @@ export default function URI_Producer() {
|
||||
delete proxy.resolved;
|
||||
delete proxy['no-resolve'];
|
||||
for (const key in proxy) {
|
||||
if (proxy[key] == null) {
|
||||
if (proxy[key] == null || /^_/i.test(key)) {
|
||||
delete proxy[key];
|
||||
}
|
||||
}
|
||||
@ -23,30 +23,15 @@ export default function URI_Producer() {
|
||||
) {
|
||||
delete proxy.tls;
|
||||
}
|
||||
if (
|
||||
!['vmess'].includes(proxy.type) &&
|
||||
proxy.server &&
|
||||
isIPv6(proxy.server)
|
||||
) {
|
||||
if (proxy.server && isIPv6(proxy.server)) {
|
||||
proxy.server = `[${proxy.server}]`;
|
||||
}
|
||||
switch (proxy.type) {
|
||||
case 'socks5':
|
||||
result = `socks://${encodeURIComponent(
|
||||
Base64.encode(
|
||||
`${proxy.username ?? ''}:${proxy.password ?? ''}`,
|
||||
),
|
||||
)}@${proxy.server}:${proxy.port}#${proxy.name}`;
|
||||
break;
|
||||
case 'ss':
|
||||
const userinfo = `${proxy.cipher}:${proxy.password}`;
|
||||
result = `ss://${
|
||||
proxy.cipher?.startsWith('2022-blake3-')
|
||||
? `${encodeURIComponent(
|
||||
proxy.cipher,
|
||||
)}:${encodeURIComponent(proxy.password)}`
|
||||
: Base64.encode(userinfo)
|
||||
}@${proxy.server}:${proxy.port}${proxy.plugin ? '/' : ''}`;
|
||||
result = `ss://${Base64.encode(userinfo)}@${proxy.server}:${
|
||||
proxy.port
|
||||
}${proxy.plugin ? '/' : ''}`;
|
||||
if (proxy.plugin) {
|
||||
result += '?plugin=';
|
||||
const opts = proxy['plugin-opts'];
|
||||
@ -65,11 +50,6 @@ export default function URI_Producer() {
|
||||
}${opts.tls ? ';tls' : ''}`,
|
||||
);
|
||||
break;
|
||||
case 'shadow-tls':
|
||||
result += encodeURIComponent(
|
||||
`shadow-tls;host=${opts.host};password=${opts.password};version=${opts.version}`,
|
||||
);
|
||||
break;
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported plugin option: ${proxy.plugin}`,
|
||||
@ -119,17 +99,12 @@ export default function URI_Producer() {
|
||||
v: '2',
|
||||
ps: proxy.name,
|
||||
add: proxy.server,
|
||||
port: `${proxy.port}`,
|
||||
port: proxy.port,
|
||||
id: proxy.uuid,
|
||||
aid: `${proxy.alterId || 0}`,
|
||||
scy: proxy.cipher,
|
||||
net,
|
||||
type,
|
||||
aid: proxy.alterId || 0,
|
||||
net,
|
||||
tls: proxy.tls ? 'tls' : '',
|
||||
alpn: Array.isArray(proxy.alpn)
|
||||
? proxy.alpn.join(',')
|
||||
: proxy.alpn,
|
||||
fp: proxy['client-fingerprint'],
|
||||
};
|
||||
if (proxy.tls && proxy.sni) {
|
||||
result.sni = proxy.sni;
|
||||
@ -140,7 +115,16 @@ export default function URI_Producer() {
|
||||
proxy[`${proxy.network}-opts`]?.path;
|
||||
let vmessTransportHost =
|
||||
proxy[`${proxy.network}-opts`]?.headers?.Host;
|
||||
|
||||
if (vmessTransportPath) {
|
||||
result.path = Array.isArray(vmessTransportPath)
|
||||
? vmessTransportPath[0]
|
||||
: vmessTransportPath;
|
||||
}
|
||||
if (vmessTransportHost) {
|
||||
result.host = Array.isArray(vmessTransportHost)
|
||||
? vmessTransportHost[0]
|
||||
: vmessTransportHost;
|
||||
}
|
||||
if (['grpc'].includes(proxy.network)) {
|
||||
result.path =
|
||||
proxy[`${proxy.network}-opts`]?.[
|
||||
@ -152,31 +136,6 @@ export default function URI_Producer() {
|
||||
'gun';
|
||||
result.host =
|
||||
proxy[`${proxy.network}-opts`]?.['_grpc-authority'];
|
||||
} else if (['kcp', 'quic'].includes(proxy.network)) {
|
||||
// https://github.com/XTLS/Xray-core/issues/91
|
||||
result.type =
|
||||
proxy[`${proxy.network}-opts`]?.[
|
||||
`_${proxy.network}-type`
|
||||
] || 'none';
|
||||
result.host =
|
||||
proxy[`${proxy.network}-opts`]?.[
|
||||
`_${proxy.network}-host`
|
||||
];
|
||||
result.path =
|
||||
proxy[`${proxy.network}-opts`]?.[
|
||||
`_${proxy.network}-path`
|
||||
];
|
||||
} else {
|
||||
if (vmessTransportPath) {
|
||||
result.path = Array.isArray(vmessTransportPath)
|
||||
? vmessTransportPath[0]
|
||||
: vmessTransportPath;
|
||||
}
|
||||
if (vmessTransportHost) {
|
||||
result.host = Array.isArray(vmessTransportHost)
|
||||
? vmessTransportHost[0]
|
||||
: vmessTransportHost;
|
||||
}
|
||||
}
|
||||
}
|
||||
result = 'vmess://' + Base64.encode(JSON.stringify(result));
|
||||
@ -186,7 +145,6 @@ export default function URI_Producer() {
|
||||
const isReality = proxy['reality-opts'];
|
||||
let sid = '';
|
||||
let pbk = '';
|
||||
let spx = '';
|
||||
if (isReality) {
|
||||
security = 'reality';
|
||||
const publicKey = proxy['reality-opts']?.['public-key'];
|
||||
@ -197,10 +155,6 @@ export default function URI_Producer() {
|
||||
if (shortId) {
|
||||
sid = `&sid=${encodeURIComponent(shortId)}`;
|
||||
}
|
||||
const spiderX = proxy['reality-opts']?.['_spider-x'];
|
||||
if (spiderX) {
|
||||
spx = `&spx=${encodeURIComponent(spiderX)}`;
|
||||
}
|
||||
} else if (proxy.tls) {
|
||||
security = 'tls';
|
||||
}
|
||||
@ -230,14 +184,6 @@ export default function URI_Producer() {
|
||||
if (proxy.flow) {
|
||||
flow = `&flow=${encodeURIComponent(proxy.flow)}`;
|
||||
}
|
||||
let extra = '';
|
||||
if (proxy._extra) {
|
||||
extra = `&extra=${encodeURIComponent(proxy._extra)}`;
|
||||
}
|
||||
let mode = '';
|
||||
if (proxy._mode) {
|
||||
mode = `&mode=${encodeURIComponent(proxy._mode)}`;
|
||||
}
|
||||
let vlessType = proxy.network;
|
||||
if (
|
||||
proxy.network === 'ws' &&
|
||||
@ -304,7 +250,7 @@ export default function URI_Producer() {
|
||||
proxy.port
|
||||
}?security=${encodeURIComponent(
|
||||
security,
|
||||
)}${vlessTransport}${alpn}${allowInsecure}${sni}${fp}${flow}${sid}${spx}${pbk}${mode}${extra}#${encodeURIComponent(
|
||||
)}${vlessTransport}${alpn}${allowInsecure}${sni}${fp}${flow}${sid}${pbk}#${encodeURIComponent(
|
||||
proxy.name,
|
||||
)}`;
|
||||
break;
|
||||
@ -374,54 +320,16 @@ export default function URI_Producer() {
|
||||
: proxy.alpn.join(','),
|
||||
)}`;
|
||||
}
|
||||
const trojanIsReality = proxy['reality-opts'];
|
||||
let trojanSid = '';
|
||||
let trojanPbk = '';
|
||||
let trojanSpx = '';
|
||||
let trojanSecurity = '';
|
||||
let trojanMode = '';
|
||||
let trojanExtra = '';
|
||||
if (trojanIsReality) {
|
||||
trojanSecurity = `&security=reality`;
|
||||
const publicKey = proxy['reality-opts']?.['public-key'];
|
||||
if (publicKey) {
|
||||
trojanPbk = `&pbk=${encodeURIComponent(publicKey)}`;
|
||||
}
|
||||
const shortId = proxy['reality-opts']?.['short-id'];
|
||||
if (shortId) {
|
||||
trojanSid = `&sid=${encodeURIComponent(shortId)}`;
|
||||
}
|
||||
const spiderX = proxy['reality-opts']?.['_spider-x'];
|
||||
if (spiderX) {
|
||||
trojanSpx = `&spx=${encodeURIComponent(spiderX)}`;
|
||||
}
|
||||
if (proxy._extra) {
|
||||
trojanExtra = `&extra=${encodeURIComponent(
|
||||
proxy._extra,
|
||||
)}`;
|
||||
}
|
||||
if (proxy._mode) {
|
||||
trojanMode = `&mode=${encodeURIComponent(proxy._mode)}`;
|
||||
}
|
||||
}
|
||||
result = `trojan://${proxy.password}@${proxy.server}:${
|
||||
proxy.port
|
||||
}?sni=${encodeURIComponent(proxy.sni || proxy.server)}${
|
||||
proxy['skip-cert-verify'] ? '&allowInsecure=1' : ''
|
||||
}${trojanTransport}${trojanAlpn}${trojanFp}${trojanSecurity}${trojanSid}${trojanPbk}${trojanSpx}${trojanMode}${trojanExtra}#${encodeURIComponent(
|
||||
}${trojanTransport}${trojanAlpn}${trojanFp}#${encodeURIComponent(
|
||||
proxy.name,
|
||||
)}`;
|
||||
break;
|
||||
case 'hysteria2':
|
||||
let hysteria2params = [];
|
||||
if (proxy['hop-interval']) {
|
||||
hysteria2params.push(
|
||||
`hop-interval=${proxy['hop-interval']}`,
|
||||
);
|
||||
}
|
||||
if (proxy['keepalive']) {
|
||||
hysteria2params.push(`keepalive=${proxy['keepalive']}`);
|
||||
}
|
||||
if (proxy['skip-cert-verify']) {
|
||||
hysteria2params.push(`insecure=1`);
|
||||
}
|
||||
@ -501,7 +409,7 @@ export default function URI_Producer() {
|
||||
hysteriaParams.push(`obfsParam=${proxy[key]}`);
|
||||
} else if (['sni'].includes(key)) {
|
||||
hysteriaParams.push(`peer=${proxy[key]}`);
|
||||
} else if (proxy[key] && !/^_/i.test(key)) {
|
||||
} else if (proxy[key]) {
|
||||
hysteriaParams.push(
|
||||
`${i}=${encodeURIComponent(proxy[key])}`,
|
||||
);
|
||||
@ -528,7 +436,6 @@ export default function URI_Producer() {
|
||||
'password',
|
||||
'server',
|
||||
'port',
|
||||
'tls',
|
||||
].includes(key)
|
||||
) {
|
||||
const i = key.replace(/-/, '_');
|
||||
@ -557,19 +464,10 @@ export default function URI_Producer() {
|
||||
['disable-sni', 'reduce-rtt'].includes(key) &&
|
||||
proxy[key]
|
||||
) {
|
||||
tuicParams.push(`${i.replace(/-/g, '_')}=1`);
|
||||
} else if (
|
||||
['congestion-controller'].includes(key)
|
||||
) {
|
||||
tuicParams.push(`${i}=1`);
|
||||
} else if (proxy[key]) {
|
||||
tuicParams.push(
|
||||
`congestion_control=${proxy[key]}`,
|
||||
);
|
||||
} else if (proxy[key] && !/^_/i.test(key)) {
|
||||
tuicParams.push(
|
||||
`${i.replace(
|
||||
/-/g,
|
||||
'_',
|
||||
)}=${encodeURIComponent(proxy[key])}`,
|
||||
`${i}=${encodeURIComponent(proxy[key])}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -584,54 +482,6 @@ export default function URI_Producer() {
|
||||
)}`;
|
||||
}
|
||||
break;
|
||||
case 'anytls':
|
||||
let anytlsParams = [];
|
||||
Object.keys(proxy).forEach((key) => {
|
||||
if (
|
||||
![
|
||||
'name',
|
||||
'type',
|
||||
'password',
|
||||
'server',
|
||||
'port',
|
||||
'tls',
|
||||
].includes(key)
|
||||
) {
|
||||
const i = key.replace(/-/, '_');
|
||||
if (['alpn'].includes(key)) {
|
||||
if (proxy[key]) {
|
||||
anytlsParams.push(
|
||||
`${i}=${encodeURIComponent(
|
||||
Array.isArray(proxy[key])
|
||||
? proxy[key][0]
|
||||
: proxy[key],
|
||||
)}`,
|
||||
);
|
||||
}
|
||||
} else if (['skip-cert-verify'].includes(key)) {
|
||||
if (proxy[key]) {
|
||||
anytlsParams.push(`insecure=1`);
|
||||
}
|
||||
} else if (['udp'].includes(key)) {
|
||||
if (proxy[key]) {
|
||||
anytlsParams.push(`udp=1`);
|
||||
}
|
||||
} else if (proxy[key] && !/^_/i.test(key)) {
|
||||
anytlsParams.push(
|
||||
`${i.replace(/-/g, '_')}=${encodeURIComponent(
|
||||
proxy[key],
|
||||
)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
result = `anytls://${encodeURIComponent(proxy.password)}@${
|
||||
proxy.server
|
||||
}:${proxy.port}/?${anytlsParams.join('&')}#${encodeURIComponent(
|
||||
proxy.name,
|
||||
)}`;
|
||||
break;
|
||||
case 'wireguard':
|
||||
let wireguardParams = [];
|
||||
|
||||
@ -653,7 +503,7 @@ export default function URI_Producer() {
|
||||
if (proxy[key]) {
|
||||
wireguardParams.push(`${key}=1`);
|
||||
}
|
||||
} else if (proxy[key] && !/^_/i.test(key)) {
|
||||
} else if (proxy[key]) {
|
||||
wireguardParams.push(
|
||||
`${key}=${encodeURIComponent(proxy[key])}`,
|
||||
);
|
||||
|
@ -11,7 +11,6 @@
|
||||
* @documentation: https://www.notion.so/Sub-Store-6259586994d34c11a4ced5c406264b46
|
||||
*/
|
||||
import { version } from '../package.json';
|
||||
import $ from '@/core/app';
|
||||
console.log(
|
||||
`
|
||||
┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
|
||||
@ -19,6 +18,7 @@ console.log(
|
||||
┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
|
||||
`,
|
||||
);
|
||||
|
||||
import migrate from '@/utils/migration';
|
||||
import serve from '@/restful';
|
||||
|
||||
|
@ -84,15 +84,12 @@ async function doSync() {
|
||||
const files = {};
|
||||
|
||||
try {
|
||||
const valid = [];
|
||||
const invalid = [];
|
||||
const allSubs = $.read(SUBS_KEY);
|
||||
const allCols = $.read(COLLECTIONS_KEY);
|
||||
const subNames = [];
|
||||
let enabledCount = 0;
|
||||
allArtifacts.map((artifact) => {
|
||||
if (artifact.sync && artifact.source) {
|
||||
enabledCount++;
|
||||
if (artifact.type === 'subscription') {
|
||||
const subName = artifact.source;
|
||||
const sub = findByName(allSubs, subName);
|
||||
@ -113,13 +110,6 @@ async function doSync() {
|
||||
}
|
||||
});
|
||||
|
||||
if (enabledCount === 0) {
|
||||
$.info(
|
||||
`需同步的配置: ${enabledCount}, 总数: ${allArtifacts.length}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (subNames.length > 0) {
|
||||
await Promise.all(
|
||||
subNames.map(async (subName) => {
|
||||
@ -166,46 +156,27 @@ async function doSync() {
|
||||
files[encodeURIComponent(artifact.name)] = {
|
||||
content: output,
|
||||
};
|
||||
|
||||
valid.push(artifact.name);
|
||||
}
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`生成同步配置 ${artifact.name} 发生错误: ${
|
||||
e.message ?? e
|
||||
}`,
|
||||
`同步配置 ${artifact.name} 发生错误: ${e.message ?? e}`,
|
||||
);
|
||||
invalid.push(artifact.name);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
$.info(`${valid.length} 个同步配置生成成功: ${valid.join(', ')}`);
|
||||
$.info(`${invalid.length} 个同步配置生成失败: ${invalid.join(', ')}`);
|
||||
|
||||
if (valid.length === 0) {
|
||||
if (invalid.length > 0) {
|
||||
throw new Error(
|
||||
`同步配置 ${invalid.join(', ')} 生成失败 详情请查看日志`,
|
||||
`同步配置 ${invalid.join(', ')} 发生错误 详情请查看日志`,
|
||||
);
|
||||
}
|
||||
|
||||
const resp = await syncToGist(files);
|
||||
const body = JSON.parse(resp.body);
|
||||
delete body.history;
|
||||
delete body.forks;
|
||||
delete body.owner;
|
||||
Object.values(body.files).forEach((file) => {
|
||||
delete file.content;
|
||||
});
|
||||
$.info('上传配置响应:');
|
||||
$.info(JSON.stringify(body, null, 2));
|
||||
|
||||
for (const artifact of allArtifacts) {
|
||||
if (
|
||||
artifact.sync &&
|
||||
artifact.source &&
|
||||
valid.includes(artifact.name)
|
||||
) {
|
||||
if (artifact.sync) {
|
||||
artifact.updated = new Date().getTime();
|
||||
// extract real url from gist
|
||||
let files = body.files;
|
||||
@ -233,18 +204,9 @@ async function doSync() {
|
||||
}
|
||||
|
||||
$.write(allArtifacts, ARTIFACTS_KEY);
|
||||
$.info('上传配置成功');
|
||||
|
||||
if (invalid.length > 0) {
|
||||
$.notify(
|
||||
'🌍 Sub-Store',
|
||||
`同步配置成功 ${valid.length} 个, 失败 ${invalid.length} 个, 详情请查看日志`,
|
||||
);
|
||||
} else {
|
||||
$.notify('🌍 Sub-Store', '同步配置完成');
|
||||
}
|
||||
$.notify('🌍 Sub-Store', '全部订阅同步成功!');
|
||||
} catch (e) {
|
||||
$.notify('🌍 Sub-Store', '同步配置失败', `原因:${e.message ?? e}`);
|
||||
$.error(`无法同步配置到 Gist,原因:${e}`);
|
||||
$.notify('🌍 Sub-Store', '同步订阅失败', `原因:${e.message ?? e}`);
|
||||
$.error(`无法同步订阅配置到 Gist,原因:${e}`);
|
||||
}
|
||||
}
|
||||
|
@ -14,12 +14,10 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : '';
|
||||
`
|
||||
┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
|
||||
Sub-Store -- v${version}
|
||||
Loon -- ${$loon}
|
||||
┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅┅
|
||||
`,
|
||||
);
|
||||
|
||||
const build = $loon.match(/\((\d+)\)$/)?.[1];
|
||||
let arg;
|
||||
if (typeof $argument != 'undefined') {
|
||||
arg = Object.fromEntries(
|
||||
@ -28,59 +26,42 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : '';
|
||||
} else {
|
||||
arg = {};
|
||||
}
|
||||
console.log(`arg: ${JSON.stringify(arg)}`);
|
||||
|
||||
const RESOURCE_TYPE = {
|
||||
PROXY: 1,
|
||||
RULE: 2,
|
||||
};
|
||||
if (!arg.resourceUrlOnly) {
|
||||
result = resource;
|
||||
}
|
||||
|
||||
result = resource;
|
||||
|
||||
if (resourceType === RESOURCE_TYPE.PROXY) {
|
||||
if (!arg.resourceUrlOnly) {
|
||||
try {
|
||||
let proxies = ProxyUtils.parse(resource);
|
||||
result = ProxyUtils.produce(proxies, 'Loon', undefined, {
|
||||
'include-unsupported-proxy':
|
||||
arg?.includeUnsupportedProxy || build >= 842,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('解析器: 使用 resource 出现错误');
|
||||
console.log(e.message ?? e);
|
||||
}
|
||||
try {
|
||||
let proxies = ProxyUtils.parse(resource);
|
||||
result = ProxyUtils.produce(proxies, 'Loon', undefined, {
|
||||
'include-unsupported-proxy': arg?.includeUnsupportedProxy,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('解析器: 使用 resource 出现错误');
|
||||
console.log(e.message ?? e);
|
||||
}
|
||||
if ((!result || /^\s*$/.test(result)) && resourceUrl) {
|
||||
console.log(`解析器: 尝试从 ${resourceUrl} 获取订阅`);
|
||||
try {
|
||||
let raw = await download(
|
||||
resourceUrl,
|
||||
arg?.ua,
|
||||
arg?.timeout,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
let raw = await download(resourceUrl, arg?.ua, arg?.timeout);
|
||||
let proxies = ProxyUtils.parse(raw);
|
||||
result = ProxyUtils.produce(proxies, 'Loon', undefined, {
|
||||
'include-unsupported-proxy':
|
||||
arg?.includeUnsupportedProxy || build >= 842,
|
||||
'include-unsupported-proxy': arg?.includeUnsupportedProxy,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(e.message ?? e);
|
||||
}
|
||||
}
|
||||
} else if (resourceType === RESOURCE_TYPE.RULE) {
|
||||
if (!arg.resourceUrlOnly) {
|
||||
try {
|
||||
const rules = RuleUtils.parse(resource);
|
||||
result = RuleUtils.produce(rules, 'Loon');
|
||||
} catch (e) {
|
||||
console.log(e.message ?? e);
|
||||
}
|
||||
try {
|
||||
const rules = RuleUtils.parse(resource);
|
||||
result = RuleUtils.produce(rules, 'Loon');
|
||||
} catch (e) {
|
||||
console.log(e.message ?? e);
|
||||
}
|
||||
if ((!result || /^\s*$/.test(result)) && resourceUrl) {
|
||||
console.log(`解析器: 尝试从 ${resourceUrl} 获取规则`);
|
||||
|
@ -1,9 +1,8 @@
|
||||
import { deleteByName, findByName, updateByName } from '@/utils/database';
|
||||
import { COLLECTIONS_KEY, ARTIFACTS_KEY, FILES_KEY } from '@/constants';
|
||||
import { COLLECTIONS_KEY, ARTIFACTS_KEY } from '@/constants';
|
||||
import { failed, success } from '@/restful/response';
|
||||
import $ from '@/core/app';
|
||||
import { RequestInvalidError, ResourceNotFoundError } from '@/restful/errors';
|
||||
import { formatDateTime } from '@/utils';
|
||||
|
||||
export default function register($app) {
|
||||
if (!$.read(COLLECTIONS_KEY)) $.write({}, COLLECTIONS_KEY);
|
||||
@ -51,25 +50,11 @@ function createCollection(req, res) {
|
||||
|
||||
function getCollection(req, res) {
|
||||
let { name } = req.params;
|
||||
let { raw } = req.query;
|
||||
name = decodeURIComponent(name);
|
||||
const allCols = $.read(COLLECTIONS_KEY);
|
||||
const collection = findByName(allCols, name);
|
||||
if (collection) {
|
||||
if (raw) {
|
||||
res.set('content-type', 'application/json')
|
||||
.set(
|
||||
'content-disposition',
|
||||
`attachment; filename="${encodeURIComponent(
|
||||
`sub-store_collection_${name}_${formatDateTime(
|
||||
new Date(),
|
||||
)}.json`,
|
||||
)}"`,
|
||||
)
|
||||
.send(JSON.stringify(collection));
|
||||
} else {
|
||||
success(res, collection);
|
||||
}
|
||||
success(res, collection);
|
||||
} else {
|
||||
failed(
|
||||
res,
|
||||
@ -106,18 +91,7 @@ function updateCollection(req, res) {
|
||||
artifact.source = newCol.name;
|
||||
}
|
||||
}
|
||||
// update all files referring this collection
|
||||
const allFiles = $.read(FILES_KEY) || [];
|
||||
for (const file of allFiles) {
|
||||
if (
|
||||
file.sourceType === 'collection' &&
|
||||
file.sourceName === oldCol.name
|
||||
) {
|
||||
file.sourceName = newCol.name;
|
||||
}
|
||||
}
|
||||
$.write(allArtifacts, ARTIFACTS_KEY);
|
||||
$.write(allFiles, FILES_KEY);
|
||||
}
|
||||
|
||||
updateByName(allCols, name, newCol);
|
||||
|
@ -1,11 +1,8 @@
|
||||
import {
|
||||
getPlatformFromHeaders,
|
||||
shouldIncludeUnsupportedProxy,
|
||||
} from '@/utils/user-agent';
|
||||
import { getPlatformFromHeaders } from '@/utils/user-agent';
|
||||
import { ProxyUtils } from '@/core/proxy-utils';
|
||||
import { COLLECTIONS_KEY, SUBS_KEY } from '@/constants';
|
||||
import { findByName } from '@/utils/database';
|
||||
import { getFlowHeaders, normalizeFlowHeader } from '@/utils/flow';
|
||||
import { getFlowHeaders } from '@/utils/flow';
|
||||
import $ from '@/core/app';
|
||||
import { failed } from '@/restful/response';
|
||||
import { InternalServerError, ResourceNotFoundError } from '@/restful/errors';
|
||||
@ -16,44 +13,11 @@ import { getISO } from '@/utils/geo';
|
||||
import env from '@/utils/env';
|
||||
|
||||
export default function register($app) {
|
||||
$app.get('/share/col/:name/:target', async (req, res) => {
|
||||
const { target } = req.params;
|
||||
if (target) {
|
||||
req.query.target = target;
|
||||
$.info(`使用路由指定目标: ${target}`);
|
||||
}
|
||||
await downloadCollection(req, res);
|
||||
});
|
||||
$app.get('/share/col/:name', downloadCollection);
|
||||
$app.get('/share/sub/:name/:target', async (req, res) => {
|
||||
const { target } = req.params;
|
||||
if (target) {
|
||||
req.query.target = target;
|
||||
$.info(`使用路由指定目标: ${target}`);
|
||||
}
|
||||
await downloadSubscription(req, res);
|
||||
});
|
||||
$app.get('/share/sub/:name', downloadSubscription);
|
||||
|
||||
$app.get('/download/collection/:name/:target', async (req, res) => {
|
||||
const { target } = req.params;
|
||||
if (target) {
|
||||
req.query.target = target;
|
||||
$.info(`使用路由指定目标: ${target}`);
|
||||
}
|
||||
await downloadCollection(req, res);
|
||||
});
|
||||
$app.get('/download/collection/:name', downloadCollection);
|
||||
$app.get('/download/:name/:target', async (req, res) => {
|
||||
const { target } = req.params;
|
||||
if (target) {
|
||||
req.query.target = target;
|
||||
$.info(`使用路由指定目标: ${target}`);
|
||||
}
|
||||
await downloadSubscription(req, res);
|
||||
});
|
||||
$app.get('/download/:name', downloadSubscription);
|
||||
|
||||
$app.get(
|
||||
'/download/collection/:name/api/v1/server/details',
|
||||
async (req, res) => {
|
||||
@ -95,9 +59,11 @@ async function downloadSubscription(req, res) {
|
||||
|
||||
const platform =
|
||||
req.query.target || getPlatformFromHeaders(req.headers) || 'JSON';
|
||||
const reqUA = req.headers['user-agent'] || req.headers['User-Agent'];
|
||||
|
||||
$.info(
|
||||
`正在下载订阅:${name}\n请求 User-Agent: ${reqUA}\n请求 target: ${req.query.target}\n实际输出: ${platform}`,
|
||||
`正在下载订阅:${name}\n请求 User-Agent: ${
|
||||
req.headers['user-agent'] || req.headers['User-Agent']
|
||||
}`,
|
||||
);
|
||||
let {
|
||||
url,
|
||||
@ -111,17 +77,7 @@ async function downloadSubscription(req, res) {
|
||||
proxy,
|
||||
noCache,
|
||||
} = req.query;
|
||||
let $options = {
|
||||
_req: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: req.params,
|
||||
headers: req.headers,
|
||||
body: req.body,
|
||||
},
|
||||
};
|
||||
let $options = {};
|
||||
if (req.query.$options) {
|
||||
try {
|
||||
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||
@ -142,14 +98,6 @@ async function downloadSubscription(req, res) {
|
||||
if (url) {
|
||||
url = decodeURIComponent(url);
|
||||
$.info(`指定远程订阅 URL: ${url}`);
|
||||
if (!/^https?:\/\//.test(url)) {
|
||||
content = url;
|
||||
$.info(`URL 不是链接,视为本地订阅`);
|
||||
}
|
||||
}
|
||||
if (content) {
|
||||
content = decodeURIComponent(content);
|
||||
$.info(`指定本地订阅: ${content}`);
|
||||
}
|
||||
if (proxy) {
|
||||
proxy = decodeURIComponent(proxy);
|
||||
@ -159,7 +107,10 @@ async function downloadSubscription(req, res) {
|
||||
ua = decodeURIComponent(ua);
|
||||
$.info(`指定远程订阅 User-Agent: ${ua}`);
|
||||
}
|
||||
|
||||
if (content) {
|
||||
content = decodeURIComponent(content);
|
||||
$.info(`指定本地订阅: ${content}`);
|
||||
}
|
||||
if (mergeSources) {
|
||||
mergeSources = decodeURIComponent(mergeSources);
|
||||
$.info(`指定合并来源: ${mergeSources}`);
|
||||
@ -174,19 +125,7 @@ async function downloadSubscription(req, res) {
|
||||
}
|
||||
if (includeUnsupportedProxy) {
|
||||
includeUnsupportedProxy = decodeURIComponent(includeUnsupportedProxy);
|
||||
$.info(
|
||||
`包含官方/商店版/未续费订阅不支持的协议: ${includeUnsupportedProxy}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!includeUnsupportedProxy &&
|
||||
shouldIncludeUnsupportedProxy(platform, reqUA)
|
||||
) {
|
||||
includeUnsupportedProxy = true;
|
||||
$.info(
|
||||
`当前客户端可包含官方/商店版/未续费订阅不支持的协议: ${includeUnsupportedProxy}`,
|
||||
);
|
||||
$.info(`包含不支持的节点: ${includeUnsupportedProxy}`);
|
||||
}
|
||||
|
||||
if (useMihomoExternal) {
|
||||
@ -201,13 +140,6 @@ async function downloadSubscription(req, res) {
|
||||
const sub = findByName(allSubs, name);
|
||||
if (sub) {
|
||||
try {
|
||||
const passThroughUA = sub.passThroughUA;
|
||||
if (passThroughUA) {
|
||||
$.info(
|
||||
`订阅开启了透传 User-Agent, 使用请求的 User-Agent: ${reqUA}`,
|
||||
);
|
||||
ua = reqUA;
|
||||
}
|
||||
let output = await produceArtifact({
|
||||
type: 'subscription',
|
||||
name,
|
||||
@ -259,7 +191,7 @@ async function downloadSubscription(req, res) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!$arguments.noFlow && /^https?/.test(url)) {
|
||||
if (!$arguments.noFlow) {
|
||||
// forward flow headers
|
||||
flowInfo = await getFlowHeaders(
|
||||
$arguments?.insecure ? `${url}#insecure` : url,
|
||||
@ -269,10 +201,7 @@ async function downloadSubscription(req, res) {
|
||||
$arguments.flowUrl,
|
||||
);
|
||||
if (flowInfo) {
|
||||
res.set(
|
||||
'subscription-userinfo',
|
||||
normalizeFlowHeader(flowInfo),
|
||||
);
|
||||
res.set('subscription-userinfo', flowInfo);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@ -284,31 +213,9 @@ async function downloadSubscription(req, res) {
|
||||
}
|
||||
}
|
||||
if (sub.subUserinfo) {
|
||||
let subUserInfo;
|
||||
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||
try {
|
||||
subUserInfo = await getFlowHeaders(
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
proxy || sub.proxy,
|
||||
sub.subUserinfo,
|
||||
);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`订阅 ${name} 使用自定义流量链接 ${
|
||||
sub.subUserinfo
|
||||
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
subUserInfo = sub.subUserinfo;
|
||||
}
|
||||
res.set(
|
||||
'subscription-userinfo',
|
||||
normalizeFlowHeader(
|
||||
[subUserInfo, flowInfo].filter((i) => i).join(';'),
|
||||
),
|
||||
[sub.subUserinfo, flowInfo].filter((i) => i).join('; '),
|
||||
);
|
||||
}
|
||||
|
||||
@ -348,7 +255,7 @@ async function downloadSubscription(req, res) {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$.error(`🌍 Sub-Store 下载订阅失败\n❌ 未找到订阅:${name}!`);
|
||||
$.error(`🌍 Sub-Store 下载订阅失败`, `❌ 未找到订阅:${name}!`);
|
||||
failed(
|
||||
res,
|
||||
new ResourceNotFoundError(
|
||||
@ -372,9 +279,11 @@ async function downloadCollection(req, res) {
|
||||
|
||||
const allCols = $.read(COLLECTIONS_KEY);
|
||||
const collection = findByName(allCols, name);
|
||||
const reqUA = req.headers['user-agent'] || req.headers['User-Agent'];
|
||||
|
||||
$.info(
|
||||
`正在下载组合订阅:${name}\n请求 User-Agent: ${reqUA}\n请求 target: ${req.query.target}\n实际输出: ${platform}`,
|
||||
`正在下载组合订阅:${name}\n请求 User-Agent: ${
|
||||
req.headers['user-agent'] || req.headers['User-Agent']
|
||||
}`,
|
||||
);
|
||||
|
||||
let {
|
||||
@ -386,17 +295,7 @@ async function downloadCollection(req, res) {
|
||||
noCache,
|
||||
} = req.query;
|
||||
|
||||
let $options = {
|
||||
_req: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: req.params,
|
||||
headers: req.headers,
|
||||
body: req.body,
|
||||
},
|
||||
};
|
||||
let $options = {};
|
||||
if (req.query.$options) {
|
||||
try {
|
||||
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||
@ -431,18 +330,7 @@ async function downloadCollection(req, res) {
|
||||
|
||||
if (includeUnsupportedProxy) {
|
||||
includeUnsupportedProxy = decodeURIComponent(includeUnsupportedProxy);
|
||||
$.info(
|
||||
`包含官方/商店版/未续费订阅不支持的协议: ${includeUnsupportedProxy}`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!includeUnsupportedProxy &&
|
||||
shouldIncludeUnsupportedProxy(platform, reqUA)
|
||||
) {
|
||||
includeUnsupportedProxy = true;
|
||||
$.info(
|
||||
`当前客户端可包含官方/商店版/未续费订阅不支持的协议: ${includeUnsupportedProxy}`,
|
||||
);
|
||||
$.info(`包含不支持的节点: ${includeUnsupportedProxy}`);
|
||||
}
|
||||
if (useMihomoExternal) {
|
||||
$.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`);
|
||||
@ -466,14 +354,14 @@ async function downloadCollection(req, res) {
|
||||
$options,
|
||||
proxy,
|
||||
noCache,
|
||||
ua: reqUA,
|
||||
});
|
||||
let subUserInfoOfSub;
|
||||
|
||||
// forward flow header from the first subscription in this collection
|
||||
const allSubs = $.read(SUBS_KEY);
|
||||
const subnames = collection.subscriptions;
|
||||
if (subnames.length > 0) {
|
||||
const sub = findByName(allSubs, subnames[0]);
|
||||
let flowInfo;
|
||||
if (
|
||||
sub.source !== 'local' ||
|
||||
['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
||||
@ -506,14 +394,17 @@ async function downloadCollection(req, res) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!$arguments.noFlow && /^https?:/.test(url)) {
|
||||
subUserInfoOfSub = await getFlowHeaders(
|
||||
if (!$arguments.noFlow) {
|
||||
flowInfo = await getFlowHeaders(
|
||||
$arguments?.insecure ? `${url}#insecure` : url,
|
||||
$arguments.flowUserAgent,
|
||||
undefined,
|
||||
proxy || sub.proxy || collection.proxy,
|
||||
$arguments.flowUrl,
|
||||
);
|
||||
if (flowInfo) {
|
||||
res.set('subscription-userinfo', flowInfo);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
$.error(
|
||||
@ -524,63 +415,13 @@ async function downloadCollection(req, res) {
|
||||
}
|
||||
}
|
||||
if (sub.subUserinfo) {
|
||||
let subUserInfo;
|
||||
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||
try {
|
||||
subUserInfo = await getFlowHeaders(
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
proxy || sub.proxy,
|
||||
sub.subUserinfo,
|
||||
);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`组合订阅 ${name} 使用自定义流量链接 ${
|
||||
sub.subUserinfo
|
||||
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
subUserInfo = sub.subUserinfo;
|
||||
}
|
||||
subUserInfoOfSub = [subUserInfo, subUserInfoOfSub]
|
||||
.filter((i) => i)
|
||||
.join('; ');
|
||||
res.set(
|
||||
'subscription-userinfo',
|
||||
[sub.subUserinfo, flowInfo].filter((i) => i).join('; '),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$.info(`组合订阅 ${name} 透传的的流量信息: ${subUserInfoOfSub}`);
|
||||
|
||||
let subUserInfoOfCol;
|
||||
if (/^https?:\/\//.test(collection.subUserinfo)) {
|
||||
try {
|
||||
subUserInfoOfCol = await getFlowHeaders(
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
proxy || collection.proxy,
|
||||
collection.subUserinfo,
|
||||
);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`组合订阅 ${name} 使用自定义流量链接 ${
|
||||
collection.subUserinfo
|
||||
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
subUserInfoOfCol = collection.subUserinfo;
|
||||
}
|
||||
const subUserInfo = [subUserInfoOfCol, subUserInfoOfSub]
|
||||
.filter((i) => i)
|
||||
.join('; ');
|
||||
if (subUserInfo) {
|
||||
res.set(
|
||||
'subscription-userinfo',
|
||||
normalizeFlowHeader(subUserInfo),
|
||||
);
|
||||
}
|
||||
if (platform === 'JSON') {
|
||||
if (resultFormat === 'nezha') {
|
||||
output = nezhaTransform(output);
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { deleteByName, findByName, updateByName } from '@/utils/database';
|
||||
import { getFlowHeaders, normalizeFlowHeader } from '@/utils/flow';
|
||||
import { FILES_KEY, ARTIFACTS_KEY } from '@/constants';
|
||||
import { getFlowHeaders } from '@/utils/flow';
|
||||
import { FILES_KEY } from '@/constants';
|
||||
import { failed, success } from '@/restful/response';
|
||||
import $ from '@/core/app';
|
||||
import {
|
||||
@ -9,7 +9,6 @@ import {
|
||||
InternalServerError,
|
||||
} from '@/restful/errors';
|
||||
import { produceArtifact } from '@/restful/sync';
|
||||
import { formatDateTime } from '@/utils';
|
||||
|
||||
export default function register($app) {
|
||||
if (!$.read(FILES_KEY)) $.write([], FILES_KEY);
|
||||
@ -52,8 +51,8 @@ function createFile(req, res) {
|
||||
async function getFile(req, res) {
|
||||
let { name } = req.params;
|
||||
name = decodeURIComponent(name);
|
||||
const reqUA = req.headers['user-agent'] || req.headers['User-Agent'];
|
||||
$.info(`正在下载文件:${name}\n请求 User-Agent: ${reqUA}`);
|
||||
|
||||
$.info(`正在下载文件:${name}`);
|
||||
let {
|
||||
url,
|
||||
subInfoUrl,
|
||||
@ -63,20 +62,8 @@ async function getFile(req, res) {
|
||||
mergeSources,
|
||||
ignoreFailedRemoteFile,
|
||||
proxy,
|
||||
noCache,
|
||||
produceType,
|
||||
} = req.query;
|
||||
let $options = {
|
||||
_req: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: req.params,
|
||||
headers: req.headers,
|
||||
body: req.body,
|
||||
},
|
||||
};
|
||||
let $options = {};
|
||||
if (req.query.$options) {
|
||||
try {
|
||||
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||
@ -126,13 +113,6 @@ async function getFile(req, res) {
|
||||
ignoreFailedRemoteFile = decodeURIComponent(ignoreFailedRemoteFile);
|
||||
$.info(`指定忽略失败的远程文件: ${ignoreFailedRemoteFile}`);
|
||||
}
|
||||
if (noCache) {
|
||||
$.info(`指定不使用缓存: ${noCache}`);
|
||||
}
|
||||
if (produceType) {
|
||||
produceType = decodeURIComponent(produceType);
|
||||
$.info(`指定生产类型: ${produceType}`);
|
||||
}
|
||||
|
||||
const allFiles = $.read(FILES_KEY);
|
||||
const file = findByName(allFiles, name);
|
||||
@ -148,9 +128,6 @@ async function getFile(req, res) {
|
||||
ignoreFailedRemoteFile,
|
||||
$options,
|
||||
proxy,
|
||||
noCache,
|
||||
produceType,
|
||||
all: true,
|
||||
});
|
||||
|
||||
try {
|
||||
@ -164,10 +141,7 @@ async function getFile(req, res) {
|
||||
proxy || file.proxy,
|
||||
);
|
||||
if (flowInfo) {
|
||||
res.set(
|
||||
'subscription-userinfo',
|
||||
normalizeFlowHeader(flowInfo),
|
||||
);
|
||||
res.set('subscription-userinfo', flowInfo);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@ -185,15 +159,9 @@ async function getFile(req, res) {
|
||||
)}`,
|
||||
);
|
||||
}
|
||||
res.set('Content-Type', 'text/plain; charset=utf-8');
|
||||
if (output?.$options?._res?.headers) {
|
||||
Object.entries(output.$options._res.headers).forEach(
|
||||
([key, value]) => {
|
||||
res.set(key, value);
|
||||
},
|
||||
);
|
||||
}
|
||||
res.send(output?.$content ?? '');
|
||||
res.set('Content-Type', 'text/plain; charset=utf-8').send(
|
||||
output ?? '',
|
||||
);
|
||||
} catch (err) {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 下载文件失败`,
|
||||
@ -211,7 +179,7 @@ async function getFile(req, res) {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$.error(`🌍 Sub-Store 下载文件失败\n❌ 未找到文件:${name}!`);
|
||||
$.error(`🌍 Sub-Store 下载文件失败`, `❌ 未找到文件:${name}!`);
|
||||
failed(
|
||||
res,
|
||||
new ResourceNotFoundError(
|
||||
@ -224,25 +192,11 @@ async function getFile(req, res) {
|
||||
}
|
||||
function getWholeFile(req, res) {
|
||||
let { name } = req.params;
|
||||
let { raw } = req.query;
|
||||
name = decodeURIComponent(name);
|
||||
const allFiles = $.read(FILES_KEY);
|
||||
const file = findByName(allFiles, name);
|
||||
if (file) {
|
||||
if (raw) {
|
||||
res.set('content-type', 'application/json')
|
||||
.set(
|
||||
'content-disposition',
|
||||
`attachment; filename="${encodeURIComponent(
|
||||
`sub-store_file_${name}_${formatDateTime(
|
||||
new Date(),
|
||||
)}.json`,
|
||||
)}"`,
|
||||
)
|
||||
.send(JSON.stringify(file));
|
||||
} else {
|
||||
success(res, file);
|
||||
}
|
||||
success(res, file);
|
||||
} else {
|
||||
failed(
|
||||
res,
|
||||
@ -268,20 +222,6 @@ function updateFile(req, res) {
|
||||
};
|
||||
$.info(`正在更新文件:${name}...`);
|
||||
|
||||
if (name !== newFile.name) {
|
||||
// update all artifacts referring this collection
|
||||
const allArtifacts = $.read(ARTIFACTS_KEY) || [];
|
||||
for (const artifact of allArtifacts) {
|
||||
if (
|
||||
artifact.type === 'file' &&
|
||||
artifact.source === oldFile.name
|
||||
) {
|
||||
artifact.source = newFile.name;
|
||||
}
|
||||
}
|
||||
$.write(allArtifacts, ARTIFACTS_KEY);
|
||||
}
|
||||
|
||||
updateByName(allFiles, name, newFile);
|
||||
$.write(allFiles, FILES_KEY);
|
||||
success(res, newFile);
|
||||
|
@ -1,8 +1,8 @@
|
||||
import express from '@/vendor/express';
|
||||
import $ from '@/core/app';
|
||||
import migrate from '@/utils/migration';
|
||||
import download, { downloadFile } from '@/utils/download';
|
||||
import { syncArtifacts, produceArtifact } from '@/restful/sync';
|
||||
import download from '@/utils/download';
|
||||
import { syncArtifacts } from '@/restful/sync';
|
||||
import { gistBackupAction } from '@/restful/miscs';
|
||||
import { TOKENS_KEY } from '@/constants';
|
||||
|
||||
@ -29,77 +29,6 @@ export default function serve() {
|
||||
host = eval('process.env.SUB_STORE_BACKEND_API_HOST') || '::';
|
||||
}
|
||||
const $app = express({ substore: $, port, host });
|
||||
if ($.env.isNode) {
|
||||
const be_merge = eval('process.env.SUB_STORE_BACKEND_MERGE');
|
||||
const be_prefix = eval('process.env.SUB_STORE_BACKEND_PREFIX');
|
||||
const fe_be_path = eval('process.env.SUB_STORE_FRONTEND_BACKEND_PATH');
|
||||
const fe_path = eval('process.env.SUB_STORE_FRONTEND_PATH');
|
||||
if (be_prefix || be_merge) {
|
||||
if (!fe_be_path.startsWith('/')) {
|
||||
throw new Error(
|
||||
'SUB_STORE_FRONTEND_BACKEND_PATH should start with /',
|
||||
);
|
||||
}
|
||||
if (be_merge) {
|
||||
$.info(`[BACKEND] MERGE mode is [ON].`);
|
||||
$.info(`[BACKEND && FRONTEND] ${host}:${port}`);
|
||||
}
|
||||
$.info(`[BACKEND PREFIX] ${host}:${port}${fe_be_path}`);
|
||||
$app.use((req, res, next) => {
|
||||
if (req.path.startsWith(fe_be_path)) {
|
||||
req.url = req.url.replace(fe_be_path, '') || '/';
|
||||
if (be_merge && req.url.startsWith('/api/')) {
|
||||
req.query['share'] = 'true';
|
||||
}
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const pathname =
|
||||
decodeURIComponent(req._parsedUrl.pathname) || '/';
|
||||
if (
|
||||
be_merge &&
|
||||
req.path.startsWith('/share/') &&
|
||||
req.query.token
|
||||
) {
|
||||
if (req.method.toLowerCase() !== 'get') {
|
||||
res.status(405).send('Method not allowed');
|
||||
return;
|
||||
}
|
||||
const tokens = $.read(TOKENS_KEY) || [];
|
||||
const token = tokens.find(
|
||||
(t) =>
|
||||
t.token === req.query.token &&
|
||||
`/share/${t.type}/${t.name}` === pathname &&
|
||||
(t.exp == null || t.exp > Date.now()),
|
||||
);
|
||||
if (token) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (be_merge && fe_path && req.path.indexOf('/', 1) == -1) {
|
||||
if (req.path.indexOf('.') == -1) {
|
||||
req.url = '/index.html';
|
||||
}
|
||||
const express_ = eval(`require("express")`);
|
||||
const mime_ = eval(`require("mime-types")`);
|
||||
const path_ = eval(`require("path")`);
|
||||
const staticFileMiddleware = express_.static(fe_path, {
|
||||
setHeaders: (res, path) => {
|
||||
const type = mime_.contentType(path_.extname(path));
|
||||
if (type) {
|
||||
res.set('Content-Type', type);
|
||||
}
|
||||
},
|
||||
});
|
||||
staticFileMiddleware(req, res, next);
|
||||
return;
|
||||
}
|
||||
res.status(403).end('Forbbiden');
|
||||
return;
|
||||
});
|
||||
}
|
||||
}
|
||||
// register routes
|
||||
registerCollectionRoutes($app);
|
||||
registerSubscriptionRoutes($app);
|
||||
@ -146,39 +75,6 @@ export default function serve() {
|
||||
// 'Asia/Shanghai' // timeZone
|
||||
);
|
||||
}
|
||||
// 格式: 0 */2 * * *,sub,a;0 */3 * * *,col,b
|
||||
// 每 2 小时处理一次单条订阅 a, 每 3 小时处理一次组合订阅 b
|
||||
const produce_cron = eval('process.env.SUB_STORE_PRODUCE_CRON');
|
||||
if (produce_cron) {
|
||||
$.info(`[PRODUCE CRON] ${produce_cron} enabled`);
|
||||
const { CronJob } = eval(`require("cron")`);
|
||||
produce_cron.split(/\s*;\s*/).map((item) => {
|
||||
const [cron, type, name] = item.split(/\s*,\s*/);
|
||||
new CronJob(
|
||||
cron.trim(),
|
||||
async function () {
|
||||
try {
|
||||
$.info(
|
||||
`[PRODUCE CRON] ${type} ${name} ${cron} started`,
|
||||
);
|
||||
await produceArtifact({ type, name });
|
||||
$.info(
|
||||
`[PRODUCE CRON] ${type} ${name} ${cron} finished`,
|
||||
);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`[PRODUCE CRON] ${type} ${name} ${cron} error: ${
|
||||
e.message ?? e
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}, // onTick
|
||||
null, // onComplete
|
||||
true, // start
|
||||
// 'Asia/Shanghai' // timeZone
|
||||
);
|
||||
});
|
||||
}
|
||||
const backend_download_cron = eval(
|
||||
'process.env.SUB_STORE_BACKEND_DOWNLOAD_CRON',
|
||||
);
|
||||
@ -235,60 +131,6 @@ export default function serve() {
|
||||
// 'Asia/Shanghai' // timeZone
|
||||
);
|
||||
}
|
||||
const mmdb_cron = eval('process.env.SUB_STORE_MMDB_CRON');
|
||||
const countryFile = eval('process.env.SUB_STORE_MMDB_COUNTRY_PATH');
|
||||
const countryUrl = eval('process.env.SUB_STORE_MMDB_COUNTRY_URL');
|
||||
const asnFile = eval('process.env.SUB_STORE_MMDB_ASN_PATH');
|
||||
const asnUrl = eval('process.env.SUB_STORE_MMDB_ASN_URL');
|
||||
if (mmdb_cron && ((countryFile && countryUrl) || (asnFile && asnUrl))) {
|
||||
$.info(`[MMDB CRON] ${mmdb_cron} enabled`);
|
||||
const { CronJob } = eval(`require("cron")`);
|
||||
new CronJob(
|
||||
mmdb_cron,
|
||||
async function () {
|
||||
try {
|
||||
$.info(`[MMDB CRON] ${mmdb_cron} started`);
|
||||
if (countryFile && countryUrl) {
|
||||
try {
|
||||
$.info(
|
||||
`[MMDB CRON] downloading ${countryUrl} to ${countryFile}`,
|
||||
);
|
||||
await downloadFile(countryUrl, countryFile);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`[MMDB CRON] ${countryUrl} download failed: ${
|
||||
e.message ?? e
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (asnFile && asnUrl) {
|
||||
try {
|
||||
$.info(
|
||||
`[MMDB CRON] downloading ${asnUrl} to ${asnFile}`,
|
||||
);
|
||||
await downloadFile(asnUrl, asnFile);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`[MMDB CRON] ${asnUrl} download failed: ${
|
||||
e.message ?? e
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$.info(`[MMDB CRON] ${mmdb_cron} finished`);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`[MMDB CRON] ${mmdb_cron} error: ${e.message ?? e}`,
|
||||
);
|
||||
}
|
||||
}, // onTick
|
||||
null, // onComplete
|
||||
true, // start
|
||||
// 'Asia/Shanghai' // timeZone
|
||||
);
|
||||
}
|
||||
const path = eval(`require("path")`);
|
||||
const fs = eval(`require("fs")`);
|
||||
const data_url = eval('process.env.SUB_STORE_DATA_URL');
|
||||
@ -300,8 +142,7 @@ export default function serve() {
|
||||
const fe_abs_path = path.resolve(
|
||||
fe_path || path.join(__dirname, 'frontend'),
|
||||
);
|
||||
const be_merge = eval('process.env.SUB_STORE_BACKEND_MERGE');
|
||||
if (fe_path && !be_merge) {
|
||||
if (fe_path) {
|
||||
try {
|
||||
fs.accessSync(path.join(fe_abs_path, 'index.html'));
|
||||
} catch (e) {
|
||||
@ -320,15 +161,11 @@ export default function serve() {
|
||||
|
||||
const staticFileMiddleware = express_.static(fe_path);
|
||||
|
||||
let be_share_rewrite = '/share/:type/:name';
|
||||
let be_api_rewrite = '';
|
||||
let be_download_rewrite = '';
|
||||
let be_api = '/api/';
|
||||
let be_download = '/download/';
|
||||
let be_share = '/share/';
|
||||
let be_download_rewrite = '';
|
||||
let be_api_rewrite = '';
|
||||
let be_share_rewrite = `${be_share}:type/:name`;
|
||||
let prefix = eval('process.env.SUB_STORE_BACKEND_PREFIX')
|
||||
? fe_be_path
|
||||
: '';
|
||||
if (fe_be_path) {
|
||||
if (!fe_be_path.startsWith('/')) {
|
||||
throw new Error(
|
||||
@ -345,9 +182,9 @@ export default function serve() {
|
||||
app.use(
|
||||
be_share_rewrite,
|
||||
createProxyMiddleware({
|
||||
target: `http://127.0.0.1:${port}${prefix}`,
|
||||
target: `http://127.0.0.1:${port}`,
|
||||
changeOrigin: true,
|
||||
pathRewrite: async (path, req) => {
|
||||
pathRewrite: (path, req) => {
|
||||
if (req.method.toLowerCase() !== 'get')
|
||||
throw new Error('Method not allowed');
|
||||
const tokens = $.read(TOKENS_KEY) || [];
|
||||
@ -359,26 +196,34 @@ export default function serve() {
|
||||
(t.exp == null || t.exp > Date.now()),
|
||||
);
|
||||
if (!token) throw new Error('Forbbiden');
|
||||
return req.originalUrl;
|
||||
return path;
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use(
|
||||
be_api_rewrite,
|
||||
createProxyMiddleware({
|
||||
target: `http://127.0.0.1:${port}${prefix}${be_api}`,
|
||||
pathRewrite: async (path) => {
|
||||
return path.includes('?')
|
||||
? `${path}&share=true`
|
||||
: `${path}?share=true`;
|
||||
target: `http://127.0.0.1:${port}`,
|
||||
pathRewrite: (path) => {
|
||||
const newPath = path.startsWith(be_api_rewrite)
|
||||
? path.replace(be_api_rewrite, be_api)
|
||||
: path;
|
||||
return newPath.includes('?')
|
||||
? `${newPath}&share=true`
|
||||
: `${newPath}?share=true`;
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use(
|
||||
be_download_rewrite,
|
||||
createProxyMiddleware({
|
||||
target: `http://127.0.0.1:${port}${prefix}${be_download}`,
|
||||
target: `http://127.0.0.1:${port}`,
|
||||
changeOrigin: true,
|
||||
pathRewrite: (path) => {
|
||||
return path.startsWith(be_download_rewrite)
|
||||
? path.replace(be_download_rewrite, be_download)
|
||||
: path;
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@ -398,10 +243,10 @@ export default function serve() {
|
||||
$.info(`[FRONTEND] ${fe_address}:${fe_port}`);
|
||||
if (fe_be_path) {
|
||||
$.info(
|
||||
`[FRONTEND -> BACKEND] ${fe_address}:${fe_port}${be_api_rewrite} -> ${host}:${port}${prefix}${be_api}`,
|
||||
`[FRONTEND -> BACKEND] ${fe_address}:${fe_port}${be_api_rewrite} -> http://127.0.0.1:${port}${be_api}`,
|
||||
);
|
||||
$.info(
|
||||
`[FRONTEND -> BACKEND] ${fe_address}:${fe_port}${be_download_rewrite} -> ${host}:${port}${prefix}${be_download}`,
|
||||
`[FRONTEND -> BACKEND] ${fe_address}:${fe_port}${be_download_rewrite} -> http://127.0.0.1:${port}${be_download}`,
|
||||
);
|
||||
$.info(
|
||||
`[SHARE BACKEND] ${fe_address}:${fe_port}${be_share_rewrite}`,
|
||||
|
@ -14,7 +14,6 @@ import { InternalServerError, RequestInvalidError } from '@/restful/errors';
|
||||
import Gist from '@/utils/gist';
|
||||
import migrate from '@/utils/migration';
|
||||
import env from '@/utils/env';
|
||||
import { formatDateTime } from '@/utils';
|
||||
|
||||
export default function register($app) {
|
||||
// utils
|
||||
@ -28,9 +27,7 @@ export default function register($app) {
|
||||
res.set('content-type', 'application/json')
|
||||
.set(
|
||||
'content-disposition',
|
||||
`attachment; filename="${encodeURIComponent(
|
||||
`sub-store_data_${formatDateTime(new Date())}.json`,
|
||||
)}"`,
|
||||
'attachment; filename="sub-store.json"',
|
||||
)
|
||||
.send(
|
||||
$.env.isNode
|
||||
@ -49,17 +46,11 @@ export default function register($app) {
|
||||
success(res);
|
||||
});
|
||||
|
||||
if (ENV().isNode) {
|
||||
$app.get('/', getEnv);
|
||||
} else {
|
||||
// Redirect sub.store to vercel webpage
|
||||
$app.get('/', async (req, res) => {
|
||||
// 302 redirect
|
||||
res.set('location', 'https://sub-store.vercel.app/')
|
||||
.status(302)
|
||||
.end();
|
||||
});
|
||||
}
|
||||
// Redirect sub.store to vercel webpage
|
||||
$app.get('/', async (req, res) => {
|
||||
// 302 redirect
|
||||
res.set('location', 'https://sub-store.vercel.app/').status(302).end();
|
||||
});
|
||||
|
||||
// handle preflight request for QX
|
||||
if (ENV().isQX) {
|
||||
@ -77,19 +68,7 @@ function getEnv(req, res) {
|
||||
if (req.query.share) {
|
||||
env.feature.share = true;
|
||||
}
|
||||
res.set('Content-Type', 'application/json;charset=UTF-8').send(
|
||||
JSON.stringify(
|
||||
{
|
||||
status: 'success',
|
||||
data: {
|
||||
guide: '⚠️⚠️⚠️ 您当前看到的是后端的响应. 若想配合前端使用, 可访问官方前端 https://sub-store.vercel.app 后自行配置后端地址, 或一键配置后端 https://sub-store.vercel.app?api=https://a.com/xxx (假设 https://a.com 是你后端的域名, /xxx 是自定义路径). 需注意 HTTPS 前端无法请求非本地的 HTTP 后端(部分浏览器上也无法访问本地 HTTP 后端). 请配置反代或在局域网自建 HTTP 前端. 如果还有问题, 可查看此排查说明: https://t.me/zhetengsha/1068',
|
||||
...env,
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
success(res, env);
|
||||
}
|
||||
|
||||
async function refresh(_, res) {
|
||||
@ -119,21 +98,6 @@ async function gistBackupAction(action) {
|
||||
const updated = settings.syncTime;
|
||||
switch (action) {
|
||||
case 'upload':
|
||||
try {
|
||||
content = $.read('#sub-store');
|
||||
if ($.env.isNode) content = JSON.stringify($.cache, null, ` `);
|
||||
$.info(`下载备份, 与本地内容对比...`);
|
||||
const onlineContent = await gist.download(
|
||||
GIST_BACKUP_FILE_NAME,
|
||||
);
|
||||
if (onlineContent === content) {
|
||||
$.info(`内容一致, 无需上传备份`);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
$.error(`${error.message ?? error}`);
|
||||
}
|
||||
|
||||
// update syncTime
|
||||
settings.syncTime = new Date().getTime();
|
||||
$.write(settings, SETTINGS_KEY);
|
||||
|
@ -15,60 +15,46 @@ export default function register($app) {
|
||||
async function previewFile(req, res) {
|
||||
try {
|
||||
const file = req.body;
|
||||
let content = '';
|
||||
if (file.type !== 'mihomoProfile') {
|
||||
if (
|
||||
file.source === 'local' &&
|
||||
!['localFirst', 'remoteFirst'].includes(file.mergeSources)
|
||||
) {
|
||||
content = file.content;
|
||||
} else {
|
||||
const errors = {};
|
||||
content = await Promise.all(
|
||||
file.url
|
||||
.split(/[\r\n]+/)
|
||||
.map((i) => i.trim())
|
||||
.filter((i) => i.length)
|
||||
.map(async (url) => {
|
||||
try {
|
||||
return await download(
|
||||
url,
|
||||
file.ua,
|
||||
undefined,
|
||||
file.proxy,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
$.error(
|
||||
`文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`,
|
||||
);
|
||||
return '';
|
||||
}
|
||||
}),
|
||||
);
|
||||
let content;
|
||||
if (
|
||||
file.source === 'local' &&
|
||||
!['localFirst', 'remoteFirst'].includes(file.mergeSources)
|
||||
) {
|
||||
content = file.content;
|
||||
} else {
|
||||
const errors = {};
|
||||
content = await Promise.all(
|
||||
file.url
|
||||
.split(/[\r\n]+/)
|
||||
.map((i) => i.trim())
|
||||
.filter((i) => i.length)
|
||||
.map(async (url) => {
|
||||
try {
|
||||
return await download(url, file.ua);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
$.error(
|
||||
`文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`,
|
||||
);
|
||||
return '';
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!file.ignoreFailedRemoteFile) {
|
||||
throw new Error(
|
||||
`文件 ${file.name} 的远程文件 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (file.ignoreFailedRemoteFile === 'enabled') {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 预览文件失败`,
|
||||
`❌ ${file.name}`,
|
||||
`远程文件 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (file.mergeSources === 'localFirst') {
|
||||
content.unshift(file.content);
|
||||
} else if (file.mergeSources === 'remoteFirst') {
|
||||
content.push(file.content);
|
||||
}
|
||||
if (
|
||||
!file.ignoreFailedRemoteFile &&
|
||||
Object.keys(errors).length > 0
|
||||
) {
|
||||
throw new Error(
|
||||
`文件 ${file.name} 的远程文件 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (file.mergeSources === 'localFirst') {
|
||||
content.unshift(file.content);
|
||||
} else if (file.mergeSources === 'remoteFirst') {
|
||||
content.push(file.content);
|
||||
}
|
||||
}
|
||||
// parse proxies
|
||||
@ -81,7 +67,7 @@ async function previewFile(req, res) {
|
||||
const processed =
|
||||
Array.isArray(file.process) && file.process.length > 0
|
||||
? await ProxyUtils.process(
|
||||
{ $files: files, $content: filesContent, $file: file },
|
||||
{ $files: files, $content: filesContent },
|
||||
file.process,
|
||||
)
|
||||
: { $content: filesContent, $files: files };
|
||||
@ -128,10 +114,6 @@ async function compareSub(req, res) {
|
||||
sub.ua,
|
||||
undefined,
|
||||
sub.proxy,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
@ -143,22 +125,12 @@ async function compareSub(req, res) {
|
||||
}),
|
||||
);
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!sub.ignoreFailedRemoteSub) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (sub.ignoreFailedRemoteSub === 'enabled') {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 预览订阅失败`,
|
||||
`❌ ${sub.name}`,
|
||||
`远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (!sub.ignoreFailedRemoteSub && Object.keys(errors).length > 0) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (sub.mergeSources === 'localFirst') {
|
||||
content.unshift(sub.content);
|
||||
@ -247,10 +219,6 @@ async function compareCollection(req, res) {
|
||||
sub.ua,
|
||||
undefined,
|
||||
sub.proxy,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
@ -261,25 +229,15 @@ async function compareCollection(req, res) {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!sub.ignoreFailedRemoteSub) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (
|
||||
sub.ignoreFailedRemoteSub === 'enabled'
|
||||
) {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 预览订阅失败`,
|
||||
`❌ ${sub.name}`,
|
||||
`远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!sub.ignoreFailedRemoteSub &&
|
||||
Object.keys(errors).length > 0
|
||||
) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (sub.mergeSources === 'localFirst') {
|
||||
raw.unshift(sub.content);
|
||||
@ -311,28 +269,20 @@ async function compareCollection(req, res) {
|
||||
errors[name] = err;
|
||||
|
||||
$.error(
|
||||
`❌ 处理组合订阅 ${collection.name} 中的子订阅: ${sub.name} 时出现错误:${err}!`,
|
||||
`❌ 处理组合订阅 ${collection.name} 中的子订阅: ${sub.name}时出现错误:${err}!`,
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!collection.ignoreFailedRemoteSub) {
|
||||
throw new Error(
|
||||
`组合订阅 ${collection.name} 的子订阅 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (collection.ignoreFailedRemoteSub === 'enabled') {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 预览组合订阅失败`,
|
||||
`❌ ${collection.name}`,
|
||||
`子订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!collection.ignoreFailedRemoteSub &&
|
||||
Object.keys(errors).length > 0
|
||||
) {
|
||||
throw new Error(
|
||||
`组合订阅 ${collection.name} 中的子订阅 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
// merge proxies with the original order
|
||||
const original = Array.prototype.concat.apply(
|
||||
|
@ -134,15 +134,11 @@ export async function updateArtifactStore() {
|
||||
settings.artifactStore = url;
|
||||
settings.artifactStoreStatus = 'VALID';
|
||||
} else {
|
||||
$.error(`找不到 Sub-Store Gist (${ARTIFACT_REPOSITORY_KEY})`);
|
||||
$.error(`找不到 Sub-Store Gist`);
|
||||
settings.artifactStoreStatus = 'NOT FOUND';
|
||||
}
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`查找 Sub-Store Gist (${ARTIFACT_REPOSITORY_KEY}) 时发生错误: ${
|
||||
err.message ?? err
|
||||
}`,
|
||||
);
|
||||
$.error(`查找 Sub-Store Gist 时发生错误: ${err.message ?? err}`);
|
||||
settings.artifactStoreStatus = 'ERROR';
|
||||
}
|
||||
$.write(settings, SETTINGS_KEY);
|
||||
|
@ -5,12 +5,7 @@ import {
|
||||
RequestInvalidError,
|
||||
} from './errors';
|
||||
import { deleteByName, findByName, updateByName } from '@/utils/database';
|
||||
import {
|
||||
SUBS_KEY,
|
||||
COLLECTIONS_KEY,
|
||||
ARTIFACTS_KEY,
|
||||
FILES_KEY,
|
||||
} from '@/constants';
|
||||
import { SUBS_KEY, COLLECTIONS_KEY, ARTIFACTS_KEY } from '@/constants';
|
||||
import {
|
||||
getFlowHeaders,
|
||||
parseFlowHeaders,
|
||||
@ -18,7 +13,6 @@ import {
|
||||
} from '@/utils/flow';
|
||||
import { success, failed } from './response';
|
||||
import $ from '@/core/app';
|
||||
import { formatDateTime } from '@/utils';
|
||||
|
||||
if (!$.read(SUBS_KEY)) $.write({}, SUBS_KEY);
|
||||
|
||||
@ -63,29 +57,9 @@ async function getFlowInfo(req, res) {
|
||||
!['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
||||
) {
|
||||
if (sub.subUserinfo) {
|
||||
let subUserInfo;
|
||||
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||
try {
|
||||
subUserInfo = await getFlowHeaders(
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
sub.proxy,
|
||||
sub.subUserinfo,
|
||||
);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`订阅 ${name} 使用自定义流量链接 ${
|
||||
sub.subUserinfo
|
||||
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
subUserInfo = sub.subUserinfo;
|
||||
}
|
||||
try {
|
||||
success(res, {
|
||||
...parseFlowHeaders(subUserInfo),
|
||||
...parseFlowHeaders(sub.subUserinfo),
|
||||
});
|
||||
} catch (e) {
|
||||
$.error(
|
||||
@ -140,7 +114,7 @@ async function getFlowInfo(req, res) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($arguments.noFlow || !/^https?/.test(url)) {
|
||||
if ($arguments.noFlow) {
|
||||
failed(
|
||||
res,
|
||||
new RequestInvalidError(
|
||||
@ -175,29 +149,9 @@ async function getFlowInfo(req, res) {
|
||||
startDate: $arguments.startDate,
|
||||
cycleDays: $arguments.cycleDays,
|
||||
});
|
||||
let subUserInfo;
|
||||
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||
try {
|
||||
subUserInfo = await getFlowHeaders(
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
sub.proxy,
|
||||
sub.subUserinfo,
|
||||
);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`订阅 ${name} 使用自定义流量链接 ${
|
||||
sub.subUserinfo
|
||||
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
subUserInfo = sub.subUserinfo;
|
||||
}
|
||||
const result = {
|
||||
...parseFlowHeaders(
|
||||
[subUserInfo, flowHeaders].filter((i) => i).join('; '),
|
||||
[sub.subUserinfo, flowHeaders].filter((i) => i).join('; '),
|
||||
),
|
||||
};
|
||||
if (remainingDays != null) {
|
||||
@ -270,11 +224,7 @@ function getSubscription(req, res) {
|
||||
res.set('content-type', 'application/json')
|
||||
.set(
|
||||
'content-disposition',
|
||||
`attachment; filename="${encodeURIComponent(
|
||||
`sub-store_subscription_${name}_${formatDateTime(
|
||||
new Date(),
|
||||
)}.json`,
|
||||
)}"`,
|
||||
`attachment; filename="${encodeURIComponent(name)}.json"`,
|
||||
)
|
||||
.send(JSON.stringify(sub));
|
||||
} else {
|
||||
@ -325,20 +275,9 @@ function updateSubscription(req, res) {
|
||||
artifact.source = sub.name;
|
||||
}
|
||||
}
|
||||
// update all files referring this subscription
|
||||
const allFiles = $.read(FILES_KEY) || [];
|
||||
for (const file of allFiles) {
|
||||
if (
|
||||
file.sourceType === 'subscription' &&
|
||||
file.sourceName == name
|
||||
) {
|
||||
file.sourceName = sub.name;
|
||||
}
|
||||
}
|
||||
|
||||
$.write(allCols, COLLECTIONS_KEY);
|
||||
$.write(allArtifacts, ARTIFACTS_KEY);
|
||||
$.write(allFiles, FILES_KEY);
|
||||
}
|
||||
updateByName(allSubs, name, newSub);
|
||||
$.write(allSubs, SUBS_KEY);
|
||||
|
@ -40,11 +40,10 @@ async function produceArtifact({
|
||||
$options,
|
||||
proxy,
|
||||
noCache,
|
||||
all,
|
||||
}) {
|
||||
platform = platform || 'JSON';
|
||||
|
||||
if (['subscription', 'sub'].includes(type)) {
|
||||
if (type === 'subscription') {
|
||||
let sub;
|
||||
if (name) {
|
||||
const allSubs = $.read(SUBS_KEY);
|
||||
@ -74,8 +73,7 @@ async function produceArtifact({
|
||||
proxy || sub.proxy,
|
||||
undefined,
|
||||
awaitCustomCache,
|
||||
noCache || sub.noCache,
|
||||
true,
|
||||
noCache,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
@ -90,23 +88,12 @@ async function produceArtifact({
|
||||
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
|
||||
subIgnoreFailedRemoteSub = ignoreFailedRemoteSub;
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!subIgnoreFailedRemoteSub) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (subIgnoreFailedRemoteSub === 'enabled') {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 处理订阅失败`,
|
||||
`❌ ${sub.name}`,
|
||||
`远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (!subIgnoreFailedRemoteSub && Object.keys(errors).length > 0) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (mergeSources === 'localFirst') {
|
||||
raw.unshift(content);
|
||||
@ -134,8 +121,7 @@ async function produceArtifact({
|
||||
proxy || sub.proxy,
|
||||
undefined,
|
||||
awaitCustomCache,
|
||||
noCache || sub.noCache,
|
||||
true,
|
||||
noCache,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
@ -150,23 +136,12 @@ async function produceArtifact({
|
||||
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
|
||||
subIgnoreFailedRemoteSub = ignoreFailedRemoteSub;
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!subIgnoreFailedRemoteSub) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (subIgnoreFailedRemoteSub === 'enabled') {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 处理订阅失败`,
|
||||
`❌ ${sub.name}`,
|
||||
`远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (!subIgnoreFailedRemoteSub && Object.keys(errors).length > 0) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (sub.mergeSources === 'localFirst') {
|
||||
raw.unshift(sub.content);
|
||||
@ -174,9 +149,6 @@ async function produceArtifact({
|
||||
raw.push(sub.content);
|
||||
}
|
||||
}
|
||||
if (produceType === 'raw') {
|
||||
return JSON.stringify((Array.isArray(raw) ? raw : [raw]).flat());
|
||||
}
|
||||
// parse proxies
|
||||
let proxies = (Array.isArray(raw) ? raw : [raw])
|
||||
.map((i) => ProxyUtils.parse(i))
|
||||
@ -216,7 +188,7 @@ async function produceArtifact({
|
||||
}
|
||||
// produce
|
||||
return ProxyUtils.produce(proxies, platform, produceType, produceOpts);
|
||||
} else if (['collection', 'col'].includes(type)) {
|
||||
} else if (type === 'collection') {
|
||||
const allSubs = $.read(SUBS_KEY);
|
||||
const allCols = $.read(COLLECTIONS_KEY);
|
||||
const collection = findByName(allCols, name);
|
||||
@ -242,14 +214,6 @@ async function produceArtifact({
|
||||
await Promise.all(
|
||||
subnames.map(async (name) => {
|
||||
const sub = findByName(allSubs, name);
|
||||
const passThroughUA = sub.passThroughUA;
|
||||
let reqUA = sub.ua;
|
||||
if (passThroughUA) {
|
||||
$.info(
|
||||
`订阅开启了透传 User-Agent, 使用请求的 User-Agent: ${ua}`,
|
||||
);
|
||||
reqUA = ua;
|
||||
}
|
||||
try {
|
||||
$.info(`正在处理子订阅:${sub.name}...`);
|
||||
let raw;
|
||||
@ -271,15 +235,14 @@ async function produceArtifact({
|
||||
try {
|
||||
return await download(
|
||||
url,
|
||||
reqUA,
|
||||
sub.ua,
|
||||
undefined,
|
||||
proxy ||
|
||||
sub.proxy ||
|
||||
collection.proxy,
|
||||
undefined,
|
||||
undefined,
|
||||
noCache || sub.noCache,
|
||||
true,
|
||||
noCache,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
@ -290,25 +253,15 @@ async function produceArtifact({
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!sub.ignoreFailedRemoteSub) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (
|
||||
sub.ignoreFailedRemoteSub === 'enabled'
|
||||
) {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 处理订阅失败`,
|
||||
`❌ ${sub.name}`,
|
||||
`远程订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!sub.ignoreFailedRemoteSub &&
|
||||
Object.keys(errors).length > 0
|
||||
) {
|
||||
throw new Error(
|
||||
`订阅 ${sub.name} 的远程订阅 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (sub.mergeSources === 'localFirst') {
|
||||
raw.unshift(sub.content);
|
||||
@ -363,23 +316,15 @@ async function produceArtifact({
|
||||
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
|
||||
collectionIgnoreFailedRemoteSub = ignoreFailedRemoteSub;
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!collectionIgnoreFailedRemoteSub) {
|
||||
throw new Error(
|
||||
`组合订阅 ${collection.name} 的子订阅 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (collectionIgnoreFailedRemoteSub === 'enabled') {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 处理组合订阅失败`,
|
||||
`❌ ${collection.name}`,
|
||||
`子订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!collectionIgnoreFailedRemoteSub &&
|
||||
Object.keys(errors).length > 0
|
||||
) {
|
||||
throw new Error(
|
||||
`组合订阅 ${name} 中的子订阅 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
|
||||
// merge proxies with the original order
|
||||
@ -454,128 +399,106 @@ async function produceArtifact({
|
||||
const allFiles = $.read(FILES_KEY);
|
||||
const file = findByName(allFiles, name);
|
||||
if (!file) throw new Error(`找不到文件 ${name}`);
|
||||
let raw = '';
|
||||
if (file.type !== 'mihomoProfile') {
|
||||
let raw;
|
||||
if (content && !['localFirst', 'remoteFirst'].includes(mergeSources)) {
|
||||
raw = content;
|
||||
} else if (url) {
|
||||
const errors = {};
|
||||
raw = await Promise.all(
|
||||
url
|
||||
.split(/[\r\n]+/)
|
||||
.map((i) => i.trim())
|
||||
.filter((i) => i.length)
|
||||
.map(async (url) => {
|
||||
try {
|
||||
return await download(
|
||||
url,
|
||||
ua || file.ua,
|
||||
undefined,
|
||||
file.proxy || proxy,
|
||||
undefined,
|
||||
undefined,
|
||||
noCache,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
$.error(
|
||||
`文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`,
|
||||
);
|
||||
return '';
|
||||
}
|
||||
}),
|
||||
);
|
||||
let fileIgnoreFailedRemoteFile = file.ignoreFailedRemoteFile;
|
||||
if (
|
||||
content &&
|
||||
!['localFirst', 'remoteFirst'].includes(mergeSources)
|
||||
ignoreFailedRemoteFile != null &&
|
||||
ignoreFailedRemoteFile !== ''
|
||||
) {
|
||||
raw = content;
|
||||
} else if (url) {
|
||||
const errors = {};
|
||||
raw = await Promise.all(
|
||||
url
|
||||
.split(/[\r\n]+/)
|
||||
.map((i) => i.trim())
|
||||
.filter((i) => i.length)
|
||||
.map(async (url) => {
|
||||
try {
|
||||
return await download(
|
||||
url,
|
||||
ua || file.ua,
|
||||
undefined,
|
||||
file.proxy || proxy,
|
||||
undefined,
|
||||
undefined,
|
||||
noCache,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
$.error(
|
||||
`文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`,
|
||||
);
|
||||
return '';
|
||||
}
|
||||
}),
|
||||
);
|
||||
let fileIgnoreFailedRemoteFile = file.ignoreFailedRemoteFile;
|
||||
if (
|
||||
ignoreFailedRemoteFile != null &&
|
||||
ignoreFailedRemoteFile !== ''
|
||||
) {
|
||||
fileIgnoreFailedRemoteFile = ignoreFailedRemoteFile;
|
||||
}
|
||||
if (
|
||||
!fileIgnoreFailedRemoteFile &&
|
||||
Object.keys(errors).length > 0
|
||||
) {
|
||||
throw new Error(
|
||||
`文件 ${file.name} 的远程文件 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (mergeSources === 'localFirst') {
|
||||
raw.unshift(content);
|
||||
} else if (mergeSources === 'remoteFirst') {
|
||||
raw.push(content);
|
||||
}
|
||||
} else if (
|
||||
file.source === 'local' &&
|
||||
!['localFirst', 'remoteFirst'].includes(file.mergeSources)
|
||||
) {
|
||||
raw = file.content;
|
||||
} else {
|
||||
const errors = {};
|
||||
raw = await Promise.all(
|
||||
file.url
|
||||
.split(/[\r\n]+/)
|
||||
.map((i) => i.trim())
|
||||
.filter((i) => i.length)
|
||||
.map(async (url) => {
|
||||
try {
|
||||
return await download(
|
||||
url,
|
||||
ua || file.ua,
|
||||
undefined,
|
||||
file.proxy || proxy,
|
||||
undefined,
|
||||
undefined,
|
||||
noCache,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
$.error(
|
||||
`文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`,
|
||||
);
|
||||
return '';
|
||||
}
|
||||
}),
|
||||
);
|
||||
let fileIgnoreFailedRemoteFile = file.ignoreFailedRemoteFile;
|
||||
if (
|
||||
ignoreFailedRemoteFile != null &&
|
||||
ignoreFailedRemoteFile !== ''
|
||||
) {
|
||||
fileIgnoreFailedRemoteFile = ignoreFailedRemoteFile;
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
if (!fileIgnoreFailedRemoteFile) {
|
||||
throw new Error(
|
||||
`文件 ${file.name} 的远程文件 ${Object.keys(
|
||||
errors,
|
||||
).join(', ')} 发生错误, 请查看日志`,
|
||||
);
|
||||
} else if (fileIgnoreFailedRemoteFile === 'enabled') {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 处理文件失败`,
|
||||
`❌ ${file.name}`,
|
||||
`远程文件 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (file.mergeSources === 'localFirst') {
|
||||
raw.unshift(file.content);
|
||||
} else if (file.mergeSources === 'remoteFirst') {
|
||||
raw.push(file.content);
|
||||
}
|
||||
fileIgnoreFailedRemoteFile = ignoreFailedRemoteFile;
|
||||
}
|
||||
if (!fileIgnoreFailedRemoteFile && Object.keys(errors).length > 0) {
|
||||
throw new Error(
|
||||
`文件 ${file.name} 的远程文件 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (mergeSources === 'localFirst') {
|
||||
raw.unshift(content);
|
||||
} else if (mergeSources === 'remoteFirst') {
|
||||
raw.push(content);
|
||||
}
|
||||
} else if (
|
||||
file.source === 'local' &&
|
||||
!['localFirst', 'remoteFirst'].includes(file.mergeSources)
|
||||
) {
|
||||
raw = file.content;
|
||||
} else {
|
||||
const errors = {};
|
||||
raw = await Promise.all(
|
||||
file.url
|
||||
.split(/[\r\n]+/)
|
||||
.map((i) => i.trim())
|
||||
.filter((i) => i.length)
|
||||
.map(async (url) => {
|
||||
try {
|
||||
return await download(
|
||||
url,
|
||||
ua || file.ua,
|
||||
undefined,
|
||||
file.proxy || proxy,
|
||||
undefined,
|
||||
undefined,
|
||||
noCache,
|
||||
);
|
||||
} catch (err) {
|
||||
errors[url] = err;
|
||||
$.error(
|
||||
`文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`,
|
||||
);
|
||||
return '';
|
||||
}
|
||||
}),
|
||||
);
|
||||
let fileIgnoreFailedRemoteFile = file.ignoreFailedRemoteFile;
|
||||
if (
|
||||
ignoreFailedRemoteFile != null &&
|
||||
ignoreFailedRemoteFile !== ''
|
||||
) {
|
||||
fileIgnoreFailedRemoteFile = ignoreFailedRemoteFile;
|
||||
}
|
||||
if (!fileIgnoreFailedRemoteFile && Object.keys(errors).length > 0) {
|
||||
throw new Error(
|
||||
`文件 ${file.name} 的远程文件 ${Object.keys(errors).join(
|
||||
', ',
|
||||
)} 发生错误, 请查看日志`,
|
||||
);
|
||||
}
|
||||
if (file.mergeSources === 'localFirst') {
|
||||
raw.unshift(file.content);
|
||||
} else if (file.mergeSources === 'remoteFirst') {
|
||||
raw.push(file.content);
|
||||
}
|
||||
}
|
||||
if (produceType === 'raw') {
|
||||
return JSON.stringify((Array.isArray(raw) ? raw : [raw]).flat());
|
||||
}
|
||||
const files = (Array.isArray(raw) ? raw : [raw]).flat();
|
||||
let filesContent = files
|
||||
@ -586,17 +509,12 @@ async function produceArtifact({
|
||||
const processed =
|
||||
Array.isArray(file.process) && file.process.length > 0
|
||||
? await ProxyUtils.process(
|
||||
{
|
||||
$files: files,
|
||||
$content: filesContent,
|
||||
$options,
|
||||
$file: file,
|
||||
},
|
||||
{ $files: files, $content: filesContent, $options },
|
||||
file.process,
|
||||
)
|
||||
: { $content: filesContent, $files: files, $options };
|
||||
|
||||
return (all ? processed : processed?.$content) ?? '';
|
||||
return processed?.$content ?? '';
|
||||
}
|
||||
}
|
||||
|
||||
@ -606,15 +524,12 @@ async function syncArtifacts() {
|
||||
const files = {};
|
||||
|
||||
try {
|
||||
const valid = [];
|
||||
const invalid = [];
|
||||
const allSubs = $.read(SUBS_KEY);
|
||||
const allCols = $.read(COLLECTIONS_KEY);
|
||||
const subNames = [];
|
||||
let enabledCount = 0;
|
||||
allArtifacts.map((artifact) => {
|
||||
if (artifact.sync && artifact.source) {
|
||||
enabledCount++;
|
||||
if (artifact.type === 'subscription') {
|
||||
const subName = artifact.source;
|
||||
const sub = findByName(allSubs, subName);
|
||||
@ -635,13 +550,6 @@ async function syncArtifacts() {
|
||||
}
|
||||
});
|
||||
|
||||
if (enabledCount === 0) {
|
||||
$.info(
|
||||
`需同步的配置: ${enabledCount}, 总数: ${allArtifacts.length}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (subNames.length > 0) {
|
||||
await Promise.all(
|
||||
subNames.map(async (subName) => {
|
||||
@ -690,47 +598,27 @@ async function syncArtifacts() {
|
||||
files[encodeURIComponent(artifact.name)] = {
|
||||
content: output,
|
||||
};
|
||||
|
||||
valid.push(artifact.name);
|
||||
}
|
||||
} catch (e) {
|
||||
$.error(
|
||||
`生成同步配置 ${artifact.name} 发生错误: ${
|
||||
e.message ?? e
|
||||
}`,
|
||||
`同步配置 ${artifact.name} 发生错误: ${e.message ?? e}`,
|
||||
);
|
||||
invalid.push(artifact.name);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
$.info(`${valid.length} 个同步配置生成成功: ${valid.join(', ')}`);
|
||||
$.info(`${invalid.length} 个同步配置生成失败: ${invalid.join(', ')}`);
|
||||
|
||||
if (valid.length === 0) {
|
||||
if (invalid.length > 0) {
|
||||
throw new Error(
|
||||
`同步配置 ${invalid.join(', ')} 生成失败 详情请查看日志`,
|
||||
`同步配置 ${invalid.join(', ')} 发生错误 详情请查看日志`,
|
||||
);
|
||||
}
|
||||
|
||||
const resp = await syncToGist(files);
|
||||
const body = JSON.parse(resp.body);
|
||||
|
||||
delete body.history;
|
||||
delete body.forks;
|
||||
delete body.owner;
|
||||
Object.values(body.files).forEach((file) => {
|
||||
delete file.content;
|
||||
});
|
||||
$.info('上传配置响应:');
|
||||
$.info(JSON.stringify(body, null, 2));
|
||||
|
||||
for (const artifact of allArtifacts) {
|
||||
if (
|
||||
artifact.sync &&
|
||||
artifact.source &&
|
||||
valid.includes(artifact.name)
|
||||
) {
|
||||
if (artifact.sync) {
|
||||
artifact.updated = new Date().getTime();
|
||||
// extract real url from gist
|
||||
let files = body.files;
|
||||
@ -758,17 +646,9 @@ async function syncArtifacts() {
|
||||
}
|
||||
|
||||
$.write(allArtifacts, ARTIFACTS_KEY);
|
||||
$.info('上传配置成功');
|
||||
|
||||
if (invalid.length > 0) {
|
||||
throw new Error(
|
||||
`同步配置成功 ${valid.length} 个, 失败 ${invalid.length} 个, 详情请查看日志`,
|
||||
);
|
||||
} else {
|
||||
$.info(`同步配置成功 ${valid.length} 个`);
|
||||
}
|
||||
$.info('全部订阅同步成功!');
|
||||
} catch (e) {
|
||||
$.error(`同步配置失败,原因:${e.message ?? e}`);
|
||||
$.error(`同步订阅失败,原因:${e.message ?? e}`);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@ -778,7 +658,7 @@ async function syncAllArtifacts(_, res) {
|
||||
await syncArtifacts();
|
||||
success(res);
|
||||
} catch (e) {
|
||||
$.error(`同步配置失败,原因:${e.message ?? e}`);
|
||||
$.error(`同步订阅失败,原因:${e.message ?? e}`);
|
||||
failed(
|
||||
res,
|
||||
new InternalServerError(
|
||||
@ -855,16 +735,6 @@ async function syncArtifact(req, res) {
|
||||
});
|
||||
artifact.updated = new Date().getTime();
|
||||
const body = JSON.parse(resp.body);
|
||||
|
||||
delete body.history;
|
||||
delete body.forks;
|
||||
delete body.owner;
|
||||
Object.values(body.files).forEach((file) => {
|
||||
delete file.content;
|
||||
});
|
||||
$.info('上传配置响应:');
|
||||
$.info(JSON.stringify(body, null, 2));
|
||||
|
||||
let files = body.files;
|
||||
let isGitLab;
|
||||
if (Array.isArray(files)) {
|
||||
|
@ -1,7 +1,6 @@
|
||||
import $ from '@/core/app';
|
||||
import dnsPacket from 'dns-packet';
|
||||
import { Buffer } from 'buffer';
|
||||
import { isIPv4 } from '@/utils';
|
||||
|
||||
export async function doh({ url, domain, type = 'A', timeout, edns }) {
|
||||
const buf = dnsPacket.encode({
|
||||
@ -24,7 +23,7 @@ export async function doh({ url, domain, type = 'A', timeout, edns }) {
|
||||
{
|
||||
code: 'CLIENT_SUBNET',
|
||||
ip: edns,
|
||||
sourcePrefixLength: isIPv4(edns) ? 24 : 56,
|
||||
sourcePrefixLength: 24,
|
||||
scopePrefixLength: 0,
|
||||
},
|
||||
],
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { SETTINGS_KEY, FILES_KEY, MODULES_KEY } from '@/constants';
|
||||
import { SETTINGS_KEY } from '@/constants';
|
||||
import { HTTP, ENV } from '@/vendor/open-api';
|
||||
import { hex_md5 } from '@/vendor/md5';
|
||||
import { getPolicyDescriptor } from '@/utils';
|
||||
@ -11,12 +11,6 @@ import {
|
||||
validCheck,
|
||||
} from '@/utils/flow';
|
||||
import $ from '@/core/app';
|
||||
import { findByName } from '@/utils/database';
|
||||
import { produceArtifact } from '@/restful/sync';
|
||||
import PROXY_PREPROCESSORS from '@/core/proxy-utils/preprocessors';
|
||||
const clashPreprocessor = PROXY_PREPROCESSORS.find(
|
||||
(processor) => processor.name === 'Clash Pre-processor',
|
||||
);
|
||||
|
||||
const tasks = new Map();
|
||||
|
||||
@ -28,7 +22,6 @@ export default async function download(
|
||||
skipCustomCache,
|
||||
awaitCustomCache,
|
||||
noCache,
|
||||
preprocess,
|
||||
) {
|
||||
let $arguments = {};
|
||||
let url = rawUrl.replace(/#noFlow$/, '');
|
||||
@ -94,9 +87,6 @@ export default async function download(
|
||||
timeout,
|
||||
proxy,
|
||||
true,
|
||||
undefined,
|
||||
undefined,
|
||||
preprocess,
|
||||
);
|
||||
} catch (e) {
|
||||
$.error(
|
||||
@ -117,9 +107,6 @@ export default async function download(
|
||||
timeout,
|
||||
proxy,
|
||||
true,
|
||||
undefined,
|
||||
undefined,
|
||||
preprocess,
|
||||
).catch((e) => {
|
||||
$.error(
|
||||
`乐观缓存: URL ${url} 异步更新缓存发生错误 ${
|
||||
@ -132,53 +119,22 @@ export default async function download(
|
||||
}
|
||||
}
|
||||
|
||||
const downloadUrlMatch = url
|
||||
.split('#')[0]
|
||||
.match(/^\/api\/(file|module)\/(.+)/);
|
||||
if (downloadUrlMatch) {
|
||||
let type = '';
|
||||
try {
|
||||
type = downloadUrlMatch?.[1];
|
||||
let name = downloadUrlMatch?.[2];
|
||||
if (name == null) {
|
||||
throw new Error(`本地 ${type} URL 无效: ${url}`);
|
||||
}
|
||||
name = decodeURIComponent(name);
|
||||
const key = type === 'module' ? MODULES_KEY : FILES_KEY;
|
||||
const item = findByName($.read(key), name);
|
||||
if (!item) {
|
||||
throw new Error(`找不到 ${type}: ${name}`);
|
||||
}
|
||||
// const downloadUrlMatch = url.match(/^\/api\/(file|module)\/(.+)/);
|
||||
// if (downloadUrlMatch) {
|
||||
// let type = downloadUrlMatch?.[1];
|
||||
// let name = downloadUrlMatch?.[2];
|
||||
// if (name == null) {
|
||||
// throw new Error(`本地 ${type} URL 无效: ${url}`);
|
||||
// }
|
||||
// name = decodeURIComponent(name);
|
||||
// const key = type === 'module' ? MODULES_KEY : FILES_KEY;
|
||||
// const item = findByName($.read(key), name);
|
||||
// if (!item) {
|
||||
// throw new Error(`找不到本地 ${type}: ${name}`);
|
||||
// }
|
||||
|
||||
if (type === 'module') {
|
||||
return item.content;
|
||||
} else {
|
||||
return await produceArtifact({
|
||||
type: 'file',
|
||||
name,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when loading ${type}: ${
|
||||
url.split('#')[0]
|
||||
}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法加载 ${type}: ${url}`);
|
||||
}
|
||||
} else if (url?.startsWith('/')) {
|
||||
try {
|
||||
const fs = eval(`require("fs")`);
|
||||
return fs.readFileSync(url.split('#')[0], 'utf8');
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when reading local file: ${
|
||||
url.split('#')[0]
|
||||
}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法从该路径读取文本内容: ${url}`);
|
||||
}
|
||||
}
|
||||
// return item.content;
|
||||
// }
|
||||
|
||||
if (!isNode && tasks.has(id)) {
|
||||
return tasks.get(id);
|
||||
@ -213,10 +169,10 @@ export default async function download(
|
||||
: { insecure: true }
|
||||
: undefined;
|
||||
$.info(
|
||||
`Downloading...\nUser-Agent: ${userAgent}\nTimeout: ${requestTimeout}\nProxy: ${proxy}\nInsecure: ${!!insecure}\nPreprocess: ${preprocess}\nURL: ${url}`,
|
||||
`Downloading...\nUser-Agent: ${userAgent}\nTimeout: ${requestTimeout}\nProxy: ${proxy}\nInsecure: ${!!insecure}\nURL: ${url}`,
|
||||
);
|
||||
try {
|
||||
let { body, headers, statusCode } = await http.get({
|
||||
const { body, headers, statusCode } = await http.get({
|
||||
url,
|
||||
...(proxy ? { proxy } : {}),
|
||||
...(isLoon && proxy ? { node: proxy } : {}),
|
||||
@ -237,15 +193,6 @@ export default async function download(
|
||||
}
|
||||
if (body.replace(/\s/g, '').length === 0)
|
||||
throw new Error(new Error('远程资源内容为空'));
|
||||
if (preprocess) {
|
||||
try {
|
||||
if (clashPreprocessor.test(body)) {
|
||||
body = clashPreprocessor.parse(body, true);
|
||||
}
|
||||
} catch (e) {
|
||||
$.error(`Clash Pre-processor error: ${e}`);
|
||||
}
|
||||
}
|
||||
let shouldCache = true;
|
||||
if (cacheThreshold) {
|
||||
const size = body.length / 1024;
|
||||
@ -306,25 +253,3 @@ export default async function download(
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function downloadFile(url, file) {
|
||||
const undici = eval("require('undici')");
|
||||
const fs = eval("require('fs')");
|
||||
const { pipeline } = eval("require('stream/promises')");
|
||||
const { Agent, interceptors, request } = undici;
|
||||
$.info(`Downloading file...\nURL: ${url}\nFile: ${file}`);
|
||||
const { body, statusCode } = await request(url, {
|
||||
dispatcher: new Agent().compose(
|
||||
interceptors.redirect({
|
||||
maxRedirections: 3,
|
||||
throwOnRedirect: true,
|
||||
}),
|
||||
),
|
||||
});
|
||||
if (statusCode !== 200)
|
||||
throw new Error(`Failed to download file from ${url}`);
|
||||
const fileStream = fs.createWriteStream(file);
|
||||
await pipeline(body, fileStream);
|
||||
$.info(`File downloaded from ${url} to ${file}`);
|
||||
return file;
|
||||
}
|
||||
|
@ -49,7 +49,7 @@ export async function getFlowHeaders(
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($arguments?.noFlow || !/^https?/.test(url)) {
|
||||
if ($arguments?.noFlow) {
|
||||
return;
|
||||
}
|
||||
const { isStash, isLoon, isShadowRocket, isQX } = ENV();
|
||||
@ -167,9 +167,6 @@ export async function getFlowHeaders(
|
||||
flowInfo = getFlowField(headers);
|
||||
}
|
||||
}
|
||||
if (flowInfo) {
|
||||
flowInfo = flowInfo.trim();
|
||||
}
|
||||
if (flowInfo) {
|
||||
headersResourceCache.set(id, flowInfo);
|
||||
}
|
||||
@ -313,41 +310,3 @@ export function getRmainingDays(opt = {}) {
|
||||
$.error(`getRmainingDays failed: ${e.message ?? e}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeFlowHeader(flowHeaders) {
|
||||
try {
|
||||
// 使用 Map 保持顺序并处理重复键
|
||||
const kvMap = new Map();
|
||||
|
||||
flowHeaders
|
||||
.split(';')
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean)
|
||||
.forEach((pair) => {
|
||||
const eqIndex = pair.indexOf('=');
|
||||
if (eqIndex === -1) return;
|
||||
|
||||
const key = pair.slice(0, eqIndex).trim();
|
||||
const encodedValue = pair.slice(eqIndex + 1).trim();
|
||||
|
||||
// 只保留第一个出现的 key
|
||||
if (!kvMap.has(key)) {
|
||||
try {
|
||||
// 解码 URI 组件并保留原始值作为 fallback
|
||||
const decodedValue = decodeURIComponent(encodedValue);
|
||||
kvMap.set(key, decodedValue);
|
||||
} catch (e) {
|
||||
kvMap.set(key, encodedValue);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 拼接标准化字符串
|
||||
return Array.from(kvMap.entries())
|
||||
.map(([k, v]) => `${k}=${encodeURIComponent(v)}`) // 重新编码保持兼容性
|
||||
.join('; ');
|
||||
} catch (e) {
|
||||
$.error(`normalizeFlowHeader failed: ${e.message ?? e}`);
|
||||
return flowHeaders;
|
||||
}
|
||||
}
|
||||
|
@ -17,10 +17,7 @@ const ISOFlags = {
|
||||
'🇧🇪': ['BE', 'BEL'],
|
||||
'🇧🇬': ['BG', 'BGR'],
|
||||
'🇧🇭': ['BH', 'BHR'],
|
||||
'🇧🇴': ['BO', 'BOL'],
|
||||
'🇧🇳': ['BN', 'BRN'],
|
||||
'🇧🇷': ['BR', 'BRA'],
|
||||
'🇧🇹': ['BT', 'BTN'],
|
||||
'🇧🇾': ['BY', 'BLR'],
|
||||
'🇨🇦': ['CA', 'CAN'],
|
||||
'🇨🇭': ['CH', 'CHE'],
|
||||
@ -41,8 +38,6 @@ const ISOFlags = {
|
||||
'🇬🇧': ['GB', 'GBR', 'UK'],
|
||||
'🇬🇪': ['GE', 'GEO'],
|
||||
'🇬🇷': ['GR', 'GRC'],
|
||||
'🇬🇹': ['GT', 'GTM'],
|
||||
'🇬🇺': ['GU', 'GUM'],
|
||||
'🇭🇰': ['HK', 'HKG', 'HKT', 'HKBN', 'HGC', 'WTT', 'CMI'],
|
||||
'🇭🇷': ['HR', 'HRV'],
|
||||
'🇭🇺': ['HU', 'HUN'],
|
||||
@ -62,15 +57,12 @@ const ISOFlags = {
|
||||
'🇮🇷': ['IR', 'IRN'],
|
||||
'🇮🇸': ['IS', 'ISL'],
|
||||
'🇮🇹': ['IT', 'ITA'],
|
||||
'🇱🇦': ['LA', 'LAO'],
|
||||
'🇱🇰': ['LK', 'LKA'],
|
||||
'🇱🇹': ['LT', 'LTU'],
|
||||
'🇱🇺': ['LU', 'LUX'],
|
||||
'🇱🇻': ['LV', 'LVA'],
|
||||
'🇲🇦': ['MA', 'MAR'],
|
||||
'🇲🇩': ['MD', 'MDA'],
|
||||
'🇳🇬': ['NG', 'NGA'],
|
||||
'🇲🇲': ['MM', 'MMR'],
|
||||
'🇲🇰': ['MK', 'MKD'],
|
||||
'🇲🇳': ['MN', 'MNG'],
|
||||
'🇲🇴': ['MO', 'MAC', 'CTM'],
|
||||
@ -89,7 +81,6 @@ const ISOFlags = {
|
||||
'🇵🇷': ['PR', 'PRI'],
|
||||
'🇵🇹': ['PT', 'PRT'],
|
||||
'🇵🇾': ['PY', 'PRY'],
|
||||
'🇵🇬': ['PG', 'PNG'],
|
||||
'🇷🇴': ['RO', 'ROU'],
|
||||
'🇷🇸': ['RS', 'SRB'],
|
||||
'🇷🇪': ['RE', 'REU'],
|
||||
@ -149,10 +140,7 @@ export function getFlag(name) {
|
||||
'🇧🇬': ['Bulgaria', '保加利亚', '保加利亞'],
|
||||
'🇧🇭': ['Bahrain', '巴林'],
|
||||
'🇧🇷': ['Brazil', '巴西', '圣保罗'],
|
||||
'🇧🇳': ['Brunei', '文莱', '汶萊'],
|
||||
'🇧🇾': ['Belarus', '白俄罗斯', '白俄'],
|
||||
'🇧🇴': ['Bolivia', '玻利维亚'],
|
||||
'🇧🇹': ['Bhutan', '不丹', '不丹王国'],
|
||||
'🇨🇦': [
|
||||
'Canada',
|
||||
'加拿大',
|
||||
@ -203,8 +191,6 @@ export function getFlag(name) {
|
||||
],
|
||||
'🇬🇪': ['Georgia', '格鲁吉亚', '格魯吉亞'],
|
||||
'🇬🇷': ['Greece', '希腊', '希臘'],
|
||||
'🇬🇺': ['Guam', '关岛', '關島'],
|
||||
'🇬🇹': ['Guatemala', '危地马拉'],
|
||||
'🇭🇰': [
|
||||
'Hongkong',
|
||||
'香港',
|
||||
@ -264,14 +250,11 @@ export function getFlag(name) {
|
||||
'🇮🇷': ['Iran', '伊朗'],
|
||||
'🇮🇸': ['Iceland', '冰岛', '冰島'],
|
||||
'🇮🇹': ['Italy', '意大利', '義大利', '米兰', 'Nachash'],
|
||||
'🇱🇰': ['Sri Lanka', '斯里兰卡', '斯里蘭卡'],
|
||||
'🇱🇦': ['Laos', '老挝', '老撾'],
|
||||
'🇱🇹': ['Lithuania', '立陶宛'],
|
||||
'🇱🇺': ['Luxembourg', '卢森堡'],
|
||||
'🇱🇻': ['Latvia', '拉脱维亚', 'Latvija'],
|
||||
'🇲🇦': ['Morocco', '摩洛哥'],
|
||||
'🇲🇩': ['Moldova', '摩尔多瓦', '摩爾多瓦'],
|
||||
'🇲🇲': ['Myanmar', '缅甸', '緬甸'],
|
||||
'🇳🇬': ['Nigeria', '尼日利亚', '尼日利亞'],
|
||||
'🇲🇰': ['Macedonia', '马其顿', '馬其頓'],
|
||||
'🇲🇳': ['Mongolia', '蒙古'],
|
||||
@ -297,7 +280,6 @@ export function getFlag(name) {
|
||||
'🇵🇱': ['Poland', '波兰', '波蘭', '华沙', 'Warsaw'],
|
||||
'🇵🇷': ['Puerto Rico', '波多黎各'],
|
||||
'🇵🇹': ['Portugal', '葡萄牙'],
|
||||
'🇵🇬': ['Papua New Guinea', '巴布亚新几内亚'],
|
||||
'🇵🇾': ['Paraguay', '巴拉圭'],
|
||||
'🇷🇴': ['Romania', '罗马尼亚'],
|
||||
'🇷🇸': ['Serbia', '塞尔维亚'],
|
||||
|
@ -114,18 +114,15 @@ export default class Gist {
|
||||
return;
|
||||
});
|
||||
} else {
|
||||
return this.http
|
||||
.get('/gists?per_page=100&page=1')
|
||||
.then((response) => {
|
||||
const gists = JSON.parse(response.body);
|
||||
$.info(`获取到当前 GitHub 用户的 gist: ${gists.length} 个`);
|
||||
for (let g of gists) {
|
||||
if (g.description === this.key) {
|
||||
return g;
|
||||
}
|
||||
return this.http.get('/gists').then((response) => {
|
||||
const gists = JSON.parse(response.body);
|
||||
for (let g of gists) {
|
||||
if (g.description === this.key) {
|
||||
return g;
|
||||
}
|
||||
return;
|
||||
});
|
||||
}
|
||||
return;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -280,7 +277,7 @@ export default class Gist {
|
||||
return Promise.reject(err);
|
||||
}
|
||||
} else {
|
||||
return Promise.reject(`找不到 Sub-Store Gist (${this.key})`);
|
||||
return Promise.reject('找不到 Sub-Store Gist');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -117,42 +117,7 @@ function numberToString(value) {
|
||||
: BigInt(value).toString();
|
||||
}
|
||||
|
||||
function isValidUUID(uuid) {
|
||||
return (
|
||||
typeof uuid === 'string' &&
|
||||
/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(
|
||||
uuid,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function formatDateTime(date, format = 'YYYY-MM-DD_HH-mm-ss') {
|
||||
const d = date instanceof Date ? date : new Date(date);
|
||||
|
||||
if (isNaN(d.getTime())) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const pad = (num) => String(num).padStart(2, '0');
|
||||
|
||||
const replacements = {
|
||||
YYYY: d.getFullYear(),
|
||||
MM: pad(d.getMonth() + 1),
|
||||
DD: pad(d.getDate()),
|
||||
HH: pad(d.getHours()),
|
||||
mm: pad(d.getMinutes()),
|
||||
ss: pad(d.getSeconds()),
|
||||
};
|
||||
|
||||
return format.replace(
|
||||
/YYYY|MM|DD|HH|mm|ss/g,
|
||||
(match) => replacements[match],
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
formatDateTime,
|
||||
isValidUUID,
|
||||
ipAddress,
|
||||
isIPv4,
|
||||
isIPv6,
|
||||
|
@ -4,8 +4,6 @@ import {
|
||||
SCHEMA_VERSION_KEY,
|
||||
ARTIFACTS_KEY,
|
||||
RULES_KEY,
|
||||
FILES_KEY,
|
||||
TOKENS_KEY,
|
||||
} from '@/constants';
|
||||
import $ from '@/core/app';
|
||||
|
||||
@ -57,17 +55,7 @@ function doMigrationV2() {
|
||||
const newRules = Object.values(rules);
|
||||
$.write(newRules, RULES_KEY);
|
||||
|
||||
// 5. migrate files
|
||||
const files = $.read(FILES_KEY) || {};
|
||||
const newFiles = Object.values(files);
|
||||
$.write(newFiles, FILES_KEY);
|
||||
|
||||
// 6. migrate tokens
|
||||
const tokens = $.read(TOKENS_KEY) || {};
|
||||
const newTokens = Object.values(tokens);
|
||||
$.write(newTokens, TOKENS_KEY);
|
||||
|
||||
// 7. delete builtin rules
|
||||
// 5. delete builtin rules
|
||||
delete $.cache.builtin;
|
||||
$.info('Migration complete!');
|
||||
|
||||
|
@ -24,7 +24,7 @@ class ResourceCache {
|
||||
this._cleanup();
|
||||
}
|
||||
|
||||
_cleanup(prefix, expires) {
|
||||
_cleanup() {
|
||||
// clear obsolete cached resource
|
||||
let clear = false;
|
||||
Object.entries(this.resourceCache).forEach((entry) => {
|
||||
@ -35,11 +35,7 @@ class ResourceCache {
|
||||
$.delete(`#${id}`);
|
||||
clear = true;
|
||||
}
|
||||
if (
|
||||
new Date().getTime() - updated.time >
|
||||
(expires ?? this.expires) ||
|
||||
(prefix && id.startsWith(prefix))
|
||||
) {
|
||||
if (new Date().getTime() - updated.time > this.expires) {
|
||||
delete this.resourceCache[id];
|
||||
clear = true;
|
||||
}
|
||||
@ -56,15 +52,10 @@ class ResourceCache {
|
||||
$.write(JSON.stringify(this.resourceCache), SCRIPT_RESOURCE_CACHE_KEY);
|
||||
}
|
||||
|
||||
get(id, expires, remove) {
|
||||
get(id) {
|
||||
const updated = this.resourceCache[id] && this.resourceCache[id].time;
|
||||
if (updated) {
|
||||
if (new Date().getTime() - updated <= (expires ?? this.expires))
|
||||
return this.resourceCache[id].data;
|
||||
if (remove) {
|
||||
delete this.resourceCache[id];
|
||||
this._persist();
|
||||
}
|
||||
if (updated && new Date().getTime() - updated <= this.expires) {
|
||||
return this.resourceCache[id].data;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
@ -1,7 +1,3 @@
|
||||
import gte from 'semver/functions/gte';
|
||||
import coerce from 'semver/functions/coerce';
|
||||
import $ from '@/core/app';
|
||||
|
||||
export function getUserAgentFromHeaders(headers) {
|
||||
const keys = Object.keys(headers);
|
||||
let UA = '';
|
||||
@ -47,7 +43,7 @@ export function getPlatformFromUserAgent({ ua, UA, accept }) {
|
||||
return 'Clash';
|
||||
} else if (ua.indexOf('v2ray') !== -1) {
|
||||
return 'V2Ray';
|
||||
} else if (ua.indexOf('sing-box') !== -1 || ua.indexOf('singbox') !== -1) {
|
||||
} else if (ua.indexOf('sing-box') !== -1) {
|
||||
return 'sing-box';
|
||||
} else if (accept.indexOf('application/json') === 0) {
|
||||
return 'JSON';
|
||||
@ -60,42 +56,3 @@ export function getPlatformFromHeaders(headers) {
|
||||
const { UA, ua, accept } = getUserAgentFromHeaders(headers);
|
||||
return getPlatformFromUserAgent({ ua, UA, accept });
|
||||
}
|
||||
export function shouldIncludeUnsupportedProxy(platform, ua) {
|
||||
// try {
|
||||
// const target = getPlatformFromUserAgent({
|
||||
// UA: ua,
|
||||
// ua: ua.toLowerCase(),
|
||||
// });
|
||||
// if (!['Stash', 'Egern', 'Loon'].includes(target)) {
|
||||
// return false;
|
||||
// }
|
||||
// const coerceVersion = coerce(ua);
|
||||
// $.log(JSON.stringify(coerceVersion, null, 2));
|
||||
// const { version } = coerceVersion;
|
||||
// if (
|
||||
// platform === 'Stash' &&
|
||||
// target === 'Stash' &&
|
||||
// gte(version, '3.1.0')
|
||||
// ) {
|
||||
// return true;
|
||||
// }
|
||||
// if (
|
||||
// platform === 'Egern' &&
|
||||
// target === 'Egern' &&
|
||||
// gte(version, '1.29.0')
|
||||
// ) {
|
||||
// return true;
|
||||
// }
|
||||
// // Loon 的 UA 不规范, version 取出来是 build
|
||||
// if (
|
||||
// platform === 'Loon' &&
|
||||
// target === 'Loon' &&
|
||||
// gte(version, '842.0.0')
|
||||
// ) {
|
||||
// return true;
|
||||
// }
|
||||
// } catch (e) {
|
||||
// $.error(`获取版本号失败: ${e}`);
|
||||
// }
|
||||
return false;
|
||||
}
|
||||
|
@ -34,6 +34,4 @@ export default {
|
||||
load,
|
||||
safeDump,
|
||||
dump,
|
||||
parse: safeLoad,
|
||||
stringify: safeDump,
|
||||
};
|
||||
|
11
backend/src/vendor/express.js
vendored
11
backend/src/vendor/express.js
vendored
@ -17,14 +17,7 @@ export default function express({ substore: $, port, host }) {
|
||||
const express_ = eval(`require("express")`);
|
||||
const bodyParser = eval(`require("body-parser")`);
|
||||
const app = express_();
|
||||
const limit = eval('process.env.SUB_STORE_BODY_JSON_LIMIT') || '1mb';
|
||||
$.info(`[BACKEND] body JSON limit: ${limit}`);
|
||||
app.use(
|
||||
bodyParser.json({
|
||||
verify: rawBodySaver,
|
||||
limit,
|
||||
}),
|
||||
);
|
||||
app.use(bodyParser.json({ verify: rawBodySaver, limit: '1mb' }));
|
||||
app.use(
|
||||
bodyParser.urlencoded({ verify: rawBodySaver, extended: true }),
|
||||
);
|
||||
@ -38,7 +31,7 @@ export default function express({ substore: $, port, host }) {
|
||||
app.start = () => {
|
||||
const listener = app.listen(port, host, () => {
|
||||
const { address, port } = listener.address();
|
||||
$.info(`[BACKEND] listening on ${address}:${port}`);
|
||||
$.info(`[BACKEND] ${address}:${port}`);
|
||||
});
|
||||
};
|
||||
return app;
|
||||
|
187
backend/src/vendor/open-api.js
vendored
187
backend/src/vendor/open-api.js
vendored
@ -10,14 +10,6 @@ const isEgern = 'object' == typeof egern;
|
||||
const isLanceX = 'undefined' != typeof $native;
|
||||
const isGUIforCores = typeof $Plugins !== 'undefined';
|
||||
|
||||
function isPlainObject(obj) {
|
||||
return (
|
||||
obj !== null &&
|
||||
typeof obj === 'object' &&
|
||||
[null, Object.prototype].includes(Object.getPrototypeOf(obj))
|
||||
);
|
||||
}
|
||||
|
||||
export class OpenAPI {
|
||||
constructor(name = 'untitled', debug = false) {
|
||||
this.name = name;
|
||||
@ -26,10 +18,6 @@ export class OpenAPI {
|
||||
this.http = HTTP();
|
||||
this.env = ENV();
|
||||
|
||||
if (isNode) {
|
||||
const dotenv = eval(`require("dotenv")`);
|
||||
dotenv.config();
|
||||
}
|
||||
this.node = (() => {
|
||||
if (isNode) {
|
||||
const fs = eval("require('fs')");
|
||||
@ -70,50 +58,29 @@ export class OpenAPI {
|
||||
const basePath =
|
||||
eval('process.env.SUB_STORE_DATA_BASE_PATH') || '.';
|
||||
let rootPath = `${basePath}/root.json`;
|
||||
const backupRootPath = `${basePath}/root_${Date.now()}.json`;
|
||||
|
||||
this.log(`Root path: ${rootPath}`);
|
||||
if (this.node.fs.existsSync(rootPath)) {
|
||||
try {
|
||||
this.root = JSON.parse(
|
||||
this.node.fs.readFileSync(`${rootPath}`),
|
||||
);
|
||||
} catch (e) {
|
||||
this.node.fs.copyFileSync(rootPath, backupRootPath);
|
||||
this.error(
|
||||
`Failed to parse ${rootPath}: ${e.message}. Backup created at ${backupRootPath}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!isPlainObject(this.root)) {
|
||||
if (!this.node.fs.existsSync(rootPath)) {
|
||||
this.node.fs.writeFileSync(rootPath, JSON.stringify({}), {
|
||||
flag: 'w',
|
||||
flag: 'wx',
|
||||
});
|
||||
this.root = {};
|
||||
} else {
|
||||
this.root = JSON.parse(
|
||||
this.node.fs.readFileSync(`${rootPath}`),
|
||||
);
|
||||
}
|
||||
|
||||
// create a json file with the given name if not exists
|
||||
let fpath = `${basePath}/${this.name}.json`;
|
||||
const backupPath = `${basePath}/${this.name}_${Date.now()}.json`;
|
||||
|
||||
this.log(`Data path: ${fpath}`);
|
||||
if (this.node.fs.existsSync(fpath)) {
|
||||
try {
|
||||
this.cache = JSON.parse(
|
||||
this.node.fs.readFileSync(`${fpath}`),
|
||||
);
|
||||
} catch (e) {
|
||||
this.node.fs.copyFileSync(fpath, backupPath);
|
||||
this.error(
|
||||
`Failed to parse ${fpath}: ${e.message}. Backup created at ${backupPath}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!isPlainObject(this.cache)) {
|
||||
if (!this.node.fs.existsSync(fpath)) {
|
||||
this.node.fs.writeFileSync(fpath, JSON.stringify({}), {
|
||||
flag: 'w',
|
||||
flag: 'wx',
|
||||
});
|
||||
this.cache = {};
|
||||
} else {
|
||||
this.cache = JSON.parse(this.node.fs.readFileSync(`${fpath}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -370,111 +337,45 @@ export function HTTP(defaultOptions = { baseURL: '' }) {
|
||||
opts: options.opts,
|
||||
});
|
||||
} else if (isLoon || isSurge || isNode) {
|
||||
worker = new Promise(async (resolve, reject) => {
|
||||
worker = new Promise((resolve, reject) => {
|
||||
const request = isNode
|
||||
? eval("require('request')")
|
||||
: $httpClient;
|
||||
const body = options.body;
|
||||
const opts = JSON.parse(JSON.stringify(options));
|
||||
opts.body = body;
|
||||
opts.timeout = opts.timeout || 8000;
|
||||
if (opts.timeout) {
|
||||
opts.timeout++;
|
||||
if (isNaN(opts.timeout)) {
|
||||
opts.timeout = 8000;
|
||||
}
|
||||
if (!isNode) {
|
||||
let unit = 'ms';
|
||||
// 这些客户端单位为 s
|
||||
if (isSurge || isStash || isShadowRocket) {
|
||||
opts.timeout = Math.ceil(opts.timeout / 1000);
|
||||
unit = 's';
|
||||
}
|
||||
// Loon 为 ms
|
||||
// console.log(`[httpClient timeout] ${opts.timeout}${unit}`);
|
||||
}
|
||||
}
|
||||
if (isNode) {
|
||||
const undici = eval("require('undici')");
|
||||
const {
|
||||
ProxyAgent,
|
||||
EnvHttpProxyAgent,
|
||||
request,
|
||||
interceptors,
|
||||
} = undici;
|
||||
const agentOpts = {
|
||||
connect: {
|
||||
rejectUnauthorized:
|
||||
opts.strictSSL === false ||
|
||||
opts.insecure === true
|
||||
? false
|
||||
: true,
|
||||
},
|
||||
bodyTimeout: opts.timeout,
|
||||
headersTimeout: opts.timeout,
|
||||
};
|
||||
try {
|
||||
const url = new URL(opts.url);
|
||||
if (url.username || url.password) {
|
||||
opts.headers = {
|
||||
...(opts.headers || {}),
|
||||
Authorization: `Basic ${Buffer.from(
|
||||
`${url.username || ''}:${
|
||||
url.password || ''
|
||||
}`,
|
||||
).toString('base64')}`,
|
||||
};
|
||||
}
|
||||
const response = await request(opts.url, {
|
||||
...opts,
|
||||
method: method.toUpperCase(),
|
||||
dispatcher: (opts.proxy
|
||||
? new ProxyAgent({
|
||||
...agentOpts,
|
||||
uri: opts.proxy,
|
||||
})
|
||||
: new EnvHttpProxyAgent(agentOpts)
|
||||
).compose(
|
||||
interceptors.redirect({
|
||||
maxRedirections: 3,
|
||||
throwOnMaxRedirects: true,
|
||||
}),
|
||||
),
|
||||
});
|
||||
resolve({
|
||||
statusCode: response.statusCode,
|
||||
headers: response.headers,
|
||||
body:
|
||||
opts.encoding === null
|
||||
? await response.body.arrayBuffer()
|
||||
: await response.body.text(),
|
||||
});
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
} else {
|
||||
$httpClient[method.toLowerCase()](
|
||||
opts,
|
||||
(err, response, body) => {
|
||||
// if (err) {
|
||||
// console.log(err);
|
||||
// } else {
|
||||
// console.log({
|
||||
// statusCode:
|
||||
// response.status || response.statusCode,
|
||||
// headers: response.headers,
|
||||
// body,
|
||||
// });
|
||||
// }
|
||||
|
||||
if (err) reject(err);
|
||||
else
|
||||
resolve({
|
||||
statusCode:
|
||||
response.status || response.statusCode,
|
||||
headers: response.headers,
|
||||
body,
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!isNode && opts.timeout) {
|
||||
opts.timeout++;
|
||||
let unit = 'ms';
|
||||
// 这些客户端单位为 s
|
||||
if (isSurge || isStash || isShadowRocket) {
|
||||
opts.timeout = Math.ceil(opts.timeout / 1000);
|
||||
unit = 's';
|
||||
}
|
||||
// Loon 为 ms
|
||||
// console.log(`[httpClient timeout] ${opts.timeout}${unit}`);
|
||||
}
|
||||
request[method.toLowerCase()](opts, (err, response, body) => {
|
||||
// if (err) {
|
||||
// console.log(err);
|
||||
// } else {
|
||||
// console.log({
|
||||
// statusCode:
|
||||
// response.status || response.statusCode,
|
||||
// headers: response.headers,
|
||||
// body,
|
||||
// });
|
||||
// }
|
||||
|
||||
if (err) reject(err);
|
||||
else
|
||||
resolve({
|
||||
statusCode: response.status || response.statusCode,
|
||||
headers: response.headers,
|
||||
body,
|
||||
});
|
||||
});
|
||||
});
|
||||
} else if (isGUIforCores) {
|
||||
worker = new Promise(async (resolve, reject) => {
|
||||
|
@ -13,13 +13,7 @@ function operator(proxies = [], targetPlatform, context) {
|
||||
// 5. `_subName` 为单条订阅名, `_subDisplayName` 为单条订阅显示名
|
||||
// 6. `_collectionName` 为组合订阅名, `_collectionDisplayName` 为组合订阅显示名
|
||||
// 7. `tls-fingerprint` 为 tls 指纹
|
||||
// 8. `underlying-proxy` 为前置代理, 不同平台会自动转换
|
||||
// 例如 $server['underlying-proxy'] = '名称'
|
||||
// 只给 mihomo 输出的话, `dialer-proxy` 也行
|
||||
// 只给 sing-box 输出的话, `detour` 也行
|
||||
// 只给 Egern 输出的话, `prev_hop` 也行
|
||||
// 只给 Shadowrocket 输出的话, `chain` 也行
|
||||
// 输出到 Clash/Stash 时, 会过滤掉配置了前置代理的节点, 并提示使用对应的功能.
|
||||
// 8. `underlying-proxy` 为前置代理
|
||||
// 9. `trojan`, `tuic`, `hysteria`, `hysteria2`, `juicity` 会在解析时设置 `tls`: true (会使用 tls 类协议的通用逻辑), 输出时删除
|
||||
// 10. `sni` 在某些协议里会自动与 `servername` 转换
|
||||
// 11. 读取节点的 ca-str 和 _ca (后端文件路径) 字段, 自动计算 fingerprint (参考 https://t.me/zhetengsha/1512)
|
||||
@ -27,14 +21,8 @@ function operator(proxies = [], targetPlatform, context) {
|
||||
// 13. `test-url` 为测延迟链接, `test-timeout` 为测延迟超时
|
||||
// 14. `ports` 为端口跳跃, `hop-interval` 变换端口号的时间间隔
|
||||
// 15. `ip-version` 设置节点使用 IP 版本,可选:dual,ipv4,ipv6,ipv4-prefer,ipv6-prefer. 会进行内部转换, 若无法匹配则使用原始值
|
||||
// 16. `sing-box` 支持使用 `_network` 来设置 `network`, 例如 `tcp`, `udp`
|
||||
// 17. `block-quic` 支持 `auto`, `on`, `off`. 不同的平台不一定都支持, 会自动转换
|
||||
|
||||
// require 为 Node.js 的 require, 在 Node.js 运行环境下 可以用来引入模块
|
||||
// 例如在 Node.js 环境下, 将文件内容写入 /tmp/1.txt 文件
|
||||
// const fs = eval(`require("fs")`)
|
||||
// // const path = eval(`require("path")`)
|
||||
// fs.writeFileSync('/tmp/1.txt', $content, "utf8");
|
||||
|
||||
// $arguments 为传入的脚本参数
|
||||
|
||||
@ -47,27 +35,8 @@ function operator(proxies = [], targetPlatform, context) {
|
||||
// 先这样处理 encodeURIComponent('arg1=a&arg2=b')
|
||||
// /api/file/foo?$options=arg1%3Da%26arg2%3Db
|
||||
|
||||
// 默认会带上 _req 字段, 结构为
|
||||
// {
|
||||
// method,
|
||||
// url,
|
||||
// path,
|
||||
// query,
|
||||
// params,
|
||||
// headers,
|
||||
// body,
|
||||
// }
|
||||
// console.log($options)
|
||||
|
||||
// 若设置 $options._res.headers
|
||||
// 则会在输出文件时设置响应头, 例如:
|
||||
|
||||
// $options._res = {
|
||||
// headers: {
|
||||
// 'X-Custom': '1'
|
||||
// }
|
||||
// }
|
||||
|
||||
// targetPlatform 为输出的目标平台
|
||||
|
||||
// lodash
|
||||
@ -78,38 +47,8 @@ function operator(proxies = [], targetPlatform, context) {
|
||||
// scriptResourceCache 缓存
|
||||
// 可参考 https://t.me/zhetengsha/1003
|
||||
// const cache = scriptResourceCache
|
||||
// 设置
|
||||
// cache.set('a:1', 1)
|
||||
// cache.set('a:2', 2)
|
||||
// 获取
|
||||
// cache.get('a:1')
|
||||
// 支持第二个参数: 自定义过期时间
|
||||
// 支持第三个参数: 是否删除过期项
|
||||
// cache.get('a:2', 1000, true)
|
||||
|
||||
// 清理
|
||||
// cache._cleanup()
|
||||
// 支持第一个参数: 匹配前缀的项也一起删除
|
||||
// 支持第二个参数: 自定义过期时间
|
||||
// cache._cleanup('a:', 1000)
|
||||
|
||||
// 关于缓存时长
|
||||
|
||||
// 拉取 Sub-Store 订阅时, 会自动拉取远程订阅
|
||||
|
||||
// 远程订阅缓存是 1 小时, 缓存的唯一 key 为 url+ user agent. 可通过前端的刷新按钮刷新缓存. 或使用参数 noCache 来禁用缓存. 例: 内部配置订阅链接时使用 http://a.com#noCache, 外部使用 sub-store 链接时使用 https://sub.store/download/1?noCache=true
|
||||
|
||||
// 当使用相关脚本时, 若在对应的脚本中使用参数开启缓存, 可设置持久化缓存 sub-store-csr-expiration-time 的值来自定义默认缓存时长, 默认为 172800000 (48 * 3600 * 1000, 即 48 小时)
|
||||
|
||||
// 🎈Loon 可在插件中设置
|
||||
|
||||
// 其他平台同理, 持久化缓存数据在 JSON 里
|
||||
|
||||
// 当配合脚本使用时, 可以在脚本的前面添加一个脚本操作, 实现保留 1 小时的缓存. 这样比较灵活
|
||||
|
||||
// async function operator() {
|
||||
// scriptResourceCache._cleanup(undefined, 1 * 3600 * 1000);
|
||||
// }
|
||||
// cache.set(id, data)
|
||||
// cache.get(id)
|
||||
|
||||
// ProxyUtils 为节点处理工具
|
||||
// 可参考 https://t.me/zhetengsha/1066
|
||||
@ -128,13 +67,8 @@ function operator(proxies = [], targetPlatform, context) {
|
||||
// getISO, // 获取 ISO 3166-1 alpha-2 代码
|
||||
// Gist, // Gist 类
|
||||
// download, // 内部的下载方法, 见 backend/src/utils/download.js
|
||||
// downloadFile, // 下载二进制文件, 见 backend/src/utils/download.js
|
||||
// MMDB, // Node.js 环境 可用于模拟 Surge/Loon 的 $utils.ipasn, $utils.ipaso, $utils.geoip. 具体见 https://t.me/zhetengsha/1269
|
||||
// isValidUUID, // 辅助判断是否为有效的 UUID
|
||||
// Buffer, // https://github.com/feross/buffer
|
||||
// Base64, // https://github.com/dankogai/js-base64
|
||||
// }
|
||||
// 为兼容 https://github.com/xishang0128/sparkle 的 JavaScript 覆写, 也可以直接使用 `b64d`(Base64 解码), `b64e`(Base64 编码), `Buffer`, `yaml`(简单兼容了下 `yaml.parse` 和 `yaml.stringify`)
|
||||
|
||||
// 如果只是为了快速修改或者筛选 可以参考 脚本操作支持节点快捷脚本 https://t.me/zhetengsha/970 和 脚本筛选支持节点快捷脚本 https://t.me/zhetengsha/1009
|
||||
// ⚠️ 注意: 函数式(即本文件这样的 function operator() {}) 和快捷操作(下面使用 $server) 只能二选一
|
||||
@ -231,20 +165,6 @@ function operator(proxies = [], targetPlatform, context) {
|
||||
|
||||
// 若不存在 `source._collection`, 说明输出结果为单条订阅, 脚本设置在此单条订阅上
|
||||
|
||||
// 这个历史遗留原因, 是有点复杂. 提供一个例子, 用来取当前脚本所在的组合订阅或单条订阅名称
|
||||
|
||||
// let name = ''
|
||||
// for (const [key, value] of Object.entries(env.source)) {
|
||||
// if (!key.startsWith('_')) {
|
||||
// name = value.displayName || value.name
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// if (!name) {
|
||||
// const collection = env.source._collection
|
||||
// name = collection.displayName || collection.name
|
||||
// }
|
||||
|
||||
// 1. 输出单条订阅 sub-1 时, 该单条订阅中的脚本上下文为:
|
||||
// {
|
||||
// "source": {
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 129 KiB |
Loading…
x
Reference in New Issue
Block a user