feat: Surge 节点参数逻辑优化
build / build (push) Waiting to run

This commit is contained in:
xream committed 2026-11-26 23:49:05 +08:00
1 parent 19574cee50
commit d0bf093c18
6 files changed
+589 -886

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.44.30",
"version": "2.44.31",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"packageManager": "pnpm@11.0.9",
+10 -96
View File
@@ -37,19 +37,6 @@ import {
} from '../ech-utils';
import { normalizeVmessSecurity } from '../vmess-security';
function surge_port_hopping(raw) {
const [parts, port_hopping] =
raw.match(
/,\s*?port-hopping\s*?=\s*?["']?\s*?((\d+(-\d+)?)([,;]\d+(-\d+)?)*)\s*?["']?\s*?/,
) || [];
return {
port_hopping: port_hopping
? port_hopping.replace(/;/g, ',')
: undefined,
line: parts ? raw.replace(parts, '') : raw,
};
}
function splitURIFragment(raw) {
const [__, content, fragment] = /^(.*?)(?:#(.*?))?$/.exec(raw);
return {
@@ -2588,6 +2575,8 @@ function URI_WireGuard() {
proxy['public-key'] = value;
} else if (/privatekey/i.test(key)) {
proxy['private-key'] = value;
} else if (/^presharedkey$/i.test(key)) {
proxy['preshared-key'] = value;
} else if (['udp'].includes(key)) {
proxy[key] = /(TRUE)|1/i.test(value);
} else if (![...Object.keys(proxy), 'flag'].includes(key)) {
@@ -3034,9 +3023,7 @@ function Loon_WireGuard() {
function Surge_Direct() {
const name = 'Surge Direct Parser';
const test = (line) => {
return /^.*=\s*direct/.test(line.split(',')[0]);
};
const test = (line) => /^[^=,]*=\s*direct\s*$/i.test(line.split(',')[0]);
const parse = (line) => getSurgeParser().parse(line);
return { name, test, parse };
}
@@ -3061,12 +3048,7 @@ function Surge_Masque() {
const test = (line) => {
return /^.*=\s*masque/.test(line.split(',')[0]);
};
const parse = (raw) => {
const { port_hopping, line } = surge_port_hopping(raw);
const proxy = getSurgeParser().parse(line);
proxy.ports = port_hopping;
return proxy;
};
const parse = (line) => getSurgeParser().parse(line);
return { name, test, parse };
}
function Surge_H2Connect() {
@@ -3161,68 +3143,10 @@ function Surge_External() {
return /^.*=\s*external/.test(line.split(',')[0]);
};
const parse = (line) => {
let parsed = /^\s*(.*?)\s*?=\s*?external\s*?,\s*(.*?)\s*$/.exec(line);
// eslint-disable-next-line no-unused-vars
let [_, name, other] = parsed;
line = other;
// exec = "/usr/bin/ssh" 或 exec = /usr/bin/ssh
let exec = /(,|^)\s*?exec\s*?=\s*"(.*?)"\s*?(,|$)/.exec(line)?.[2];
if (!exec) {
exec = /(,|^)\s*?exec\s*?=\s*(.*?)\s*?(,|$)/.exec(line)?.[2];
}
// local-port = "1080" 或 local-port = 1080
let localPort = /(,|^)\s*?local-port\s*?=\s*"(.*?)"\s*?(,|$)/.exec(
line,
)?.[2];
if (!localPort) {
localPort = /(,|^)\s*?local-port\s*?=\s*(.*?)\s*?(,|$)/.exec(
line,
)?.[2];
}
// args = "-m", args = "rc4-md5"
// args = -m, args = rc4-md5
const argsRegex = /(,|^)\s*?args\s*?=\s*("(.*?)"|(.*?))(?=\s*?(,|$))/g;
let argsMatch;
const args = [];
while ((argsMatch = argsRegex.exec(line)) !== null) {
if (argsMatch[3] != null) {
args.push(argsMatch[3]);
} else if (argsMatch[4] != null) {
args.push(argsMatch[4]);
}
}
// addresses = "[ipv6]",,addresses = "ipv6", addresses = "ipv4"
// addresses = [ipv6], addresses = ipv6, addresses = ipv4
const addressesRegex =
/(,|^)\s*?addresses\s*?=\s*("(.*?)"|(.*?))(?=\s*?(,|$))/g;
let addressesMatch;
const addresses = [];
while ((addressesMatch = addressesRegex.exec(line)) !== null) {
let ip;
if (addressesMatch[3] != null) {
ip = addressesMatch[3];
} else if (addressesMatch[4] != null) {
ip = addressesMatch[4];
}
if (ip != null) {
ip = `${ip}`.trim().replace(/^\[/, '').replace(/\]$/, '');
}
if (isIP(ip)) {
addresses.push(ip);
}
}
const proxy = {
type: 'external',
name,
exec,
'local-port': localPort,
args,
addresses,
};
const proxy = getSurgeParser().parse(line);
proxy.addresses = proxy.addresses
.map((ip) => ip.trim().replace(/^\[/, '').replace(/\]$/, ''))
.filter(isIP);
return proxy;
};
return { name, test, parse };
@@ -3248,12 +3172,7 @@ function Surge_Tuic() {
const test = (line) => {
return /^.*=\s*tuic(-v5)?/.test(line.split(',')[0]);
};
const parse = (raw) => {
const { port_hopping, line } = surge_port_hopping(raw);
const proxy = getSurgeParser().parse(line);
proxy['ports'] = port_hopping;
return proxy;
};
const parse = (line) => getSurgeParser().parse(line);
return { name, test, parse };
}
function Surge_WireGuard() {
@@ -3270,12 +3189,7 @@ function Surge_Hysteria2() {
const test = (line) => {
return /^.*=\s*hysteria2/.test(line.split(',')[0]);
};
const parse = (raw) => {
const { port_hopping, line } = surge_port_hopping(raw);
const proxy = getSurgeParser().parse(line);
proxy['ports'] = port_hopping;
return proxy;
};
const parse = (line) => getSurgeParser().parse(line);
return { name, test, parse };
}
@@ -402,7 +402,7 @@ const grammars = String.raw`
}
}
start = (masque/anytls/shadowsocks/vmess/vless/trojan/h2_connect/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh/trust_tunnel/direct) {
start = (masque/anytls/shadowsocks/vmess/vless/trojan/h2_connect/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh/trust_tunnel/direct/external) {
if (
["auto", "none", "apple-26", "chromium-155"].includes(clientFingerprint) &&
proxy.network !== "h3" &&
@@ -424,7 +424,7 @@ start = (masque/anytls/shadowsocks/vmess/vless/trojan/h2_connect/https/http/snel
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/alpn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/ecn/udp_port/others)* {
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/udp_relay/alpn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/udp_port/proxy_policy_parameter/others)* {
proxy.type = "ss";
// handle obfs
if (obfs.type == "http" || obfs.type === "tls") {
@@ -435,7 +435,7 @@ shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/
}
handleShadowTLS();
}
vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_http_upgrade/ws_path/ws_headers/vmess_method/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/ecn/others)* {
vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_http_upgrade/ws_path/ws_headers/vmess_method/tls/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/others)* {
proxy.type = "vmess";
proxy.cipher = proxy.cipher || "auto";
// Surfboard 与 Surge 默认不一致, 不管 Surfboard https://getsurfboard.com/docs/profile-format/proxy/external-proxy/vmess
@@ -447,7 +447,7 @@ vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_http_upgrade/ws_
handleWebsocket();
handleShadowTLS();
}
vless = tag equals vless_address (vless_username/vless_option/reality_option/ws/ws_http_upgrade/ws_path/ws_headers/grpc/grpc_service_name/grpc_mode/grpc_authority/xhttp/xhttp_headers/xhttp_option/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/ecn/others)* {
vless = tag equals vless_address (vless_username/vless_option/reality_option/ws/ws_http_upgrade/ws_path/ws_headers/grpc/grpc_service_name/grpc_mode/grpc_authority/xhttp/xhttp_headers/xhttp_option/tls/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/others)* {
proxy["packet-encoding"] = "xudp";
if (proxy["reality-opts"] && proxy["reality-opts"]["public-key"]) proxy.tls = true;
if (xhttpEnabled) {
@@ -459,30 +459,30 @@ vless = tag equals vless_address (vless_username/vless_option/reality_option/ws/
handleShadowTLS();
}
vless_address = "vless" address { proxy.type = "vless"; }
trojan = tag equals "trojan" address (passwordk/ws/ws_http_upgrade/ws_path/ws_headers/tls/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/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/ecn/others)* {
trojan = tag equals "trojan" address (passwordk/ws/ws_http_upgrade/ws_path/ws_headers/tls/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/others)* {
proxy.type = "trojan";
handleWebsocket();
handleShadowTLS();
}
https = tag equals "https" address (username password)? (usernamek passwordk)? (headers/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/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/ecn/others)* {
https = tag equals "https" address (username password)? (usernamek passwordk)? (headers/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/others)* {
proxy.type = "http";
proxy.tls = true;
handleShadowTLS();
}
h2_connect = tag equals "h2-connect" address (username password)? (usernamek passwordk)? (headers/max_streams/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/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/ecn/others)* {
h2_connect = tag equals "h2-connect" address (username password)? (usernamek passwordk)? (headers/max_streams/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/others)* {
proxy.type = "h2-connect";
proxy.tls = true;
handleShadowTLS();
}
http = tag equals "http" address (username password)? (usernamek passwordk)? (headers/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/ecn/others)* {
http = tag equals "http" address (username password)? (usernamek passwordk)? (headers/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/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/ecn/others)* {
ssh = tag equals "ssh" address (username password)? (usernamek passwordk)? (server_fingerprint/idle_timeout/private_key/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/others)* {
proxy.type = "ssh";
handleShadowTLS();
}
snell = tag equals ("snell"i/"opensnell"i) address (snell_version/snell_mode/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/alpn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/ecn/others)* {
snell = tag equals ("snell"i/"opensnell"i) address (snell_version/snell_mode/snell_psk/obfs/obfs_host/obfs_uri/udp_relay/reuse/alpn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/others)* {
proxy.type = "snell";
// handle obfs
if (obfs.type == "http" || obfs.type === "tls") {
@@ -492,48 +492,71 @@ snell = tag equals ("snell"i/"opensnell"i) address (snell_version/snell_mode/sne
}
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/client_cert/ech_config/sni/cert_verify_name/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
tuic = tag equals "tuic" address (alpn/token/tls_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/shadow_tls_version/shadow_tls_sni/shadow_tls_password/port_hopping/port_hopping_interval/proxy_policy_parameter/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/client_cert/ech_config/sni/cert_verify_name/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
tuic_v5 = tag equals "tuic-v5" address (alpn/passwordk/uuidk/tls_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/shadow_tls_version/shadow_tls_sni/shadow_tls_password/port_hopping/port_hopping_interval/proxy_policy_parameter/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/ecn/others)* {
wireguard = tag equals "wireguard" (section_name/common_policy_parameter/proxy_only_parameter/ignored_policy_parameter)* {
if (!proxy["section-name"]) error("WireGuard requires section-name");
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/cert_verify_name/alpn/tls_verification/client_cert/ech_config/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/salamander_password/gecko_password/others)* {
hysteria2 = tag equals "hysteria2" address (sni/cert_verify_name/alpn/tls_verification/client_cert/ech_config/passwordk/tls_fingerprint/download_bandwidth/shadow_tls_version/shadow_tls_sni/shadow_tls_password/port_hopping/port_hopping_interval/salamander_password/gecko_password/proxy_policy_parameter/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/ecn/others)* {
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/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/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/ecn/others)* {
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (udp_relay/sni/cert_verify_name/alpn/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/shadow_tls_version/shadow_tls_sni/shadow_tls_password/proxy_policy_parameter/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/client_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/alpn/fast_open/tfo/block_quic/ecn/others)* {
anytls = tag equals "anytls" address (passwordk/reuse/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/alpn/proxy_policy_parameter/others)* {
proxy.type = "anytls";
proxy.tls = true;
}
trust_tunnel = tag equals "trust-tunnel" address (usernamek/passwordk/client_random_auth_key/headers/max_streams/reuse/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/alpn/h3/fast_open/tfo/block_quic/ecn/others)* {
trust_tunnel = tag equals "trust-tunnel" address (usernamek/passwordk/client_random_auth_key/headers/max_streams/reuse/tls_fingerprint/client_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/alpn/h3/proxy_policy_parameter/others)* {
proxy.type = "trusttunnel";
proxy.tls = true;
}
masque = tag equals "masque" address (usernamek/passwordk/port_hopping_interval/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/alpn/fast_open/tfo/udp_relay/ecn/block_quic/others)* {
masque = tag equals "masque" address (usernamek/passwordk/port_hopping/port_hopping_interval/tls_fingerprint/tls_verification/client_cert/ech_config/sni/cert_verify_name/alpn/udp_relay/proxy_policy_parameter/others)* {
proxy.type = "masque-surge";
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)* {
direct = tag equals "direct"i (common_policy_parameter/interface_parameter/udp_relay/ignored_policy_parameter)* {
proxy.type = "direct";
}
external = tag equals "external" (external_exec/external_local_port/external_arg/external_address/udp_relay/proxy_policy_parameter/ignored_policy_parameter)* {
proxy.type = "external";
proxy.args = proxy.args || [];
proxy.addresses = proxy.addresses || [];
}
external_exec = comma "exec" equals value:quoted_value { if (proxy.exec === undefined) proxy.exec = value; }
external_local_port = comma "local-port" equals value:quoted_value { if (proxy["local-port"] === undefined) proxy["local-port"] = value; }
external_arg = comma "args" equals value:quoted_value {
proxy.args = proxy.args || [];
proxy.args.push(value);
}
external_address = comma "addresses" equals value:quoted_value {
proxy.addresses = proxy.addresses || [];
proxy.addresses.push(value);
}
proxy_policy_parameter = common_policy_parameter / interface_parameter / proxy_only_parameter
common_policy_parameter = ip_version / hybrid / tfo / fast_open / tos / block_quic / test_url / test_timeout / test_udp
interface_parameter = interface / allow_other_interface / dns_follow_interface
proxy_only_parameter = no_error_alert / ecn / underlying_proxy
ignored_policy_parameter = comma [^=,]+ equals quoted_value
address = comma server:server comma port:port {
proxy.server = server;
proxy.port = port;
@@ -567,6 +590,13 @@ port = digits:[0-9]+ {
}
}
port_hopping = comma "port-hopping" equals value:(
'"' _ list:port_hopping_list _ '"' { return list; }
/ "'" _ list:port_hopping_list _ "'" { return list; }
/ port_hopping_list
) &(_ ("," / !.)) { proxy.ports = value.replace(/\s+/g, "").replace(/;/g, ","); }
port_hopping_list = $(port_hopping_range (_ [,;] _ port_hopping_range)*)
port_hopping_range = [0-9]+ ("-" [0-9]+)?
port_hopping_interval = comma "port-hopping-interval" equals match:$[0-9]+ { proxy["hop-interval"] = parseInt(match.trim()); }
username = & {
@@ -678,28 +708,41 @@ 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; }
fast_open = comma "fast-open" equals flag:policy_bool { proxy.tfo = flag; }
reuse = comma "reuse" equals flag:bool { proxy.reuse = flag; }
ecn = comma "ecn" equals mode:("auto" / "on" / "off" / bool) &(_ ("," / !.)) { proxy.ecn = mode; }
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 value:(vless_quoted_value / uri) { proxy["underlying-proxy"] = value; }
ecn = comma "ecn" equals mode:policy_toggle { if (mode !== undefined) proxy.ecn = mode; }
tfo = comma "tfo" equals flag:policy_bool { proxy.tfo = flag; }
ip_version = comma "ip-version" equals value:quoted_value { proxy["ip-version"] = value.trim(); }
section_name = comma "section-name" equals value:quoted_value { proxy["section-name"] = value.trim(); }
no_error_alert = comma "no-error-alert" equals value:quoted_value { proxy["no-error-alert"] = value.trim(); }
underlying_proxy = comma "underlying-proxy" equals value:quoted_value { proxy["underlying-proxy"] = value.trim(); }
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()); }
test_url = comma "test-url" equals value:quoted_value { proxy["test-url"] = value.trim(); }
test_udp = comma "test-udp" equals value:quoted_value { proxy["test-udp"] = value.trim(); }
test_timeout = comma "test-timeout" equals value:quoted_value {
const seconds = value.trim();
if (/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(seconds)) proxy["test-timeout"] = Number(seconds);
}
max_streams = comma "max-streams" equals match:quoted_integer { proxy["max-streams"] = match; }
quoted_integer = '"' match:$[0-9]+ '"' { return parseInt(match.trim()); } / "'" match:$[0-9]+ "'" { return parseInt(match.trim()); } / match:$[0-9]+ { return 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; }
tos = comma "tos" equals value:quoted_value {
const text = value.trim();
proxy.tos = /^(?:\d+|0x[\da-f]+)$/i.test(text) ? Number(text) : text;
}
interface = comma "interface" equals value:quoted_value { proxy.interface = value.trim(); }
allow_other_interface = comma "allow-other-interface" equals flag:policy_bool { proxy["allow-other-interface"] = flag; }
dns_follow_interface = comma "dns-follow-interface" equals flag:policy_bool { proxy["dns-follow-interface"] = flag; }
hybrid = comma "hybrid" equals mode:policy_toggle { if (mode !== undefined) proxy.hybrid = mode; }
policy_bool = value:quoted_value &{ return /^(?:true|false)$/.test(value.trim()); } { return value.trim() === "true"; }
policy_toggle = value:quoted_value {
const mode = value.trim();
if (mode === "true" || mode === "false") return mode === "true";
if (["auto", "on", "off"].includes(mode)) return mode;
}
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"] = stripQuotes(match.join("")); }
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(""); }
block_quic = comma "block-quic" equals value:quoted_value { proxy["block-quic"] = value.trim(); }
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]+ { shadowTLS.version = parseInt(match.trim()); }
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { shadowTLS.host = match.join(""); }
@@ -711,12 +754,11 @@ alpn = comma "alpn" equals match:quoted_value {
}
h3 = comma "h3" equals flag:bool { if (flag) proxy.network = "h3"; }
quoted_value
= double_quoted_vless_value
= '"' value:$(("\\" ('"' / "\\") / [^"])*) '"' &(_ ("," / !.)) { return proxy.type === "vless" ? unescapeQuotedValue(value) : value; }
/ '"' match:$[^"]* '"' { return match; }
/ "'" match:$[^']* "'" { return proxy.type === "vless" ? unescapeQuotedValue(match) : match; }
/ uri
/ value:uri { return value.trim(); }
vless_quoted_value = &{ return proxy.type === "vless"; } value:quoted_value { return value.trim(); }
double_quoted_vless_value = &{ return proxy.type === "vless"; } '"' value:$(("\\" ('"' / "\\") / [^"])*) '"' &(_ ("," / !.)) { return unescapeQuotedValue(value); }
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'; }
gecko_password = comma "gecko-password" equals match:[^,]+ { proxy['obfs-password'] = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); proxy.obfs = 'gecko'; }
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,9 @@
import { Base64 } from 'js-base64';
import { Result, isPresent } from './utils';
import Surge_Producer, { SurgeUnsupportedProxyError } from './surge';
import { Result } from './utils';
import Surge_Producer, {
appendSurgePolicyParameters,
SurgeUnsupportedProxyError,
} from './surge';
import ClashMeta_Producer from './clashmeta';
import { isIPv4, isIPv6 } from '@/utils';
import $ from '@/core/app';
@@ -70,27 +73,10 @@ function external(proxy) {
});
}
result.appendIfPresent(
`,no-error-alert=${proxy['no-error-alert']}`,
'no-error-alert',
);
// udp
result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp');
// tfo
if (isPresent(proxy, 'tfo')) {
result.append(`,tfo=${proxy['tfo']}`);
} else if (isPresent(proxy, 'fast-open')) {
result.append(`,tfo=${proxy['fast-open']}`);
}
// test-url
result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url');
// block-quic
result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic');
appendSurgePolicyParameters(result, proxy);
return result.toString();
}
// eslint-disable-next-line no-unused-vars
@@ -38,6 +38,128 @@ function captureErrors(fn) {
}
describe('Proxy text producers', function () {
it('round-trips documented Surge common policy parameters', function () {
const testUrl =
'https://check.example.com/status?list=one,port-hopping=3000';
const parameters = [
'interface = "en1"',
'allow-other-interface="false"',
'dns-follow-interface="true"',
'no-error-alert = false',
'ip-version = prefer-v6 ',
'hybrid="off"',
'tfo="false"',
'tos="0x88"',
'ecn="auto"',
'block-quic=adaptive',
`test-url="${testUrl}"`,
'test-timeout="0.75"',
'test-udp=check.example.com@192.0.2.53',
'underlying-proxy="Entry Group"',
].join(',');
const expected = {
'interface-name': 'en1',
'allow-other-interface': false,
'dns-follow-interface': true,
'no-error-alert': 'false',
'ip-version': 'prefer-v6',
hybrid: 'off',
tfo: false,
tos: 136,
ecn: 'auto',
'block-quic': 'adaptive',
'test-url': testUrl,
'test-timeout': 0.75,
'test-udp': 'check.example.com@192.0.2.53',
'underlying-proxy': 'Entry Group',
};
for (const policy of [
'ss,example.com,443,encrypt-method=aes-128-gcm,password=secret',
'socks5,example.com,1080',
'socks5-tls,example.com,443',
'h2-connect,example.com,443',
`vless,example.com,443,username=${UUID}`,
'hysteria2,example.com,443,password=secret',
'external,exec="/usr/bin/ssh",local-port=1080,args="-o",args="Option=a,b",args="say \\"test\\""',
]) {
const [proxy] = ProxyUtils.parse(`Proxy=${policy},${parameters}`);
expectSubset(proxy, expected, policy);
expect(proxy).to.not.have.property('ports');
const targets =
proxy.type === 'external'
? ['SurgeMac']
: ['Surge', 'SurgeMac'];
for (const target of targets) {
const output = produceExternal(target, proxy);
expect(output).to.include(`,test-url="${testUrl}"`);
const [roundTripped] = ProxyUtils.parse(output);
expectSubset(roundTripped, expected, target);
if (proxy.type === 'external') {
expect(roundTripped.args).to.deep.equal([
'-o',
'Option=a,b',
'say \\"test\\"',
]);
}
}
}
});
it('applies Surge common parameters to Direct aliases', function () {
const proxyOnly = {
'no-error-alert': true,
ecn: true,
'underlying-proxy': 'Entry',
};
const [proxy] = ProxyUtils.parse(
'Alias=direct,interface=en1,dns-follow-interface=false,test-url=https://check.example.com,ecn=true',
);
expectSubset(proxy, {
type: 'direct',
'interface-name': 'en1',
'dns-follow-interface': false,
'test-url': 'https://check.example.com',
});
expect(proxy).to.not.have.property('ecn');
for (const target of ['Surge', 'SurgeMac']) {
const output = produceExternal(target, { ...proxy, ...proxyOnly });
expect(output).to.equal(
'Alias=direct,test-url=https://check.example.com,interface=en1,dns-follow-interface=false',
);
}
});
it('rejects Surge port hopping with an underlying proxy and out-of-range TOS', function () {
const proxies = ProxyUtils.parse(
[
'Hysteria=hysteria2,example.com,443,password=secret,port-hopping=443,2000-2005,underlying-proxy=Entry',
`TUIC=tuic-v5,example.com,443,uuid=${UUID},password=secret,port-hopping="443;2000-2005",underlying-proxy=Entry`,
"MASQUE=masque,example.com,443,password=secret,port-hopping='443;2000-2005',underlying-proxy=Entry",
'TOS=ss,example.com,443,encrypt-method=aes-128-gcm,password=secret,tos=0x100',
].join('\n'),
);
expect(proxies.slice(0, 3).map(({ ports }) => ports)).to.deep.equal(
Array(3).fill('443,2000-2005'),
);
for (const target of ['Surge', 'SurgeMac']) {
const { result, errors } = captureErrors(() =>
ProxyUtils.produce(proxies, target, 'external'),
);
expect(result).to.equal('');
expect(errors).to.have.length(4);
for (const error of errors.slice(0, 3)) {
expect(error).to.include(
'port-hopping cannot be combined with underlying-proxy',
);
}
expect(errors[3]).to.include(
'tos must be an integer between 0 and 255',
);
}
});
it('round-trips Surge ECN modes and converts them to Loon booleans', function () {
for (const [input, mode, loonEcn] of [
['auto', 'auto', undefined],
@@ -3227,6 +3349,42 @@ describe('Proxy text producers', function () {
expect(output).to.not.include('ipv6-cidr');
});
it('round-trips supported Surge WireGuard policy parameters', function () {
const [proxy] = ProxyUtils.parse(
'WG=wireguard,section-name="office,2",underlying-proxy=Entry,ip-version=dual,no-error-alert=true,' +
'test-url=http://10.0.0.1/check?a=b,test-timeout=8,test-udp=example.com@10.0.0.1,' +
'hybrid=on,tos=0x88,tfo=false,block-quic=adaptive,ecn=false,' +
'interface=en1,allow-other-interface=true,dns-follow-interface=true,' +
'shadow-tls-version=3,shadow-tls-password="unused,with=padding=="',
);
expectSubset(proxy, {
type: 'wireguard-surge',
'section-name': 'office,2',
'underlying-proxy': 'Entry',
'ip-version': 'dual',
'no-error-alert': 'true',
'test-url': 'http://10.0.0.1/check?a=b',
'test-timeout': 8,
'test-udp': 'example.com@10.0.0.1',
hybrid: 'on',
tos: 136,
tfo: false,
'block-quic': 'adaptive',
ecn: false,
});
expect(proxy).to.not.have.any.keys('interface-name', 'plugin');
for (const target of ['Surge', 'SurgeMac']) {
const output = produceExternal(target, proxy);
expect(output).to.equal(
'WG=wireguard,section-name="office,2",ip-version=dual,no-error-alert=true,tfo=false,' +
'test-url=http://10.0.0.1/check?a=b,test-timeout=8,test-udp=example.com@10.0.0.1,' +
'hybrid=on,tos=136,block-quic=adaptive,ecn=false,underlying-proxy=Entry',
);
expect(ProxyUtils.parse(output)).to.deep.equal([proxy]);
}
});
it('produces Surge WireGuard sections without leaking CIDR metadata fields', function () {
const output = produceExternal(
'Surge',
@@ -3241,17 +3399,131 @@ describe('Proxy text producers', function () {
ipv6: 'fd00::2',
'ip-cidr': 24,
'ipv6-cidr': 64,
'allow-peer-access': false,
},
{ 'include-unsupported-proxy': true },
);
expect(output).to.include('# > WireGuard Proxy Surge WG');
expect(output).to.include('\nprivate-key = private-key\n');
expect(output).to.include('self-ip = 10.0.0.2');
expect(output).to.include('self-ip-v6 = fd00::2');
expect(output).to.include('allow-peer-access = false');
expect(output).to.include('allowed-ips = "0.0.0.0/0,::/0"');
expect(output).to.not.include('ip-cidr');
expect(output).to.not.include('ipv6-cidr');
});
it('exports a Surge WireGuard keystore reference as the only private key field', function () {
for (const target of ['Surge', 'SurgeMac']) {
for (const privateKey of [undefined, 'inline-key']) {
const output = produceExternal(
target,
{
type: 'wireguard',
name: 'WG',
server: 'wg.example.com',
port: 51820,
ip: '10.0.0.2',
'public-key': 'peer-key',
'private-key': privateKey,
'private-key-keystore-name': 'office-key',
},
{ 'include-unsupported-proxy': true },
);
expect(output).to.include(
'[WireGuard WG]\nprivate-key-keystore-name = office-key\n',
);
expect(output).to.not.include('\nprivate-key =');
expect(output).to.not.include('inline-key');
}
}
});
it('exports Surge WireGuard listeners with every peer and its own fields', function () {
const proxy = {
type: 'wireguard',
name: 'Home WG',
'section-name': 'home-wg',
'private-key': 'private-key',
ip: '10.0.0.1/24',
ipv6: 'fd00::1/64',
'dns-server': ['10.0.0.53', '[fd00::53]:5353', 'system'],
'prefer-ipv6': false,
'ip-version': 'ipv6-prefer',
'allow-peer-access': false,
'accept-incoming': true,
'listen-port': '51820',
'underlying-proxy': 'Entry',
'interface-name': 'en1',
'allow-other-interface': true,
plugin: 'shadow-tls',
'plugin-opts': { version: 3, password: 'unused' },
ecn: false,
peers: [
{
'public-key': 'phone-key',
'allowed-ips': ['10.0.0.2/32'],
'persistent-keepalive': 0,
keepalive: 25,
'client-id': 'aabbcc',
},
{
'public-key': 'router-key',
'allowed-ips': ['10.20.0.0/24', 'fd20::/64'],
server: '2001:db8::10',
port: 51821,
reserved: [83, 12, 235],
'pre-shared-key': 'shared-key',
},
{
'public-key': 'laptop-key',
'allowed-ips': '"10.0.0.3/32, fd00::3/128"',
endpoint: 'laptop.example.com:51822',
'client-id': 'AQID',
},
],
};
for (const target of ['Surge', 'SurgeMac']) {
const output = produceExternal(target, proxy, {
'include-unsupported-proxy': true,
});
expect(output).to.include(
'# Home WG=wireguard,section-name=home-wg,ip-version=prefer-v6,ecn=false\n',
);
expect(output.split('[WireGuard home-wg]\n')[1]).to.equal(
[
'private-key = private-key',
'self-ip = 10.0.0.1',
'self-ip-v6 = fd00::1',
'dns-server = 10.0.0.53, [fd00::53]:5353, system',
'prefer-ipv6 = false',
'listen-port = 51820',
'peer = (public-key = phone-key, allowed-ips = "10.0.0.2/32", keepalive = 0, client-id = 0xaabbcc)',
'peer = (public-key = router-key, allowed-ips = "10.20.0.0/24,fd20::/64", endpoint = [2001:db8::10]:51821, client-id = 83/12/235, preshared-key = shared-key)',
'peer = (public-key = laptop-key, allowed-ips = "10.0.0.3/32, fd00::3/128", endpoint = laptop.example.com:51822, client-id = AQID)',
].join('\n'),
);
}
});
it('exports WireGuard URI preshared keys and normalizes legacy peer access for Surge', function () {
const [proxy] = ProxyUtils.parse(
'wireguard://private-key@wg.example.com:51820/?address=10.0.0.2&publickey=peer-key&presharedkey=shared%2Bkey%3D&allowed-ips=10.0.0.0%2F24&accept-incoming=true&ip-version=ipv6-prefer#WG',
);
const output = produceExternal('Surge', proxy, {
'include-unsupported-proxy': true,
});
expect(output).to.include(
'prefer-ipv6 = true\nallow-peer-access = true',
);
expect(output).to.include(
'peer = (public-key = peer-key, allowed-ips = "10.0.0.0/24", endpoint = wg.example.com:51820, preshared-key = shared+key=)',
);
expect(output).to.not.include('accept-incoming');
});
it('produces Surfboard trojan websocket lines', function () {
const output = produceExternal('Surfboard', {
type: 'trojan',