chore(backend): overhaul proxy-utils coverage and retire legacy parser tooling

- replace PEG testcase suites with raw-input parser coverage
- add parser pipeline, URI, QX, Loon, and Surge integration specs
- add producer and preprocessor coverage with shared test helpers
- cover supported formats, protocol branches, and vmess/vless transport variants
- fix Loon vs Surge dispatch for Loon-only HTTP/SOCKS5 options
- remove proxy-utils debug logging
- simplify the test script and prune unused test/build dependencies
- drop obsolete gulp, bundle, and PEG source artifacts
This commit is contained in:
xream committed 2026-03-25 20:19:12 +08:00
1 parent eaba311e6b
commit 3cd71f9cab
23 files changed
+2451 -6264

No files matched your search

-51
View File
@@ -1,51 +0,0 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { build } = require('esbuild');
!(async () => {
const version = JSON.parse(
fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'),
).version.trim();
let content = fs.readFileSync(path.join(__dirname, 'sub-store.min.js'), {
encoding: 'utf8',
});
content = content.replace(
/eval\(('|")(require\(('|").*?('|")\))('|")\)/g,
'$2',
);
fs.writeFileSync(
path.join(__dirname, 'dist/sub-store.no-bundle.js'),
content,
{
encoding: 'utf8',
},
);
await build({
entryPoints: ['dist/sub-store.no-bundle.js'],
bundle: true,
minify: true,
sourcemap: true,
platform: 'node',
format: 'cjs',
outfile: 'dist/sub-store.bundle.js',
});
fs.writeFileSync(
path.join(__dirname, 'dist/sub-store.bundle.js'),
`// SUB_STORE_BACKEND_VERSION: ${version}
${fs.readFileSync(path.join(__dirname, 'dist/sub-store.bundle.js'), {
encoding: 'utf8',
})}`,
{
encoding: 'utf8',
},
);
})()
.catch((e) => {
console.log(e);
})
.finally(() => {
console.log('done');
});
-118
View File
@@ -1,118 +0,0 @@
import fs from 'fs';
import browserify from 'browserify';
import gulp from 'gulp';
import prettier from 'gulp-prettier';
import header from 'gulp-header';
import eslint from 'gulp-eslint-new';
import newFile from 'gulp-file';
import path from 'path';
import tap from 'gulp-tap';
import pkg from './package.json';
export function peggy() {
return gulp.src('src/**/*.peg').pipe(
tap(function (file) {
const filename = path.basename(file.path).split('.')[0] + '.js';
const raw = fs.readFileSync(file.path, 'utf8');
const contents = `import * as peggy from 'peggy';
const grammars = String.raw\`\n${raw}\n\`;
let parser;
export default function getParser() {
if (!parser) {
parser = peggy.generate(grammars);
}
return parser;
}\n`;
return newFile(filename, contents).pipe(
gulp.dest(path.dirname(file.path)),
);
}),
);
}
export function lint() {
return gulp
.src('src/**/*.js')
.pipe(eslint({ fix: true }))
.pipe(eslint.fix())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
export function styles() {
return gulp
.src('src/**/*.js')
.pipe(
prettier({
singleQuote: true,
trailingComma: 'all',
tabWidth: 4,
bracketSpacing: true,
}),
)
.pipe(gulp.dest((file) => file.base));
}
function scripts(src, dest) {
return () => {
return browserify(src)
.transform('babelify', {
presets: [['@babel/preset-env']],
plugins: [
[
'babel-plugin-relative-path-import',
{
paths: [
{
rootPathPrefix: '@',
rootPathSuffix: 'src',
},
],
},
],
],
})
.plugin('tinyify')
.bundle()
.pipe(fs.createWriteStream(dest));
};
}
function banner(dest) {
return () =>
gulp
.src(dest)
.pipe(
header(fs.readFileSync('./banner', 'utf-8'), {
pkg,
updated: new Date().toLocaleString('zh-CN'),
}),
)
.pipe(gulp.dest((file) => file.base));
}
const artifacts = [
{ src: 'src/main.js', dest: 'sub-store.min.js' },
{
src: 'src/products/resource-parser.loon.js',
dest: 'dist/sub-store-parser.loon.min.js',
},
{
src: 'src/products/cron-sync-artifacts.js',
dest: 'dist/cron-sync-artifacts.min.js',
},
{ src: 'src/products/sub-store-0.js', dest: 'dist/sub-store-0.min.js' },
{ src: 'src/products/sub-store-1.js', dest: 'dist/sub-store-1.min.js' },
];
export const build = gulp.series(
gulp.parallel(
artifacts.map((artifact) => scripts(artifact.src, artifact.dest)),
),
gulp.parallel(artifacts.map((artifact) => banner(artifact.dest))),
);
const all = gulp.series(peggy, lint, styles, build);
export default all;
+3 -19
View File
@@ -1,17 +1,15 @@
{
"name": "sub-store",
"version": "2.21.56",
"version": "2.21.57",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"scripts": {
"preinstall": "npx only-allow pnpm",
"test": "gulp peggy && npx cross-env BABEL_ENV=test mocha src/test/**/*.spec.js --require @babel/register --recursive",
"test": "mocha src/test/**/*.spec.js --require @babel/register --recursive",
"serve": "node sub-store.min.js",
"start": "nodemon -w src -w package.json --exec babel-node src/main.js",
"dev:esbuild": "nodemon -w src -w package.json dev-esbuild.js",
"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"
},
@@ -24,7 +22,6 @@
},
"dependencies": {
"@maxmind/geoip2-node": "^5.0.0",
"automerge": "1.0.1-preview.7",
"body-parser": "^1.19.0",
"buffer": "^6.0.3",
"connect-history-api-fallback": "^2.0.0",
@@ -52,26 +49,13 @@
"@babel/node": "^7.17.10",
"@babel/preset-env": "^7.18.0",
"@babel/register": "^7.17.7",
"@types/gulp": "^4.0.9",
"babel-plugin-relative-path-import": "^2.0.1",
"babelify": "^10.0.0",
"browser-pack-flat": "^3.4.2",
"browserify": "^17.0.0",
"chai": "^4.3.6",
"esbuild": "^0.19.8",
"eslint": "^8.16.0",
"gulp": "^4.0.2",
"gulp-babel": "^8.0.0",
"gulp-eslint-new": "^1.4.4",
"gulp-file": "^0.4.0",
"gulp-header": "^2.0.9",
"gulp-prettier": "^4.0.0",
"gulp-tap": "^2.0.0",
"mocha": "^10.0.0",
"nodemon": "^2.0.16",
"peggy": "^2.0.1",
"prettier": "2.6.2",
"prettier-plugin-sort-imports": "^1.6.1",
"tinyify": "^3.0.0"
"prettier": "2.6.2"
}
}
+3 -4021
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -136,7 +136,6 @@ async function processFn(
}
}
}
console.log(rawArgs);
url = `${url.split('#')[0]}${
rawArgs[2]
? `#${rawArgs[2]}`
+11 -2
View File
@@ -1657,10 +1657,16 @@ function Surge_Trojan() {
return { name, test, parse };
}
const LOON_ONLY_OPTIONS =
/(^|,)\s*(fast-open|over-tls|tls-name|ip-mode|tls-cert-sha256|tls-pubkey-sha256)\s*=/i;
function Surge_Http() {
const name = 'Surge HTTP Parser';
const test = (line) => {
return /^.*=\s*https?/.test(line.split(',')[0]);
return (
/^.*=\s*https?/.test(line.split(',')[0]) &&
!LOON_ONLY_OPTIONS.test(line)
);
};
const parse = (line) => getSurgeParser().parse(line);
return { name, test, parse };
@@ -1669,7 +1675,10 @@ function Surge_Http() {
function Surge_Socks5() {
const name = 'Surge Socks5 Parser';
const test = (line) => {
return /^.*=\s*socks5(-tls)?/.test(line.split(',')[0]);
return (
/^.*=\s*socks5(-tls)?/.test(line.split(',')[0]) &&
!LOON_ONLY_OPTIONS.test(line)
);
};
const parse = (line) => getSurgeParser().parse(line);
return { name, test, parse };
@@ -1,212 +0,0 @@
// global initializer
{{
function $set(obj, path, value) {
if (Object(obj) !== obj) return obj;
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path
.slice(0, -1)
.reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
path[path.length - 1]
] = value;
return obj;
}
}}
// per-parser initializer
{
const proxy = {};
const obfs = {};
const transport = {};
const $ = {};
function handleTransport() {
if (transport.type === "tcp") { /* do nothing */ }
else if (transport.type === "ws") {
proxy.network = "ws";
$set(proxy, "ws-opts.path", transport.path);
$set(proxy, "ws-opts.headers.Host", transport.host);
} else if (transport.type === "http") {
proxy.network = "http";
$set(proxy, "http-opts.path", transport.path);
$set(proxy, "http-opts.headers.Host", transport.host);
}
}
}
start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2/anytls) {
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/udp_over_tcp/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)* {
proxy.type = "ss";
// handle ss obfs
if (obfs.type == "http" || obfs.type === "tls") {
proxy.plugin = "obfs";
$set(proxy, "plugin-opts.mode", obfs.type);
$set(proxy, "plugin-opts.host", obfs.host);
$set(proxy, "plugin-opts.path", obfs.path);
}
}
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/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_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/flow/public_key/short_id/block_quic/others)* {
proxy.type = "vless";
handleTransport();
}
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
proxy.type = "trojan";
handleTransport();
}
anytls = tag equals "anytls"i address password (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/idle_session_check_interval/idle_session_timeout/min_idle_session/max_stream_count/others)* {
proxy.type = "anytls";
handleTransport();
}
hysteria2 = tag equals "hysteria2"i address password (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/ip_mode/block_quic/others)* {
proxy.type = "hysteria2";
}
https = tag equals "https"i address (username password)? (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
proxy.type = "http";
proxy.tls = true;
}
http = tag equals "http"i address (username password)? (fast_open/udp_relay/ip_mode/block_quic/others)* {
proxy.type = "http";
}
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
proxy.type = "socks5";
}
address = comma server:server comma port:port {
proxy.server = server;
proxy.port = port;
}
server = ip/domain
ip = & {
const start = peg$currPos;
let j = start;
while (j < input.length) {
if (input[j] === ",") break;
j++;
}
peg$currPos = j;
$.ip = input.substring(start, j).trim();
return true;
} { return $.ip; }
domain = match:[0-9a-zA-z-_.]+ {
const domain = match.join("");
if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
return domain;
}
throw new Error("Invalid domain: " + domain);
}
port = digits:[0-9]+ {
const port = parseInt(digits.join(""), 10);
if (port >= 0 && port <= 65535) {
return port;
}
throw new Error("Invalid port number: " + port);
}
method = comma 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"/"auto"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"none"/"rc4-md5"/"rc4"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
username = & {
let j = peg$currPos;
let start, end;
let first = true;
while (j < input.length) {
if (input[j] === ',') {
if (first) {
start = j + 1;
first = false;
} else {
end = j;
break;
}
}
j++;
}
const match = input.substring(start, end);
if (match.indexOf("=") === -1) {
$.username = match;
peg$currPos = end;
return true;
}
} { proxy.username = $.username; }
password = comma '"' match:[^"]* '"' { proxy.password = match.join(""); }
uuid = comma '"' match:[^"]+ '"' { proxy.uuid = match.join(""); }
obfs_typev = comma type:("http"/"tls") { obfs.type = type; }
obfs_hostv = comma match:[^,]+ { obfs.host = match.join(""); }
obfs_ss = comma "obfs-name" equals type:("http"/"tls") { obfs.type = type; }
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { obfs.type = type; }
obfs_ssr_param = comma "obfs-param" equals match:$[^,]+ { proxy["obfs-param"] = match; }
obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); }
obfs_uri = comma "obfs-uri" equals uri:uri { obfs.path = uri; }
uri = $[^,]+
transport = comma "transport" equals type:("tcp"/"ws"/"http") { transport.type = type; }
transport_host = comma "host" equals match:[^,]+ { transport.host = match.join("").replace(/^"(.*)"$/, '$1'); }
transport_path = comma "path" equals path:uri { transport.path = path; }
ssr_protocol = comma "protocol" equals protocol:("origin"/"auth_sha1_v4"/"auth_aes128_md5"/"auth_aes128_sha1"/"auth_chain_a"/"auth_chain_b") { proxy.protocol = protocol; }
ssr_protocol_param = comma "protocol-param" equals param:$[^=,]+ { proxy["protocol-param"] = param; }
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_name = comma sni:("tls-name") equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
sni = comma "sni" equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
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"; }
idle_session_check_interval = comma "idle-session-check-interval" equals match:$[0-9]+ { proxy["idle-session-check-interval"] = parseInt(match.trim()); }
idle_session_timeout = comma "idle-session-timeout" equals match:$[0-9]+ { proxy["idle-session-timeout"] = parseInt(match.trim()); }
min_idle_session = comma "min-idle-session" equals match:$[0-9]+ { proxy["min-idle-session"] = parseInt(match.trim()); }
max_stream_count = comma "max-stream-count" equals match:$[0-9]+ { proxy["max-stream-count"] = parseInt(match.trim()); }
udp_over_tcp = comma "udp-over-tcp" equals flag:bool { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 2; }
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
comma = _ "," _
equals = _ "=" _
_ = [ \r\t]*
bool = b:("true"/"false") { return b === "true" }
others = comma [^=,]+ equals [^=,]+
@@ -1,203 +0,0 @@
// global initializer
{{
function $set(obj, path, value) {
if (Object(obj) !== obj) return obj;
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path
.slice(0, -1)
.reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
path[path.length - 1]
] = value;
return obj;
}
}}
// per-parse initializer
{
const proxy = {};
const obfs = {};
const $ = {};
function handleObfs() {
if (obfs.type === "ws" || obfs.type === "wss") {
proxy.network = "ws";
if (obfs.type === 'wss') {
proxy.tls = true;
}
$set(proxy, "ws-opts.path", obfs.path);
$set(proxy, "ws-opts.headers.Host", obfs.host);
} else if (obfs.type === "over-tls") {
proxy.tls = true;
} else if (obfs.type === "http") {
proxy.network = "http";
$set(proxy, "http-opts.path", obfs.path);
$set(proxy, "http-opts.headers.Host", obfs.host);
}
}
}
start = (trojan/shadowsocks/vmess/vless/http/socks5) {
return proxy
}
trojan = "trojan" equals address
(password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/obfs/obfs_host/obfs_uri/tag/udp_relay/udp_over_tcp/fast_open/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
proxy.type = "trojan";
handleObfs();
}
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/reality_base64_pubkey/reality_hex_shortid/others)* {
if (proxy.protocol || proxy.type === "ssr") {
proxy.type = "ssr";
if (!proxy.protocol) {
proxy.protocol = "origin";
}
// handle ssr obfs
if (obfs.host) proxy["obfs-param"] = obfs.host;
if (obfs.type) proxy.obfs = obfs.type;
} else {
proxy.type = "ss";
// handle ss obfs
if (obfs.type == "http" || obfs.type === "tls") {
proxy.plugin = "obfs";
$set(proxy, "plugin-opts", {
mode: obfs.type
});
} else if (obfs.type === "ws" || obfs.type === "wss") {
proxy.plugin = "v2ray-plugin";
$set(proxy, "plugin-opts.mode", "websocket");
if (obfs.type === "wss") {
$set(proxy, "plugin-opts.tls", true);
}
} else if (obfs.type === 'over-tls') {
throw new Error('ss over-tls is not supported');
}
if (obfs.type) {
$set(proxy, "plugin-opts.host", obfs.host);
$set(proxy, "plugin-opts.path", obfs.path);
}
}
}
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/reality_base64_pubkey/reality_hex_shortid/others)* {
proxy.type = "vmess";
proxy.cipher = proxy.cipher || "none";
if (proxy.aead === false) {
proxy.alterId = 1;
} else {
proxy.alterId = 0;
}
handleObfs();
}
vless = "vless" 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/reality_base64_pubkey/reality_hex_shortid/vless_flow/others)* {
proxy.type = "vless";
proxy.cipher = proxy.cipher || "none";
handleObfs();
}
http = "http" equals address
(username/password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/fast_open/udp_relay/udp_over_tcp/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)*{
proxy.type = "http";
}
socks5 = "socks5" equals address
(username/password/password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/fast_open/udp_relay/udp_over_tcp/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
proxy.type = "socks5";
}
address = server:server ":" port:port {
proxy.server = server;
proxy.port = port;
}
server = ip/domain
domain = match:[0-9a-zA-z-_.]+ {
const domain = match.join("");
if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
return domain;
}
}
ip = & {
const start = peg$currPos;
let end;
let j = start;
while (j < input.length) {
if (input[j] === ",") break;
if (input[j] === ":") end = j;
j++;
}
peg$currPos = end || j;
$.ip = input.substring(start, end).trim();
return true;
} { return $.ip; }
port = digits:[0-9]+ {
const port = parseInt(digits.join(""), 10);
if (port >= 0 && port <= 65535) {
return port;
}
}
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");
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; }
tls_host = comma sni:("tls-host") equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
tls_verification = comma "tls-verification" equals flag:bool {
proxy["skip-cert-verify"] = !flag;
}
tls_fingerprint = comma "tls-cert-sha256" equals tls_fingerprint:$[^,]+ { proxy["tls-fingerprint"] = tls_fingerprint.trim(); }
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals param:$[^=,]+ { proxy["tls-pubkey-sha256"] = param; }
tls_alpn = comma "tls-alpn" equals param:$[^=,]+ { proxy["tls-alpn"] = param; }
tls_no_session_ticket = comma "tls-no-session-ticket" equals flag:bool {
proxy["tls-no-session-ticket"] = flag;
}
tls_no_session_reuse = comma "tls-no-session-reuse" equals flag:bool {
proxy["tls-no-session-reuse"] = flag;
}
obfs_ss = comma "obfs" equals type:("http"/"tls"/"wss"/"ws"/"over-tls") { obfs.type = type; return type; }
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { proxy.type = "ssr"; obfs.type = type; return type; }
obfs = comma "obfs" equals type:("wss"/"ws"/"over-tls"/"http") { obfs.type = type; return type; };
obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); }
obfs_uri = comma "obfs-uri" equals uri:uri { obfs.path = uri; }
ssr_protocol = comma "ssr-protocol" equals protocol:("origin"/"auth_sha1_v4"/"auth_aes128_md5"/"auth_aes128_sha1"/"auth_chain_a"/"auth_chain_b") { proxy.protocol = protocol; return protocol; }
ssr_protocol_param = comma "ssr-protocol-param" equals param:$[^=,]+ { proxy["protocol-param"] = param; }
reality_base64_pubkey = comma "reality-base64-pubkey" equals param:$[^=,]+ {
$set(proxy, "reality-opts.public-key", param);
}
reality_hex_shortid = comma "reality-hex-shortid" equals param:$[^=,]+ {
$set(proxy, "reality-opts.short-id", param);
}
vless_flow = comma "vless-flow" equals param:$[^=,]+ { proxy["flow"] = param; }
server_check_url = comma "server_check_url" equals param:$[^=,]+ { proxy["test-url"] = param; }
uri = $[^,]+
tag = comma "tag" equals tag:[^=,]+ { proxy.name = tag.join(""); }
others = comma [^=,]+ equals [^=,]+
comma = _ "," _
equals = _ "=" _
_ = [ \r\t]*
bool = b:("true"/"false") { return b === "true" }
@@ -1,267 +0,0 @@
// global initializer
{{
function $set(obj, path, value) {
if (Object(obj) !== obj) return obj;
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path
.slice(0, -1)
.reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
path[path.length - 1]
] = value;
return obj;
}
}}
// per-parser initializer
{
const proxy = {};
const obfs = {};
const $ = {};
function handleWebsocket() {
if (obfs.type === "ws") {
proxy.network = "ws";
$set(proxy, "ws-opts.path", obfs.path);
$set(proxy, "ws-opts.headers", obfs['ws-headers']);
if (proxy['ws-opts'] && proxy['ws-opts']['headers'] && proxy['ws-opts']['headers'].Host) {
proxy['ws-opts']['headers'].Host = proxy['ws-opts']['headers'].Host.replace(/^"(.*)"$/, '$1')
}
}
}
function handleShadowTLS() {
if (proxy['shadow-tls-password'] && !proxy['shadow-tls-version']) {
proxy['shadow-tls-version'] = 2;
}
}
}
start = (anytls/shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh/trust_tunnel/direct) {
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)* {
proxy.type = "ss";
// handle obfs
if (obfs.type == "http" || obfs.type === "tls") {
proxy.plugin = "obfs";
$set(proxy, "plugin-opts.mode", obfs.type);
$set(proxy, "plugin-opts.host", obfs.host);
$set(proxy, "plugin-opts.path", obfs.path);
}
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)* {
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;
}
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)* {
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)* {
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)* {
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)* {
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)* {
proxy.type = "snell";
// handle obfs
if (obfs.type == "http" || obfs.type === "tls") {
$set(proxy, "obfs-opts.mode", obfs.type);
$set(proxy, "obfs-opts.host", obfs.host);
$set(proxy, "obfs-opts.path", obfs.path);
}
handleShadowTLS();
}
tuic = tag equals "tuic" address (alpn/token/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
proxy.type = "tuic";
handleShadowTLS();
}
tuic_v5 = tag equals "tuic-v5" address (alpn/passwordk/uuidk/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
proxy.type = "tuic";
proxy.version = 5;
handleShadowTLS();
}
wireguard = tag equals "wireguard" (section_name/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
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/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/salamander_password/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/fast_open/tfo/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)* {
proxy.type = "socks5";
proxy.tls = true;
handleShadowTLS();
}
anytls = tag equals "anytls" address (passwordk/reuse/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/block_quic/others)* {
proxy.type = "anytls";
proxy.tls = true;
}
trust_tunnel = tag equals "trust-tunnel" address (usernamek/passwordk/reuse/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/block_quic/others)* {
proxy.type = "trusttunnel";
proxy.tls = true;
}
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)* {
proxy.type = "direct";
}
address = comma server:server comma port:port {
proxy.server = server;
proxy.port = port;
}
server = ip/domain
ip = & {
const start = peg$currPos;
let j = start;
while (j < input.length) {
if (input[j] === ",") break;
j++;
}
peg$currPos = j;
$.ip = input.substring(start, j).trim();
return true;
} { return $.ip; }
domain = match:[0-9a-zA-z-_.]+ {
const domain = match.join("");
if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
return domain;
}
}
port = digits:[0-9]+ {
const port = parseInt(digits.join(""), 10);
if (port >= 0 && port <= 65535) {
return port;
}
}
port_hopping_interval = comma "port-hopping-interval" equals match:$[0-9]+ { proxy["hop-interval"] = parseInt(match.trim()); }
username = & {
let j = peg$currPos;
let start, end;
let first = true;
while (j < input.length) {
if (input[j] === ',') {
if (first) {
start = j + 1;
first = false;
} else {
end = j;
break;
}
}
j++;
}
const match = input.substring(start, end);
if (match.indexOf("=") === -1) {
$.username = match;
peg$currPos = end;
return true;
}
} { proxy.username = $.username.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
password = comma match:[^,]+ { proxy.password = match.join("").replace(/^"(.*)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
tls = comma "tls" equals flag:bool { proxy.tls = flag; }
sni = comma "sni" equals match:[^,]+ {
const sni = match.join("").replace(/^"(.*)"$/, '$1');
if (sni === "off") {
proxy["disable-sni"] = true;
} else {
proxy.sni = sni;
}
}
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
tls_fingerprint = comma "server-cert-fingerprint-sha256" equals tls_fingerprint:$[^,]+ { proxy["tls-fingerprint"] = tls_fingerprint.trim(); }
snell_psk = comma "psk" equals match:[^,]+ { proxy.psk = match.join(""); }
snell_version = comma "version" equals match:$[0-9]+ { proxy.version = parseInt(match.trim()); }
usernamek = comma "username" equals match:[^,]+ { proxy.username = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
passwordk = comma "password" equals match:[^,]+ { proxy.password = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
vmess_uuid = comma "username" equals match:[^,]+ { proxy.uuid = match.join(""); }
vmess_aead = comma "vmess-aead" equals flag:bool { proxy.aead = flag; }
method = comma "encrypt-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"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
ws = comma "ws" equals flag:bool { obfs.type = "ws"; }
ws_headers = comma "ws-headers" equals headers:$[^,]+ {
const pairs = headers.split("|");
const result = {};
pairs.forEach(pair => {
const [key, value] = pair.trim().split(":");
result[key.trim()] = value.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1');
})
obfs["ws-headers"] = result;
}
ws_path = comma "ws-path" equals path:uri { obfs.path = path.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
obfs = comma "obfs" equals type:("http"/"tls") { obfs.type = type; }
obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); };
obfs_uri = comma "obfs-uri" equals path:uri { obfs.path = path }
uri = $[^,]+
udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
reuse = comma "reuse" equals flag:bool { proxy.reuse = flag; }
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
tfo = comma "tfo" equals flag:bool { proxy.tfo = flag; }
ip_version = comma "ip-version" equals match:[^,]+ { proxy["ip-version"] = match.join(""); }
section_name = comma "section-name" equals match:[^,]+ { proxy["section-name"] = match.join(""); }
no_error_alert = comma "no-error-alert" equals match:[^,]+ { proxy["no-error-alert"] = match.join(""); }
underlying_proxy = comma "underlying-proxy" equals match:[^,]+ { proxy["underlying-proxy"] = match.join(""); }
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
test_url = comma "test-url" equals match:[^,]+ { proxy["test-url"] = match.join(""); }
test_udp = comma "test-udp" equals match:[^,]+ { proxy["test-udp"] = match.join(""); }
test_timeout = comma "test-timeout" equals match:$[0-9]+ { proxy["test-timeout"] = parseInt(match.trim()); }
tos = comma "tos" equals match:$[0-9]+ { proxy.tos = parseInt(match.trim()); }
interface = comma "interface" equals match:[^,]+ { proxy.interface = match.join(""); }
allow_other_interface = comma "allow-other-interface" equals flag:bool { proxy["allow-other-interface"] = flag; }
hybrid = comma "hybrid" equals flag:bool { proxy.hybrid = flag; }
idle_timeout = comma "idle-timeout" equals match:$[0-9]+ { proxy["idle-timeout"] = parseInt(match.trim()); }
private_key = comma "private-key" equals match:[^,]+ { proxy["keystore-private-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
server_fingerprint = comma "server-fingerprint" equals match:[^,]+ { proxy["server-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match.join(""); }
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'); }
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(""); }
salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); proxy.obfs = 'salamander'; }
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
comma = _ "," _
equals = _ "=" _
_ = [ \r\t]*
bool = b:("true"/"false") { return b === "true" }
others = comma [^=,]+ equals [^=,]+
@@ -1,158 +0,0 @@
// global initializer
{{
function $set(obj, path, value) {
if (Object(obj) !== obj) return obj;
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path
.slice(0, -1)
.reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
path[path.length - 1]
] = value;
return obj;
}
function toBool(str) {
if (typeof str === 'undefined' || str === null) return undefined;
return /(TRUE)|1/i.test(str);
}
}}
{
const proxy = {};
const obfs = {};
const $ = {};
const params = {};
}
start = (trojan) {
return proxy
}
trojan = "trojan://" password:password "@" server:server ":" port:port "/"? params? name:name?{
proxy.type = "trojan";
proxy.password = password;
proxy.server = server;
proxy.port = port;
proxy.name = name;
// name may be empty
if (!proxy.name) {
proxy.name = server + ":" + port;
}
};
password = match:$[^@]+ {
return decodeURIComponent(match);
};
server = ip/domain;
domain = match:[0-9a-zA-z-_.]+ {
const domain = match.join("");
if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
return domain;
}
}
ip = & {
const start = peg$currPos;
let end;
let j = start;
while (j < input.length) {
if (input[j] === ",") break;
if (input[j] === ":") end = j;
j++;
}
peg$currPos = end || j;
$.ip = input.substring(start, end).trim();
return true;
} { return $.ip; }
port = digits:[0-9]+ {
const port = parseInt(digits.join(""), 10);
if (port >= 0 && port <= 65535) {
return port;
} else {
throw new Error("Invalid port: " + port);
}
}
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;
proxy.alpn = params.alpn ? decodeURIComponent(params.alpn).split(',') : undefined;
if (toBool(params["ws"])) {
proxy.network = "ws";
$set(proxy, "ws-opts.path", params["wspath"]);
}
if (params["type"]) {
let httpupgrade
proxy.network = params["type"]
if(proxy.network === 'httpupgrade') {
proxy.network = 'ws'
httpupgrade = true
}
if (['grpc'].includes(proxy.network)) {
proxy[proxy.network + '-opts'] = {
'grpc-service-name': params["serviceName"],
'_grpc-type': params["mode"],
'_grpc-authority': params["authority"],
};
} else {
if (params["path"]) {
$set(proxy, proxy.network+"-opts.path", decodeURIComponent(params["path"]));
}
if (params["host"]) {
$set(proxy, proxy.network+"-opts.headers.Host", decodeURIComponent(params["host"]));
}
if (httpupgrade) {
$set(proxy, proxy.network+"-opts.v2ray-http-upgrade", true);
$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"]);
proxy.tfo = toBool(params["tfo"]);
}
param = kv/single;
kv = key:$[a-z]i+ "=" value:$[^&#]i* {
params[key] = value;
}
single = key:$[a-z]i+ {
params[key] = true;
};
name = "#" + match:$.* {
return decodeURIComponent(match);
}
+36
View File
@@ -0,0 +1,36 @@
import { expect } from 'chai';
import { ProxyUtils } from '@/core/proxy-utils';
export const UUID = '11111111-1111-4111-8111-111111111111';
export function clone(value) {
return JSON.parse(JSON.stringify(value));
}
export function parseAll(raw) {
return ProxyUtils.parse(raw);
}
export function parseOne(raw) {
const proxies = parseAll(raw);
expect(proxies, raw).to.have.length(1);
return proxies[0];
}
export function expectSubset(actual, expected, path = 'proxy') {
if (Array.isArray(expected)) {
expect(actual, path).to.deep.equal(expected);
return;
}
if (expected && typeof expected === 'object') {
expect(actual, path).to.be.an('object');
for (const [key, value] of Object.entries(expected)) {
expectSubset(actual[key], value, `${path}.${key}`);
}
return;
}
expect(actual, path).to.deep.equal(expected);
}
-144
View File
@@ -1,144 +0,0 @@
import getLoonParser from '@/core/proxy-utils/parsers/peggy/loon';
import { describe, it } from 'mocha';
import testcases from './testcases';
import { expect } from 'chai';
const parser = getLoonParser();
describe('Loon', function () {
describe('shadowsocks', function () {
it('test shadowsocks simple', function () {
const { input, expected } = testcases.SS.SIMPLE;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
it('test shadowsocks obfs + tls', function () {
const { input, expected } = testcases.SS.OBFS_TLS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
it('test shadowsocks obfs + http', function () {
const { input, expected } = testcases.SS.OBFS_HTTP;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
});
describe('shadowsocksr', function () {
it('test shadowsocksr simple', function () {
const { input, expected } = testcases.SSR.SIMPLE;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
});
describe('trojan', function () {
it('test trojan simple', function () {
const { input, expected } = testcases.TROJAN.SIMPLE;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
it('test trojan + ws', function () {
const { input, expected } = testcases.TROJAN.WS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
it('test trojan + wss', function () {
const { input, expected } = testcases.TROJAN.WSS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
});
describe('vmess', function () {
it('test vmess simple', function () {
const { input, expected } = testcases.VMESS.SIMPLE;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vmess + aead', function () {
const { input, expected } = testcases.VMESS.AEAD;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vmess + ws', function () {
const { input, expected } = testcases.VMESS.WS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vmess + wss', function () {
const { input, expected } = testcases.VMESS.WSS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vmess + http', function () {
const { input, expected } = testcases.VMESS.HTTP;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vmess + http + tls', function () {
const { input, expected } = testcases.VMESS.HTTP_TLS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
});
describe('vless', function () {
it('test vless simple', function () {
const { input, expected } = testcases.VLESS.SIMPLE;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vless + ws', function () {
const { input, expected } = testcases.VLESS.WS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vless + wss', function () {
const { input, expected } = testcases.VLESS.WSS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vless + http', function () {
const { input, expected } = testcases.VLESS.HTTP;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
it('test vless + http + tls', function () {
const { input, expected } = testcases.VLESS.HTTP_TLS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected.Loon);
});
});
describe('http(s)', function () {
it('test http simple', function () {
const { input, expected } = testcases.HTTP.SIMPLE;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
it('test http with authentication', function () {
const { input, expected } = testcases.HTTP.AUTH;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
it('test https', function () {
const { input, expected } = testcases.HTTP.TLS;
const proxy = parser.parse(input.Loon);
expect(proxy).eql(expected);
});
});
});
@@ -0,0 +1,188 @@
import { Base64 } from 'js-base64';
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { parseAll, parseOne, expectSubset, UUID } from './helpers';
describe('Proxy parser pipeline coverage', function () {
it('parses base64-encoded subscriptions', function () {
const raw = Base64.encode(
[
'https://alice:pa%24%24@https.example.com#HTTPS%20Default',
`socks://${encodeURIComponent(
Base64.encode('bob:secret'),
)}@socks.example.com:1080#SOCKS`,
].join('\n'),
);
const proxies = parseAll(raw);
expect(proxies).to.have.length(2);
expectSubset(proxies[0], {
type: 'http',
name: 'HTTPS Default',
server: 'https.example.com',
port: 443,
tls: true,
username: 'alice',
password: 'pa$$',
});
expectSubset(proxies[1], {
type: 'socks5',
name: 'SOCKS',
server: 'socks.example.com',
port: 1080,
username: 'bob',
password: 'secret',
});
});
it('parses SSD subscriptions into shadowsocks nodes', function () {
const payload = {
port: 8388,
encryption: 'aes-128-gcm',
password: 'shared-secret',
servers: [
{
server: 'ssd.example.com',
remarks: 'SSD Node',
plugin: 'obfs-local',
plugin_options: 'obfs=http;obfs-host=cdn.example.com',
},
],
};
const proxy = parseOne(`ssd://${Base64.encode(JSON.stringify(payload))}`);
expectSubset(proxy, {
type: 'ss',
name: 'SSD Node',
server: 'ssd.example.com',
port: 8388,
cipher: 'aes-128-gcm',
password: 'shared-secret',
plugin: 'obfs',
'plugin-opts': {
mode: 'http',
host: 'cdn.example.com',
},
});
});
it('extracts [Proxy] blocks from full config documents before parsing', function () {
const raw = `[General]
skip-proxy = 192.168.0.0/16
[Proxy]
Direct = direct
HTTP = http,full-config.example.com,8080,username=user,password=pass
[Rule]
FINAL,DIRECT
`;
const proxies = parseAll(raw);
expect(proxies).to.have.length(2);
expectSubset(proxies[0], {
type: 'direct',
name: 'Direct',
});
expectSubset(proxies[1], {
type: 'http',
name: 'HTTP',
server: 'full-config.example.com',
port: 8080,
username: 'user',
password: 'pass',
});
});
it('parses full Clash YAML documents end-to-end', function () {
const raw = `proxies:
- name: clash-vless
type: vless
server: clash.example.com
port: 443
uuid: ${UUID}
servername: sni.example.com
reality-opts:
public-key: pubkey
short-id: 08
- name: clash-http
type: http
server: http.clash.example.com
port: 8080
benchmark-url: https://check.example.com
benchmark-timeout: 9
`;
const proxies = parseAll(raw);
expect(proxies).to.have.length(2);
expectSubset(proxies[0], {
type: 'vless',
name: 'clash-vless',
server: 'clash.example.com',
port: 443,
uuid: UUID,
sni: 'sni.example.com',
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
});
expectSubset(proxies[1], {
type: 'http',
name: 'clash-http',
server: 'http.clash.example.com',
port: 8080,
'test-url': 'https://check.example.com',
'test-timeout': 9,
});
});
it('accepts every Clash-supported proxy type as inline objects', function () {
const supportedTypes = [
'tailscale',
'trusttunnel',
'naive',
'anytls',
'mieru',
'masque',
'sudoku',
'juicity',
'ss',
'ssr',
'vmess',
'socks5',
'http',
'snell',
'trojan',
'tuic',
'vless',
'hysteria',
'hysteria2',
'wireguard',
'ssh',
'direct',
];
for (const type of supportedTypes) {
const proxy = parseOne(
JSON.stringify({
name: `${type}-inline`,
type,
server: `${type}.example.com`,
port: 443,
}),
);
expectSubset(proxy, {
name: `${type}-inline`,
type,
});
}
});
});
-142
View File
@@ -1,142 +0,0 @@
import getQXParser from '@/core/proxy-utils/parsers/peggy/qx';
import { describe, it } from 'mocha';
import testcases from './testcases';
import { expect } from 'chai';
const parser = getQXParser();
describe('QX', function () {
describe('shadowsocks', function () {
it('test shadowsocks simple', function () {
const { input, expected } = testcases.SS.SIMPLE;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test shadowsocks obfs + tls', function () {
const { input, expected } = testcases.SS.OBFS_TLS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test shadowsocks obfs + http', function () {
const { input, expected } = testcases.SS.OBFS_HTTP;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test shadowsocks v2ray-plugin + ws', function () {
const { input, expected } = testcases.SS.V2RAY_PLUGIN_WS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test shadowsocks v2ray-plugin + wss', function () {
const { input, expected } = testcases.SS.V2RAY_PLUGIN_WSS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
});
describe('shadowsocksr', function () {
it('test shadowsocksr simple', function () {
const { input, expected } = testcases.SSR.SIMPLE;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
});
describe('trojan', function () {
it('test trojan simple', function () {
const { input, expected } = testcases.TROJAN.SIMPLE;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test trojan + ws', function () {
const { input, expected } = testcases.TROJAN.WS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test trojan + wss', function () {
const { input, expected } = testcases.TROJAN.WSS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test trojan + tls fingerprint', function () {
const { input, expected } = testcases.TROJAN.TLS_FINGERPRINT;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
});
describe('vmess', function () {
it('test vmess simple', function () {
const { input, expected } = testcases.VMESS.SIMPLE;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected.QX);
});
it('test vmess aead', function () {
const { input, expected } = testcases.VMESS.AEAD;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected.QX);
});
it('test vmess + ws', function () {
const { input, expected } = testcases.VMESS.WS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected.QX);
});
it('test vmess + wss', function () {
const { input, expected } = testcases.VMESS.WSS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected.QX);
});
it('test vmess + http', function () {
const { input, expected } = testcases.VMESS.HTTP;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected.QX);
});
});
describe('http', function () {
it('test http simple', function () {
const { input, expected } = testcases.HTTP.SIMPLE;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test http with authentication', function () {
const { input, expected } = testcases.HTTP.AUTH;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test https', function () {
const { input, expected } = testcases.HTTP.TLS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
});
describe('socks5', function () {
it('test socks5 simple', function () {
const { input, expected } = testcases.SOCKS5.SIMPLE;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test socks5 with authentication', function () {
const { input, expected } = testcases.SOCKS5.AUTH;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
it('test socks5 + tls', function () {
const { input, expected } = testcases.SOCKS5.TLS;
const proxy = parser.parse(input.QX);
expect(proxy).eql(expected);
});
});
});
@@ -1,138 +0,0 @@
import getSurgeParser from '@/core/proxy-utils/parsers/peggy/surge';
import { describe, it } from 'mocha';
import testcases from './testcases';
import { expect } from 'chai';
const parser = getSurgeParser();
describe('Surge', function () {
describe('shadowsocks', function () {
it('test shadowsocks simple', function () {
const { input, expected } = testcases.SS.SIMPLE;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test shadowsocks obfs + tls', function () {
const { input, expected } = testcases.SS.OBFS_TLS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test shadowsocks obfs + http', function () {
const { input, expected } = testcases.SS.OBFS_HTTP;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
});
describe('trojan', function () {
it('test trojan simple', function () {
const { input, expected } = testcases.TROJAN.SIMPLE;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test trojan + ws', function () {
const { input, expected } = testcases.TROJAN.WS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test trojan + wss', function () {
const { input, expected } = testcases.TROJAN.WSS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test trojan + tls fingerprint', function () {
const { input, expected } = testcases.TROJAN.TLS_FINGERPRINT;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
});
describe('vmess', function () {
it('test vmess simple', function () {
const { input, expected } = testcases.VMESS.SIMPLE;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected.Surge);
});
it('test vmess aead', function () {
const { input, expected } = testcases.VMESS.AEAD;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected.Surge);
});
it('test vmess + ws', function () {
const { input, expected } = testcases.VMESS.WS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected.Surge);
});
it('test vmess + wss', function () {
const { input, expected } = testcases.VMESS.WSS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected.Surge);
});
});
describe('http', function () {
it('test http simple', function () {
const { input, expected } = testcases.HTTP.SIMPLE;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test http with authentication', function () {
const { input, expected } = testcases.HTTP.AUTH;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test https', function () {
const { input, expected } = testcases.HTTP.TLS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
});
describe('socks5', function () {
it('test socks5 simple', function () {
const { input, expected } = testcases.SOCKS5.SIMPLE;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test socks5 with authentication', function () {
const { input, expected } = testcases.SOCKS5.AUTH;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test socks5 + tls', function () {
const { input, expected } = testcases.SOCKS5.TLS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
});
describe('snell', function () {
it('test snell simple', function () {
const { input, expected } = testcases.SNELL.SIMPLE;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test snell obfs + http', function () {
const { input, expected } = testcases.SNELL.OBFS_HTTP;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
it('test snell obfs + tls', function () {
const { input, expected } = testcases.SNELL.OBFS_TLS;
const proxy = parser.parse(input.Surge);
expect(proxy).eql(expected);
});
});
});
-749
View File
@@ -1,749 +0,0 @@
function createTestCases() {
const name = 'name';
const server = 'example.com';
const port = 10086;
const cipher = 'chacha20';
const username = 'username';
const password = 'password';
const obfs_host = 'obfs.com';
const obfs_path = '/resource/file';
const ssr_protocol = 'auth_chain_b';
const ssr_protocol_param = 'def';
const ssr_obfs = 'tls1.2_ticket_fastauth';
const ssr_obfs_param = 'obfs.com';
const uuid = '23ad6b10-8d1a-40f7-8ad0-e3e35cd32291';
const sni = 'sni.com';
const tls_fingerprint =
'67:1B:C8:F2:D4:60:DD:A7:EE:60:DA:BB:A3:F9:A4:D7:C8:29:0F:3E:2F:75:B6:A9:46:88:48:7D:D3:97:7E:98';
const SS = {
SIMPLE: {
input: {
Loon: `${name}=shadowsocks,${server},${port},${cipher},"${password}"`,
QX: `shadowsocks=${server}:${port},method=${cipher},password=${password},tag=${name}`,
Surge: `${name}=ss,${server},${port},encrypt-method=${cipher},password=${password}`,
},
expected: {
type: 'ss',
name,
server,
port,
cipher,
password,
},
},
OBFS_TLS: {
input: {
Loon: `${name}=shadowsocks,${server},${port},${cipher},"${password}",obfs-name=tls,obfs-uri=${obfs_path},obfs-host=${obfs_host}`,
QX: `shadowsocks=${server}:${port},method=${cipher},password=${password},obfs=tls,obfs-host=${obfs_host},obfs-uri=${obfs_path},tag=${name}`,
Surge: `${name}=ss,${server},${port},encrypt-method=${cipher},password=${password},obfs=tls,obfs-host=${obfs_host},obfs-uri=${obfs_path}`,
},
expected: {
type: 'ss',
name,
server,
port,
cipher,
password,
plugin: 'obfs',
'plugin-opts': {
mode: 'tls',
path: obfs_path,
host: obfs_host,
},
},
},
OBFS_HTTP: {
input: {
Loon: `${name}=shadowsocks,${server},${port},${cipher},"${password}",obfs-name=http,obfs-uri=${obfs_path},obfs-host=${obfs_host}`,
QX: `shadowsocks=${server}:${port},method=${cipher},password=${password},obfs=http,obfs-host=${obfs_host},obfs-uri=${obfs_path},tag=${name}`,
Surge: `${name}=ss,${server},${port},encrypt-method=${cipher},password=${password},obfs=http,obfs-host=${obfs_host},obfs-uri=${obfs_path}`,
},
expected: {
type: 'ss',
name,
server,
port,
cipher,
password,
plugin: 'obfs',
'plugin-opts': {
mode: 'http',
path: obfs_path,
host: obfs_host,
},
},
},
V2RAY_PLUGIN_WS: {
input: {
QX: `shadowsocks=${server}:${port},method=${cipher},password=${password},obfs=ws,obfs-host=${obfs_host},obfs-uri=${obfs_path},tag=${name}`,
},
expected: {
type: 'ss',
name,
server,
port,
cipher,
password,
plugin: 'v2ray-plugin',
'plugin-opts': {
mode: 'websocket',
path: obfs_path,
host: obfs_host,
},
},
},
V2RAY_PLUGIN_WSS: {
input: {
QX: `shadowsocks=${server}:${port},method=${cipher},password=${password},obfs=wss,obfs-host=${obfs_host},obfs-uri=${obfs_path},tag=${name}`,
},
expected: {
type: 'ss',
name,
server,
port,
cipher,
password,
plugin: 'v2ray-plugin',
'plugin-opts': {
mode: 'websocket',
path: obfs_path,
host: obfs_host,
tls: true,
},
},
},
};
const SSR = {
SIMPLE: {
input: {
QX: `shadowsocks=${server}:${port},method=${cipher},password=${password},ssr-protocol=${ssr_protocol},ssr-protocol-param=${ssr_protocol_param},obfs=${ssr_obfs},obfs-host=${ssr_obfs_param},tag=${name}`,
Loon: `${name}=shadowsocksr,${server},${port},${cipher},"${password}",protocol=${ssr_protocol},protocol-param=${ssr_protocol_param},obfs=${ssr_obfs},obfs-param=${ssr_obfs_param}`,
},
expected: {
type: 'ssr',
name,
server,
port,
cipher,
password,
obfs: ssr_obfs,
protocol: ssr_protocol,
'obfs-param': ssr_obfs_param,
'protocol-param': ssr_protocol_param,
},
},
};
const TROJAN = {
SIMPLE: {
input: {
QX: `trojan=${server}:${port},password=${password},tag=${name}`,
Loon: `${name}=trojan,${server},${port},"${password}"`,
Surge: `${name}=trojan,${server},${port},password=${password}`,
},
expected: {
type: 'trojan',
name,
server,
port,
password,
},
},
WS: {
input: {
QX: `trojan=${server}:${port},password=${password},obfs=ws,obfs-host=${obfs_host},obfs-uri=${obfs_path},tag=${name}`,
Loon: `${name}=trojan,${server},${port},"${password}",transport=ws,path=${obfs_path},host=${obfs_host}`,
Surge: `${name}=trojan,${server},${port},password=${password},ws=true,ws-path=${obfs_path},ws-headers=Host:${obfs_host}`,
},
expected: {
type: 'trojan',
name,
server,
port,
password,
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
},
},
WSS: {
input: {
QX: `trojan=${server}:${port},password=${password},obfs=wss,obfs-host=${obfs_host},obfs-uri=${obfs_path},tls-verification=false,tls-host=${sni},tag=${name}`,
Loon: `${name}=trojan,${server},${port},"${password}",transport=ws,path=${obfs_path},host=${obfs_host},over-tls=true,tls-name=${sni},skip-cert-verify=true`,
Surge: `${name}=trojan,${server},${port},password=${password},ws=true,ws-path=${obfs_path},ws-headers=Host:${obfs_host},skip-cert-verify=true,sni=${sni},tls=true`,
},
expected: {
type: 'trojan',
name,
server,
port,
password,
network: 'ws',
tls: true,
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
'skip-cert-verify': true,
sni,
},
},
TLS_FINGERPRINT: {
input: {
QX: `trojan=${server}:${port},password=${password},tls-verification=false,tls-host=${sni},tls-cert-sha256=${tls_fingerprint},tag=${name},over-tls=true`,
Surge: `${name}=trojan,${server},${port},password=${password},skip-cert-verify=true,sni=${sni},tls=true,server-cert-fingerprint-sha256=${tls_fingerprint}`,
},
expected: {
type: 'trojan',
name,
server,
port,
password,
tls: true,
'skip-cert-verify': true,
sni,
'tls-fingerprint': tls_fingerprint,
},
},
};
const VMESS = {
SIMPLE: {
input: {
QX: `vmess=${server}:${port},method=${cipher},password=${uuid},tag=${name}`,
Loon: `${name}=vmess,${server},${port},${cipher},"${uuid}"`,
Surge: `${name}=vmess,${server},${port},username=${uuid}`,
},
expected: {
QX: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
alterId: 0,
},
Loon: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
alterId: 0,
},
Surge: {
type: 'vmess',
name,
server,
port,
uuid,
cipher: 'none', // Surge lacks support for specifying cipher for vmess protocol!
alterId: 0,
},
},
},
AEAD: {
input: {
QX: `vmess=${server}:${port},method=${cipher},password=${uuid},aead=true,tag=${name}`,
Loon: `${name}=vmess,${server},${port},${cipher},"${uuid}",alterId=0`,
Surge: `${name}=vmess,${server},${port},username=${uuid},vmess-aead=true`,
},
expected: {
QX: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
aead: true,
alterId: 0,
},
Loon: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
alterId: 0,
},
Surge: {
type: 'vmess',
name,
server,
port,
uuid,
cipher: 'none', // Surge lacks support for specifying cipher for vmess protocol!
alterId: 0,
aead: true,
},
},
},
WS: {
input: {
QX: `vmess=${server}:${port},method=${cipher},password=${uuid},obfs=ws,obfs-host=${obfs_host},obfs-uri=${obfs_path},tag=${name}`,
Loon: `${name}=vmess,${server},${port},${cipher},"${uuid}",transport=ws,host=${obfs_host},path=${obfs_path}`,
Surge: `${name}=vmess,${server},${port},username=${uuid},ws=true,ws-path=${obfs_path},ws-headers=Host:${obfs_host}`,
},
expected: {
QX: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
alterId: 0,
},
Loon: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
alterId: 0,
},
Surge: {
type: 'vmess',
name,
server,
port,
uuid,
cipher: 'none', // Surge lacks support for specifying cipher for vmess protocol!
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
alterId: 0,
},
},
},
WSS: {
input: {
QX: `vmess=${server}:${port},method=${cipher},password=${uuid},obfs=wss,obfs-host=${obfs_host},obfs-uri=${obfs_path},tls-verification=false,tls-host=${sni},tag=${name}`,
Loon: `${name}=vmess,${server},${port},${cipher},"${uuid}",transport=ws,host=${obfs_host},path=${obfs_path},over-tls=true,tls-name=${sni},skip-cert-verify=true`,
Surge: `${name}=vmess,${server},${port},username=${uuid},ws=true,ws-path=${obfs_path},ws-headers=Host:${obfs_host},skip-cert-verify=true,sni=${sni},tls=true`,
},
expected: {
QX: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
tls: true,
'skip-cert-verify': true,
sni,
alterId: 0,
},
Loon: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
tls: true,
'skip-cert-verify': true,
sni,
alterId: 0,
},
Surge: {
type: 'vmess',
name,
server,
port,
uuid,
cipher: 'none', // Surge lacks support for specifying cipher for vmess protocol!
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
tls: true,
'skip-cert-verify': true,
sni,
alterId: 0,
},
},
},
HTTP: {
input: {
QX: `vmess=${server}:${port},method=${cipher},password=${uuid},obfs=http,obfs-host=${obfs_host},obfs-uri=${obfs_path},tag=${name}`,
Loon: `${name}=vmess,${server},${port},${cipher},"${uuid}",transport=http,host=${obfs_host},path=${obfs_path}`,
},
expected: {
QX: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
network: 'http',
'http-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
alterId: 0,
},
Loon: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
network: 'http',
'http-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
alterId: 0,
},
},
},
HTTP_TLS: {
input: {
Loon: `${name}=vmess,${server},${port},${cipher},"${uuid}",transport=http,host=${obfs_host},path=${obfs_path},over-tls=true,tls-name=${sni},skip-cert-verify=true`,
},
expected: {
Loon: {
type: 'vmess',
name,
server,
port,
uuid,
cipher,
network: 'http',
'http-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
tls: true,
'skip-cert-verify': true,
sni,
alterId: 0,
},
},
},
};
const VLESS = {
SIMPLE: {
input: {
Loon: `${name}=vless,${server},${port},"${uuid}"`,
},
expected: {
Loon: {
type: 'vless',
name,
server,
port,
uuid,
},
},
},
WS: {
input: {
Loon: `${name}=vless,${server},${port},"${uuid}",transport=ws,host=${obfs_host},path=${obfs_path}`,
},
expected: {
Loon: {
type: 'vless',
name,
server,
port,
uuid,
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
},
},
},
WSS: {
input: {
Loon: `${name}=vless,${server},${port},"${uuid}",transport=ws,host=${obfs_host},path=${obfs_path},over-tls=true,tls-name=${sni},skip-cert-verify=true`,
},
expected: {
Loon: {
type: 'vless',
name,
server,
port,
uuid,
network: 'ws',
'ws-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
tls: true,
'skip-cert-verify': true,
sni,
},
},
},
HTTP: {
input: {
Loon: `${name}=vless,${server},${port},"${uuid}",transport=http,host=${obfs_host},path=${obfs_path}`,
},
expected: {
Loon: {
type: 'vless',
name,
server,
port,
uuid,
network: 'http',
'http-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
},
},
},
HTTP_TLS: {
input: {
Loon: `${name}=vless,${server},${port},"${uuid}",transport=http,host=${obfs_host},path=${obfs_path},over-tls=true,tls-name=${sni},skip-cert-verify=true`,
},
expected: {
Loon: {
type: 'vless',
name,
server,
port,
uuid,
network: 'http',
'http-opts': {
path: obfs_path,
headers: {
Host: obfs_host,
},
},
tls: true,
'skip-cert-verify': true,
sni,
},
},
},
};
const HTTP = {
SIMPLE: {
input: {
Loon: `${name}=http,${server},${port}`,
QX: `http=${server}:${port},tag=${name}`,
Surge: `${name}=http,${server},${port}`,
},
expected: {
type: 'http',
name,
server,
port,
},
},
AUTH: {
input: {
Loon: `${name}=http,${server},${port},${username},"${password}"`,
QX: `http=${server}:${port},tag=${name},username=${username},password=${password}`,
Surge: `${name}=http,${server},${port},${username},${password}`,
},
expected: {
type: 'http',
name,
server,
port,
username,
password,
},
},
TLS: {
input: {
Loon: `${name}=https,${server},${port},${username},"${password}",tls-name=${sni},skip-cert-verify=true`,
QX: `http=${server}:${port},username=${username},password=${password},over-tls=true,tls-host=${sni},tls-verification=false,tag=${name}`,
Surge: `${name}=https,${server},${port},${username},${password},sni=${sni},skip-cert-verify=true`,
},
expected: {
type: 'http',
name,
server,
port,
username,
password,
sni,
'skip-cert-verify': true,
tls: true,
},
},
};
const SOCKS5 = {
SIMPLE: {
input: {
QX: `socks5=${server}:${port},tag=${name}`,
Surge: `${name}=socks5,${server},${port}`,
},
expected: {
type: 'socks5',
name,
server,
port,
},
},
AUTH: {
input: {
QX: `socks5=${server}:${port},tag=${name},username=${username},password=${password}`,
Surge: `${name}=socks5,${server},${port},${username},${password}`,
},
expected: {
type: 'socks5',
name,
server,
port,
username,
password,
},
},
TLS: {
input: {
QX: `socks5=${server}:${port},username=${username},password=${password},over-tls=true,tls-host=${sni},tls-verification=false,tag=${name}`,
Surge: `${name}=socks5-tls,${server},${port},${username},${password},sni=${sni},skip-cert-verify=true`,
},
expected: {
type: 'socks5',
name,
server,
port,
username,
password,
sni,
'skip-cert-verify': true,
tls: true,
},
},
};
const SNELL = {
SIMPLE: {
input: {
Surge: `${name}=snell,${server},${port},psk=${password},version=3`,
},
expected: {
type: 'snell',
name,
server,
port,
psk: password,
version: 3,
},
},
OBFS_HTTP: {
input: {
Surge: `${name}=snell,${server},${port},psk=${password},version=3,obfs=http,obfs-host=${obfs_host},obfs-uri=${obfs_path}`,
},
expected: {
type: 'snell',
name,
server,
port,
psk: password,
version: 3,
'obfs-opts': {
mode: 'http',
host: obfs_host,
path: obfs_path,
},
},
},
OBFS_TLS: {
input: {
Surge: `${name}=snell,${server},${port},psk=${password},version=3,obfs=tls,obfs-host=${obfs_host},obfs-uri=${obfs_path}`,
},
expected: {
type: 'snell',
name,
server,
port,
psk: password,
version: 3,
'obfs-opts': {
mode: 'tls',
host: obfs_host,
path: obfs_path,
},
},
},
};
return {
SS,
SSR,
VMESS,
VLESS,
TROJAN,
HTTP,
SOCKS5,
SNELL,
};
}
export default createTestCases();
+332
View File
@@ -0,0 +1,332 @@
import { Base64 } from 'js-base64';
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { UUID, parseOne, expectSubset } from './helpers';
describe('Proxy URI parser coverage', function () {
describe('generic URIs', function () {
it('parses HTTPS URIs with implicit default port', function () {
const proxy = parseOne(
'https://alice:pa%24%24@https.example.com#HTTPS%20Default',
);
expectSubset(proxy, {
type: 'http',
name: 'HTTPS Default',
server: 'https.example.com',
port: 443,
tls: true,
username: 'alice',
password: 'pa$$',
});
});
it('parses legacy socks:// URIs with base64 auth', function () {
const proxy = parseOne(
`socks://${encodeURIComponent(
Base64.encode('bob:secret'),
)}@socks.example.com:1080#SOCKS`,
);
expectSubset(proxy, {
type: 'socks5',
name: 'SOCKS',
server: 'socks.example.com',
port: 1080,
username: 'bob',
password: 'secret',
});
});
});
describe('shadowsocks family', function () {
it('parses SIP002 shadowsocks URIs with obfs and transport flags', function () {
const userInfo = encodeURIComponent(
Base64.encode('aes-128-gcm:secret'),
);
const plugin = encodeURIComponent(
'obfs-local;obfs=http;obfs-host=obfs.example.com',
);
const proxy = parseOne(
`ss://${userInfo}@ss.example.com:8388/?plugin=${plugin}&uot=1&tfo=1#SS%20Obfs`,
);
expectSubset(proxy, {
type: 'ss',
name: 'SS Obfs',
server: 'ss.example.com',
port: 8388,
cipher: 'aes-128-gcm',
password: 'secret',
plugin: 'obfs',
'plugin-opts': {
mode: 'http',
host: 'obfs.example.com',
},
'udp-over-tcp': true,
tfo: true,
});
});
it('parses legacy shadowsocks URIs with v2ray-plugin options', function () {
const legacy = Base64.encode(
'chacha20-ietf-poly1305:legacy-pass@legacy.example.com:443',
);
const plugin = encodeURIComponent(
'v2ray-plugin;tls;host=cdn.example.com;path=/socket',
);
const proxy = parseOne(
`ss://${legacy}?plugin=${plugin}#SS%20V2ray`,
);
expectSubset(proxy, {
type: 'ss',
name: 'SS V2ray',
server: 'legacy.example.com',
port: 443,
cipher: 'chacha20-ietf-poly1305',
password: 'legacy-pass',
plugin: 'v2ray-plugin',
'plugin-opts': {
mode: 'websocket',
host: 'cdn.example.com',
path: '/socket',
tls: true,
},
});
});
it('parses shadowsocks shadow-tls compatibility payloads', function () {
const userInfo = Base64.encode('aes-256-gcm:shadow-pass');
const payload = Base64.encode(
JSON.stringify({
host: 'mask.example.com',
password: 'tls-pass',
version: '3',
address: '1.1.1.1',
port: '9443',
}),
);
const proxy = parseOne(
`ss://${userInfo}@ss.example.com:8388?shadow-tls=${payload}#SS%20ShadowTLS`,
);
expectSubset(proxy, {
type: 'ss',
name: 'SS ShadowTLS',
server: '1.1.1.1',
port: 9443,
cipher: 'aes-256-gcm',
password: 'shadow-pass',
plugin: 'shadow-tls',
'plugin-opts': {
host: 'mask.example.com',
password: 'tls-pass',
version: 3,
},
});
});
it('parses SSR URIs with protocol and obfs parameters', function () {
const encoded = Base64.encode(
[
'ssr.example.com:8899:origin:aes-256-cfb:http_simple:',
Base64.encode('ssr-secret'),
'/?remarks=',
Base64.encode('SSR Node'),
'&obfsparam=',
Base64.encode('cdn.example.com'),
'&protoparam=',
Base64.encode('user:pass'),
].join(''),
);
const proxy = parseOne(`ssr://${encoded}`);
expectSubset(proxy, {
type: 'ssr',
name: 'SSR Node',
server: 'ssr.example.com',
port: 8899,
protocol: 'origin',
cipher: 'aes-256-cfb',
obfs: 'http_simple',
password: 'ssr-secret',
'protocol-param': 'user:pass',
'obfs-param': 'cdn.example.com',
});
});
});
describe('other modern URI formats', function () {
it('parses AnyTLS URIs and drops plain tcp transport metadata', function () {
const proxy = parseOne(
'anytls://top-secret@anytls.example.com:443?type=tcp&alpn=h2,http/1.1&insecure=1&udp=1#AnyTLS',
);
expectSubset(proxy, {
type: 'anytls',
name: 'AnyTLS',
server: 'anytls.example.com',
port: 443,
password: 'top-secret',
tls: true,
sni: 'anytls.example.com',
alpn: ['h2', 'http/1.1'],
udp: true,
'skip-cert-verify': true,
});
expect(proxy.network).to.equal(undefined);
});
it('parses Hysteria URIs with fallback SNI and throughput fields', function () {
const proxy = parseOne(
'hy://hysteria.example.com:8443?auth=token&peer=sni.example.com&alpn=h3,h2&mport=2000,3000&obfsParam=mask&upmbps=10&downmbps=20&insecure=1#Hysteria',
);
expectSubset(proxy, {
type: 'hysteria',
name: 'Hysteria',
server: 'hysteria.example.com',
port: 8443,
protocol: 'udp',
'auth-str': 'token',
sni: 'sni.example.com',
alpn: ['h3', 'h2'],
ports: '2000,3000',
obfs: 'mask',
up: '10',
down: '20',
'skip-cert-verify': true,
});
});
it('parses Hysteria2 URIs with port hopping ranges', function () {
const proxy = parseOne(
'hy2://hy2-secret@hy2.example.com:8443-8445?peer=peer.example.com&obfs=salamander&obfs-password=mask&insecure=1&fastopen=1&pinSHA256=fingerprint&hop-interval=30&keepalive=15#Hy2%20Range',
);
expectSubset(proxy, {
type: 'hysteria2',
name: 'Hy2 Range',
server: 'hy2.example.com',
ports: '8443-8445',
password: 'hy2-secret',
sni: 'peer.example.com',
obfs: 'salamander',
'obfs-password': 'mask',
'skip-cert-verify': true,
tfo: true,
'tls-fingerprint': 'fingerprint',
'hop-interval': 30,
keepalive: 15,
});
expect(proxy.port).to.be.within(8443, 8445);
});
it('parses Hysteria2 URIs with mport overrides', function () {
const proxy = parseOne(
'hy2://hy2-secret@hy2.example.com:443?mport=9000,9002-9004#Hy2%20Mport',
);
expectSubset(proxy, {
type: 'hysteria2',
name: 'Hy2 Mport',
server: 'hy2.example.com',
port: 443,
ports: '9000,9002-9004',
password: 'hy2-secret',
});
});
it('parses TUIC URIs with colon-containing passwords and booleans', function () {
const proxy = parseOne(
`tuic://${UUID}:pass%3Aword@tuic.example.com?alpn=h3,hq-29&allow-insecure=1&fast-open=1&disable-sni=1&reduce-rtt=1&congestion-control=bbr#TUIC`,
);
expectSubset(proxy, {
type: 'tuic',
name: 'TUIC',
server: 'tuic.example.com',
port: 443,
uuid: UUID,
password: 'pass:word',
alpn: ['h3', 'hq-29'],
'skip-cert-verify': true,
tfo: true,
'disable-sni': true,
'reduce-rtt': true,
'congestion-controller': 'bbr',
});
});
it('parses WireGuard URIs with address lists and reserved bytes', function () {
const proxy = parseOne(
'wg://private-key@wg.example.com?publickey=public-key&privatekey=override-key&address=10.0.0.2/32,[fd00::2]/128&reserved=1,2,3&mtu=1280&udp=0#WG',
);
expectSubset(proxy, {
type: 'wireguard',
name: 'WG',
server: 'wg.example.com',
port: 51820,
'private-key': 'override-key',
'public-key': 'public-key',
ip: '10.0.0.2',
ipv6: 'fd00::2',
reserved: [1, 2, 3],
mtu: 1280,
udp: false,
});
});
it('parses Trojan URIs with websocket transport', function () {
const proxy = parseOne(
'trojan://trojan-pass@trojan-ws.example.com?type=ws&host=ws.example.com&path=%2Fws#Trojan%20WS',
);
expectSubset(proxy, {
type: 'trojan',
name: 'Trojan WS',
server: 'trojan-ws.example.com',
port: 443,
password: 'trojan-pass',
network: 'ws',
'ws-opts': {
path: '/ws',
headers: {
Host: 'ws.example.com',
},
},
});
});
it('parses Trojan URIs with grpc reality metadata', function () {
const proxy = parseOne(
'trojan://trojan-pass@trojan-grpc.example.com?type=grpc&serviceName=grpc-service&authority=grpc.example.com&mode=multi&security=reality&pbk=pubkey&sid=08&spx=%2Fspider&udp=1&tfo=1#Trojan%20Reality',
);
expectSubset(proxy, {
type: 'trojan',
name: 'Trojan Reality',
server: 'trojan-grpc.example.com',
port: 443,
password: 'trojan-pass',
network: 'grpc',
udp: true,
tfo: true,
'grpc-opts': {
'grpc-service-name': 'grpc-service',
'_grpc-type': 'multi',
'_grpc-authority': 'grpc.example.com',
},
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
'_spider-x': '/spider',
},
_mode: 'multi',
});
});
});
});
File diff suppressed because it is too large. Load diff
@@ -1,39 +0,0 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { normalizeClashYaml } from '@/core/proxy-utils/preprocessors';
describe('Clash preprocessor helper', function () {
it('quotes reality short-id scalars that may be re-parsed as numbers', function () {
const input = `proxies:
- name: test-1
type: vless
reality-opts:
short-id: 08
- name: test-2
type: vless
reality-opts:
short-id: 0088
- name: test-3
type: vless
reality-opts:
short-id: '51'
- name: test-4
type: vless
reality-opts:
short-id: ""
- name: test-5
type: vless
reality-opts:
short-id: null
`;
const output = normalizeClashYaml(input);
expect(output).to.include('short-id: "08"');
expect(output).to.include('short-id: "0088"');
expect(output).to.include("short-id: '51'");
expect(output).to.include('short-id: ""');
expect(output).to.include('short-id: null');
});
});
@@ -0,0 +1,203 @@
import { expect } from 'chai';
import { Base64 } from 'js-base64';
import { describe, it } from 'mocha';
import PREPROCESSORS, {
normalizeClashYaml,
} from '@/core/proxy-utils/preprocessors';
function getPreprocessor(name) {
const processor = PREPROCESSORS.find((item) => item.name === name);
expect(processor, name).to.exist;
return processor;
}
describe('Proxy preprocessors', function () {
describe('normalizeClashYaml', function () {
it('quotes reality short-id scalars that may be re-parsed as numbers', function () {
const input = `proxies:
- name: test-1
type: vless
reality-opts:
short-id: 08
- name: test-2
type: vless
reality-opts:
short-id: 0088
- name: test-3
type: vless
reality-opts:
short-id: '51'
- name: test-4
type: vless
reality-opts:
short-id: ""
- name: test-5
type: vless
reality-opts:
short-id: null
`;
const output = normalizeClashYaml(input);
expect(output).to.include('short-id: "08"');
expect(output).to.include('short-id: "0088"');
expect(output).to.include("short-id: '51'");
expect(output).to.include('short-id: ""');
expect(output).to.include('short-id: null');
});
it('keeps non-clash or invalid yaml input untouched', function () {
const invalid = 'proxies:\n - name: broken\n short-id: [';
const unrelated = 'ss://YWVzLTEyOC1nY206c2VjcmV0@example.com:8388';
expect(normalizeClashYaml(invalid)).to.equal(invalid);
expect(normalizeClashYaml(unrelated)).to.equal(unrelated);
});
});
describe('HTML preprocessor', function () {
it('detects html payloads and discards them', function () {
const processor = getPreprocessor('HTML');
const raw = '<!DOCTYPE html><html><body>blocked</body></html>';
expect(processor.test(raw)).to.equal(true);
expect(processor.parse(raw)).to.equal('');
});
});
describe('Base64 preprocessor', function () {
it('decodes base64 subscriptions that expand to proxy lines', function () {
const processor = getPreprocessor('Base64 Pre-processor');
const decoded =
'ss://YWVzLTEyOC1nY206c2VjcmV0@example.com:8388#Node\n' +
'trojan://secret@example.com:443#Trojan';
const encoded = Base64.encode(decoded);
expect(processor.test(encoded)).to.equal(true);
expect(processor.parse(encoded)).to.equal(decoded);
});
it('ignores already decoded proxy payloads', function () {
const processor = getPreprocessor('Base64 Pre-processor');
const raw = 'ss://YWVzLTEyOC1nY206c2VjcmV0@example.com:8388#Node';
expect(processor.test(raw)).to.equal(false);
});
});
describe('Fallback Base64 preprocessor', function () {
it('decodes valid fallback payloads and preserves invalid ones', function () {
const processor = getPreprocessor('Fallback Base64 Pre-processor');
const decoded = 'vmess://dGVzdA==';
const encoded = Base64.encode(decoded);
const invalid = 'not-base64-and-not-a-proxy';
expect(processor.test(invalid)).to.equal(true);
expect(processor.parse(encoded)).to.equal(decoded);
expect(processor.parse(invalid)).to.equal(invalid);
});
});
describe('Clash preprocessor', function () {
it('converts clash yaml proxies into json lines', function () {
const processor = getPreprocessor('Clash Pre-processor');
const raw = `proxies:
- name: Clash SS
type: ss
server: ss.example.com
port: 8388
cipher: aes-128-gcm
password: secret
- name: Clash VLESS
type: vless
server: vless.example.com
port: 443
uuid: 11111111-1111-4111-8111-111111111111
reality-opts:
short-id: 08
`;
expect(processor.test(raw)).to.equal(true);
const output = processor.parse(raw);
const wrapped = processor.parse(raw, true);
expect(output).to.include('"name":"Clash SS"');
expect(output).to.include('"name":"Clash VLESS"');
expect(output).to.include('"short-id":"08"');
expect(wrapped).to.match(/^proxies:\n - /);
});
});
describe('SSD preprocessor', function () {
it('expands SSD documents into ss uris with inherited and overridden fields', function () {
const processor = getPreprocessor('SSD Pre-processor');
const raw = `ssd://${Base64.encode(
JSON.stringify({
airport: 'Test SSD',
port: 8388,
encryption: 'aes-128-gcm',
password: 'base-secret',
servers: [
{
server: 'ssd1.example.com',
remarks: 'SSD 1',
},
{
server: 'ssd2.example.com',
port: 443,
encryption: 'chacha20-ietf-poly1305',
password: 'override-secret',
remarks: 'SSD 2',
plugin: 'v2ray-plugin',
plugin_options: 'host=cdn.example.com;path=/ws;tls',
},
],
}),
)}`;
expect(processor.test(raw)).to.equal(true);
const output = processor.parse(raw).split('\n');
expect(output).to.have.length(2);
expect(output[0]).to.equal(
`ss://${Base64.encode(
'aes-128-gcm:base-secret',
)}@ssd1.example.com:8388#SSD 1`,
);
expect(output[1]).to.equal(
`ss://${Base64.encode(
'chacha20-ietf-poly1305:override-secret',
)}@ssd2.example.com:443/?plugin=${encodeURIComponent(
'v2ray-plugin;host=cdn.example.com;path=/ws;tls',
)}#SSD 2`,
);
});
});
describe('Full config preprocessor', function () {
it('extracts the [Proxy] block from full config payloads', function () {
const processor = getPreprocessor('Full Config Preprocessor');
const raw = `[General]
skip-proxy = 192.168.0.0/16
[Proxy]
Node 1 = ss,example.com,8388,encrypt-method=aes-128-gcm,password=secret
Node 2 = trojan,example.com,443,password=secret
[Rule]
FINAL,DIRECT
`;
expect(processor.test(raw)).to.equal(true);
expect(processor.parse(raw).trim()).to.equal(
[
'Node 1 = ss,example.com,8388,encrypt-method=aes-128-gcm,password=secret',
'Node 2 = trojan,example.com,443,password=secret',
].join('\n'),
);
});
});
});
@@ -0,0 +1,54 @@
import { expect } from 'chai';
import { ProxyUtils } from '@/core/proxy-utils';
import { safeLoad } from '@/utils/yaml';
export const UUID = '11111111-1111-4111-8111-111111111111';
export function clone(value) {
return JSON.parse(JSON.stringify(value));
}
function asList(proxies) {
return Array.isArray(proxies) ? proxies : [proxies];
}
export function produceInternal(platform, proxies, opts = {}) {
return ProxyUtils.produce(clone(asList(proxies)), platform, 'internal', opts);
}
export function produceExternal(platform, proxies, opts = {}) {
const output = ProxyUtils.produce(
clone(asList(proxies)),
platform,
'external',
opts,
);
expect(output, platform).to.be.a('string').and.not.equal('');
return output;
}
export function loadProducedYaml(platform, proxies, opts = {}) {
return safeLoad(produceExternal(platform, proxies, opts));
}
export function loadProducedJson(platform, proxies, opts = {}) {
return JSON.parse(produceExternal(platform, proxies, opts));
}
export function expectSubset(actual, expected, path = 'value') {
if (Array.isArray(expected)) {
expect(actual, path).to.deep.equal(expected);
return;
}
if (expected && typeof expected === 'object') {
expect(actual, path).to.be.an('object');
for (const [key, value] of Object.entries(expected)) {
expectSubset(actual[key], value, `${path}.${key}`);
}
return;
}
expect(actual, path).to.deep.equal(expected);
}
@@ -0,0 +1,324 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';
import {
UUID,
expectSubset,
loadProducedJson,
loadProducedYaml,
produceInternal,
} from './helpers';
describe('Proxy structured producers', function () {
it('filters unsupported Clash proxies by default and normalizes vmess ws early data', function () {
const proxies = [
{
type: 'vmess',
name: 'Clash VMess',
server: 'vmess.example.com',
port: 443,
uuid: UUID,
cipher: 'chacha20',
aead: true,
tls: true,
sni: 'sni.example.com',
network: 'ws',
'ws-opts': {
path: '/ws?ed=2048',
headers: {
Host: 'cdn.example.com',
},
},
},
{
type: 'vless',
name: 'Clash Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
flow: 'xtls-rprx-vision',
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
},
];
const internal = produceInternal('Clash', proxies);
const external = loadProducedYaml('Clash', proxies);
expect(internal).to.have.length(1);
expect(external.proxies).to.have.length(1);
expectSubset(internal[0], {
type: 'vmess',
name: 'Clash VMess',
cipher: 'auto',
alterId: 0,
servername: 'sni.example.com',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
'early-data-header-name': 'Sec-WebSocket-Protocol',
'max-early-data': 2048,
},
});
});
it('keeps unsupported Clash proxies when include-unsupported-proxy is enabled', function () {
const internal = produceInternal(
'Clash',
{
type: 'vless',
name: 'Clash Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
flow: 'xtls-rprx-vision',
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
},
{ 'include-unsupported-proxy': true },
);
expect(internal).to.have.length(1);
expectSubset(internal[0], {
type: 'vless',
name: 'Clash Reality',
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
});
});
it('adds Clash.Meta reality defaults and preserves websocket early data', function () {
const proxy = {
type: 'vless',
name: 'Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
flow: 'xtls-rprx-vision',
network: 'ws',
'ws-opts': {
path: '/ws?ed=2048',
headers: {
Host: 'cdn.example.com',
},
},
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
};
const internal = produceInternal('ClashMeta', proxy)[0];
const external = loadProducedYaml('ClashMeta', proxy);
expectSubset(internal, {
type: 'vless',
name: 'Reality',
'client-fingerprint': 'chrome',
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
'ws-opts': {
path: '/ws',
'early-data-header-name': 'Sec-WebSocket-Protocol',
'max-early-data': 2048,
},
});
expectSubset(external.proxies[0], {
type: 'vless',
name: 'Reality',
'client-fingerprint': 'chrome',
});
});
it('normalizes Stash TUIC defaults and external yaml wrapper', function () {
const proxy = {
type: 'tuic',
name: 'TUIC',
server: 'tuic.example.com',
port: 443,
uuid: UUID,
password: 'secret',
tfo: true,
};
const internal = produceInternal('Stash', proxy)[0];
const external = loadProducedYaml('Stash', proxy);
expectSubset(internal, {
type: 'tuic',
name: 'TUIC',
alpn: ['h3'],
'fast-open': true,
version: 5,
});
expectSubset(external.proxies[0], {
type: 'tuic',
name: 'TUIC',
alpn: ['h3'],
'fast-open': true,
version: 5,
});
});
it('promotes shadow-tls fields for Shadowrocket', function () {
const proxy = {
type: 'ss',
name: 'ShadowTLS SS',
server: 'ss.example.com',
port: 8388,
cipher: 'aes-128-gcm',
password: 'secret',
'shadow-tls-password': 'shadow-pass',
'shadow-tls-sni': 'mask.example.com',
'shadow-tls-version': 3,
'skip-cert-verify': true,
};
const internal = produceInternal('Shadowrocket', proxy)[0];
const external = loadProducedYaml('Shadowrocket', proxy);
expectSubset(internal, {
type: 'ss',
name: 'ShadowTLS SS',
plugin: 'shadow-tls',
'plugin-opts': {
host: 'mask.example.com',
password: 'shadow-pass',
version: 3,
},
});
expectSubset(external.proxies[0], {
type: 'ss',
plugin: 'shadow-tls',
});
});
it('maps shadowsocks shadow-tls fields into Egern nested structures', function () {
const proxy = {
type: 'ss',
name: 'ShadowTLS SS',
server: 'ss.example.com',
port: 8388,
cipher: 'aes-128-gcm',
password: 'secret',
'shadow-tls-password': 'shadow-pass',
'shadow-tls-sni': 'mask.example.com',
'shadow-tls-version': 3,
};
const internal = produceInternal('Egern', proxy)[0];
const external = loadProducedYaml('Egern', proxy);
expectSubset(internal, {
shadowsocks: {
name: 'ShadowTLS SS',
method: 'aes-128-gcm',
server: 'ss.example.com',
port: 8388,
password: 'secret',
shadow_tls: {
password: 'shadow-pass',
sni: 'mask.example.com',
},
},
});
expectSubset(external.proxies[0], {
shadowsocks: {
name: 'ShadowTLS SS',
},
});
});
it('emits sing-box outbounds with reality tls and websocket transport', function () {
const output = loadProducedJson('sing-box', {
type: 'vless',
name: 'Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
flow: 'xtls-rprx-vision',
network: 'ws',
'ws-opts': {
path: '/ws?ed=2048',
headers: {
Host: 'cdn.example.com',
},
},
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
});
expect(output.outbounds).to.have.length(1);
expect(output.endpoints).to.have.length(0);
expectSubset(output.outbounds[0], {
tag: 'Reality',
type: 'vless',
server: 'vless.example.com',
server_port: 443,
flow: 'xtls-rprx-vision',
tls: {
enabled: true,
server_name: 'vless.example.com',
reality: {
enabled: true,
public_key: 'pubkey',
short_id: '08',
},
utls: {
enabled: true,
fingerprint: 'chrome',
},
},
transport: {
type: 'ws',
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
early_data_header_name: 'Sec-WebSocket-Protocol',
max_early_data: 2048,
},
});
});
it('stringifies JSON producer outputs as plain arrays', function () {
const proxy = {
type: 'http',
name: 'JSON HTTP',
server: 'http.example.com',
port: 8080,
username: 'user',
password: 'pass',
};
const internal = produceInternal('JSON', proxy);
const external = loadProducedJson('JSON', proxy);
expect(internal).to.have.length(1);
expectSubset(internal[0], {
type: 'http',
name: 'JSON HTTP',
});
expect(external).to.have.length(1);
expectSubset(external[0], {
type: 'http',
name: 'JSON HTTP',
});
});
});
@@ -0,0 +1,241 @@
import { expect } from 'chai';
import { Base64 } from 'js-base64';
import { describe, it } from 'mocha';
import { produceExternal, UUID } from './helpers';
describe('Proxy text producers', function () {
it('produces Quantumult X VLESS reality websocket lines', function () {
const output = produceExternal('QX', {
type: 'vless',
name: 'QX Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
sni: 'sni.example.com',
flow: 'xtls-rprx-vision',
network: 'ws',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
},
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
});
expect(output).to.equal(
`vless=vless.example.com:443,method=none,password=${UUID},obfs=wss,obfs-uri=/ws,obfs-host=cdn.example.com,tls-host=sni.example.com,vless-flow=xtls-rprx-vision,tag=QX Reality,reality-base64-pubkey=pubkey,reality-hex-shortid=08`,
);
});
it('produces Loon VLESS reality websocket lines', function () {
const output = produceExternal('Loon', {
type: 'vless',
name: 'Loon Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
sni: 'sni.example.com',
flow: 'xtls-rprx-vision',
network: 'ws',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
},
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
'skip-cert-verify': true,
});
expect(output).to.equal(
`Loon Reality=vless,vless.example.com,443,"${UUID}",transport=ws,path=/ws,host=cdn.example.com,over-tls=true,skip-cert-verify=true,flow=xtls-rprx-vision,sni=sni.example.com,public-key="pubkey",short-id=08`,
);
});
it('produces Loon AnyTLS lines and keeps only supported fields', function () {
const output = produceExternal('Loon', {
type: 'anytls',
name: 'Loon AnyTLS',
server: 'anytls.example.com',
port: 443,
password: 'secret',
tls: true,
sni: 'sni.example.com',
network: 'ws',
'ws-opts': {
path: '/anytls',
headers: {
Host: 'cdn.example.com',
},
},
'skip-cert-verify': true,
'idle-session-timeout': 30,
'max-stream-count': 16,
});
expect(output).to.equal(
'Loon AnyTLS=anytls,anytls.example.com,443,"secret",idle-session-timeout=30,max-stream-count=16,skip-cert-verify=true,tls-name=sni.example.com',
);
});
it('produces Surge TUIC v5 lines with port hopping', function () {
const output = produceExternal('Surge', {
type: 'tuic',
name: 'Surge TUIC',
server: 'tuic.example.com',
port: 443,
uuid: UUID,
password: 'secret',
ports: '9000,9002-9004',
sni: 'sni.example.com',
'skip-cert-verify': true,
alpn: ['h3'],
ecn: true,
});
expect(output).to.equal(
`Surge TUIC=tuic-v5,tuic.example.com,443,uuid=${UUID},password="secret",alpn=h3,port-hopping="9000;9002-9004",sni="sni.example.com",skip-cert-verify=true,ecn=true`,
);
});
it('produces Surfboard trojan websocket lines', function () {
const output = produceExternal('Surfboard', {
type: 'trojan',
name: 'Trojan',
server: 'trojan.example.com',
port: 443,
password: 'secret',
network: 'ws',
tls: true,
sni: 'sni.example.com',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
},
});
expect(output).to.equal(
'Trojan=trojan,trojan.example.com,443,password=secret,ws=true,ws-path=/ws,ws-headers=Host:"cdn.example.com",tls=true,sni="sni.example.com"',
);
});
it('produces SurgeMac external lines', function () {
const output = produceExternal('SurgeMac', {
type: 'external',
name: 'External',
exec: '/usr/bin/ssh',
'local-port': 1080,
args: ['-D', 'localhost:1080'],
addresses: ['1.1.1.1', '2001:db8::1'],
udp: true,
tfo: true,
'test-url': 'https://test.example.com',
'block-quic': 'on',
});
expect(output).to.equal(
'External=external,exec="/usr/bin/ssh",local-port=1080,args="-D",args="localhost:1080",addresses=1.1.1.1,addresses=2001:db8::1,udp-relay=true,tfo=true,test-url=https://test.example.com,block-quic=on',
);
});
it('wraps unsupported SurgeMac protocols with Mihomo external mode when requested', function () {
const output = produceExternal(
'SurgeMac',
{
type: 'vless',
name: 'Mihomo VLESS',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
network: 'ws',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
},
},
{ useMihomoExternal: true, localPort: 16666 },
);
expect(output).to.include(
'Mihomo VLESS=external,exec="/usr/local/bin/mihomo",local-port=16666',
);
expect(output).to.include('args="-config"');
expect(output).to.include('udp-relay=true');
});
it('produces URI VLESS reality websocket links', function () {
const output = produceExternal('URI', {
type: 'vless',
name: 'URI Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
sni: 'sni.example.com',
flow: 'xtls-rprx-vision',
network: 'ws',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
'max-early-data': 2048,
'early-data-header-name': 'Sec-WebSocket-Protocol',
},
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
'_spider-x': '/spider',
},
'client-fingerprint': 'chrome',
alpn: ['h2'],
});
expect(output).to.equal(
`vless://${UUID}@vless.example.com:443?security=reality&type=ws&path=%2Fws&host=cdn.example.com&alpn=h2&sni=sni.example.com&fp=chrome&flow=xtls-rprx-vision&sid=08&spx=%2Fspider&pbk=pubkey#URI%20Reality`,
);
});
it('produces V2Ray exports as base64 encoded URI lists', function () {
const output = produceExternal('V2Ray', {
type: 'vless',
name: 'URI Reality',
server: 'vless.example.com',
port: 443,
uuid: UUID,
tls: true,
sni: 'sni.example.com',
flow: 'xtls-rprx-vision',
network: 'ws',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
},
},
'reality-opts': {
'public-key': 'pubkey',
'short-id': '08',
},
});
expect(Base64.decode(output)).to.equal(
`vless://${UUID}@vless.example.com:443?security=reality&type=ws&path=%2Fws&host=cdn.example.com&sni=sni.example.com&flow=xtls-rprx-vision&sid=08&pbk=pubkey#URI%20Reality`,
);
});
});