diff --git a/backend/package.json b/backend/package.json index 6ef447a2..4d8bbf98 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/core/proxy-utils/parsers/index.js b/backend/src/core/proxy-utils/parsers/index.js index 732fd8d9..ebe34705 100644 --- a/backend/src/core/proxy-utils/parsers/index.js +++ b/backend/src/core/proxy-utils/parsers/index.js @@ -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 }; } diff --git a/backend/src/core/proxy-utils/parsers/peggy/surge.js b/backend/src/core/proxy-utils/parsers/peggy/surge.js index ca461d56..9986a8a5 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/surge.js +++ b/backend/src/core/proxy-utils/parsers/peggy/surge.js @@ -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'; } diff --git a/backend/src/core/proxy-utils/producers/surge.js b/backend/src/core/proxy-utils/producers/surge.js index 5acfd7ef..acbed11d 100644 --- a/backend/src/core/proxy-utils/producers/surge.js +++ b/backend/src/core/proxy-utils/producers/surge.js @@ -1,6 +1,11 @@ import _ from 'lodash'; -import { Result, isPresent, supportsVlessTransportSecurity } from './utils'; -import { isNotBlank, getIfNotBlank, isPlainObject } from '@/utils'; +import { + Result, + isPresent, + normalizeWireGuardInterface, + supportsVlessTransportSecurity, +} from './utils'; +import { isNotBlank, getIfNotBlank, isIPv6, isPlainObject } from '@/utils'; import $ from '@/core/app'; import { isMihomoEchEnabled, normalizeInlineEchConfigList } from '../ech-utils'; import { SURGE_XHTTP_FIELDS } from '../surge-xhttp'; @@ -51,6 +56,69 @@ function hasNonBlankValue(value) { return value != null && `${value}`.trim().length > 0; } +export function appendSurgePolicyParameters(result, proxy) { + const isDirect = proxy.type === 'direct'; + const supportsInterface = !['wireguard', 'wireguard-surge'].includes( + proxy.type, + ); + const ipVersion = proxy['ip-version']; + const tos = stripSurgeQuotes(proxy.tos); + if ( + tos != null && + (!/^(?:\d+|0x[\da-f]+)$/i.test(tos) || Number(tos) > 255) + ) { + throw new Error('Surge tos must be an integer between 0 and 255'); + } + + const parameters = { + 'ip-version': ipVersions[ipVersion] ?? ipVersion, + 'no-error-alert': isDirect ? undefined : proxy['no-error-alert'], + tfo: proxy.tfo ?? proxy['fast-open'], + 'test-url': proxy['test-url'], + 'test-timeout': proxy['test-timeout'], + 'test-udp': proxy['test-udp'], + hybrid: proxy.hybrid, + tos, + 'allow-other-interface': supportsInterface + ? proxy['allow-other-interface'] + : undefined, + interface: supportsInterface + ? proxy.interface ?? proxy['interface-name'] + : undefined, + 'dns-follow-interface': supportsInterface + ? proxy['dns-follow-interface'] + : undefined, + 'block-quic': proxy['block-quic'], + ecn: isDirect ? undefined : proxy.ecn, + 'underlying-proxy': isDirect ? undefined : proxy['underlying-proxy'], + }; + + for (const [key, value] of Object.entries(parameters)) { + if (value == null) continue; + const formatted = + typeof value === 'string' && value.includes(',') + ? quoteSurgeValue(value) + : value; + result.append(`,${key}=${formatted}`); + } +} + +function appendPortHopping(result, proxy) { + if (hasNonBlankValue(proxy.ports)) { + if (hasNonBlankValue(stripSurgeQuotes(proxy['underlying-proxy']))) { + throw new Error( + 'Surge port-hopping cannot be combined with underlying-proxy', + ); + } + result.append( + `,port-hopping="${String(proxy.ports).replace(/,/g, ';')}"`, + ); + } + if (hasNonBlankValue(proxy['hop-interval'])) { + result.append(`,port-hopping-interval=${proxy['hop-interval']}`); + } +} + function formatSurgeAlpn(alpn) { const values = Array.isArray(alpn) ? alpn @@ -258,7 +326,7 @@ export default function Surge_Producer() { case 'tuic': return tuic(proxy); case 'wireguard-surge': - return wireguard_surge(proxy); + return wireguardPolicy(proxy); case 'hysteria2': return hysteria2(proxy); case 'ssh': @@ -336,14 +404,6 @@ function shadowsocks(proxy) { result.append(`,encrypt-method=${proxy.cipher}`); result.appendIfPresent(`,password="${proxy.password}"`, 'password'); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // obfs if (isPresent(proxy, 'plugin')) { if (proxy.plugin === 'obfs') { @@ -361,43 +421,12 @@ function shadowsocks(proxy) { } } - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - // udp result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp'); - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy, true); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -406,14 +435,6 @@ function trojan(proxy) { result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`); result.appendIfPresent(`,password="${proxy.password}"`, 'password'); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // transport handleTransport(result, proxy); @@ -423,40 +444,9 @@ function trojan(proxy) { // tls verification appendTlsProxyParams(result, proxy); - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -465,52 +455,13 @@ function anytls(proxy) { result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`); result.appendIfPresent(`,password="${proxy.password}"`, 'password'); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // tls verification appendTlsProxyParams(result, proxy); - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - // reuse result.appendIfPresent(`,reuse=${proxy['reuse']}`, 'reuse'); + appendSurgePolicyParameters(result, proxy); return result.toString(); } function trusttunnel(proxy) { @@ -535,52 +486,13 @@ function trusttunnel(proxy) { ); if (proxy.network === 'h3') result.append(',h3=true'); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // tls verification appendTlsProxyParams(result, proxy); - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - // reuse result.appendIfPresent(`,reuse=${proxy['reuse']}`, 'reuse'); + appendSurgePolicyParameters(result, proxy); return result.toString(); } function masque_surge(proxy) { @@ -589,52 +501,11 @@ function masque_surge(proxy) { result.appendIfPresent(`,username="${proxy.username}"`, 'username'); result.appendIfPresent(`,password="${proxy.password}"`, 'password'); - if (hasNonBlankValue(proxy.ports)) { - result.append( - `,port-hopping="${String(proxy.ports).replace(/,/g, ';')}"`, - ); - } - if (hasNonBlankValue(proxy['hop-interval'])) { - result.append(`,port-hopping-interval=${proxy['hop-interval']}`); - } + appendPortHopping(result, proxy); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); appendTlsProxyParams(result, proxy); - if (isPresent(proxy, 'tfo')) { - result.append(`,tfo=${proxy.tfo}`); - } else if (isPresent(proxy, 'fast-open')) { - result.append(`,tfo=${proxy['fast-open']}`); - } - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy.hybrid}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy.tos}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy.interface}`, 'interface'); - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } function h2Connect(proxy) { @@ -649,48 +520,13 @@ function h2Connect(proxy) { 'max-streams', ); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - appendTlsProxyParams(result, proxy); - if (proxy.tfo) { - $.info(`Option tfo is not supported by Surge, thus omitted`); - } - result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp'); - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); appendShadowTLS(result, proxy); - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -706,14 +542,6 @@ function v2ray(proxy, includeUnsupportedProxy) { } } - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - if (isVless) { appendVlessParams(result, proxy); } else { @@ -726,40 +554,9 @@ function v2ray(proxy, includeUnsupportedProxy) { appendTlsProxyParams(result, proxy, Boolean(proxy.tls)); } - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -872,46 +669,7 @@ function ssh(proxy) { 'server-fingerprint', ); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } function http(proxy) { @@ -922,97 +680,19 @@ function http(proxy) { result.appendIfPresent(`,password="${proxy.password}"`, 'password'); appendHeaders(result, proxy); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // tls verification appendTlsProxyParams(result, proxy, Boolean(proxy.tls)); - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } function direct(proxy) { const result = new Result(proxy); - const type = 'direct'; - result.append(`${proxy.name}=${type}`); - - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); + result.append(`${proxy.name}=direct`); + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -1023,56 +703,15 @@ function socks5(proxy) { result.appendIfPresent(`,username="${proxy.username}"`, 'username'); result.appendIfPresent(`,password="${proxy.password}"`, 'password'); - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // tls verification appendTlsProxyParams(result, proxy, Boolean(proxy.tls)); - // tfo - if (proxy.tfo) { - $.info(`Option tfo is not supported by Surge, thus omitted`); - } - // udp result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp'); - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -1114,14 +753,6 @@ function snell(proxy) { result.appendIfPresent(`,mode=${proxy.mode}`, 'mode'); } - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // obfs result.appendIfPresent( `,obfs=${proxy['obfs-opts']?.mode}`, @@ -1136,43 +767,12 @@ function snell(proxy) { 'obfs-opts.path', ); - // tfo - result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - // reuse result.appendIfPresent(`,reuse=${proxy['reuse']}`, 'reuse'); + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -1189,221 +789,162 @@ function tuic(proxy) { result.appendIfPresent(`,password="${proxy.password}"`, 'password'); result.appendIfPresent(`,token=${proxy.token}`, 'token'); - if (hasNonBlankValue(proxy.ports)) { - result.append( - `,port-hopping="${String(proxy.ports).replace(/,/g, ';')}"`, - ); - } - - if (hasNonBlankValue(proxy['hop-interval'])) { - result.append(`,port-hopping-interval=${proxy['hop-interval']}`); - } - - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); + appendPortHopping(result, proxy); // tls verification appendTlsProxyParams(result, proxy); - // 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'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } function wireguard(proxy) { - if (Array.isArray(proxy.peers) && proxy.peers.length > 0) { - proxy.server = proxy.peers[0].server; - proxy.port = proxy.peers[0].port; - proxy.ip = proxy.peers[0].ip; - proxy.ipv6 = proxy.peers[0].ipv6; - proxy['public-key'] = proxy.peers[0]['public-key']; - proxy['preshared-key'] = proxy.peers[0]['pre-shared-key']; - // https://github.com/MetaCubeX/mihomo/blob/0404e35be8736b695eae018a08debb175c1f96e6/docs/config.yaml#L717 - proxy['allowed-ips'] = proxy.peers[0]['allowed-ips']; - proxy.reserved = proxy.peers[0].reserved; + const peers = + Array.isArray(proxy.peers) && proxy.peers.length > 0 + ? proxy.peers + : [proxy]; + const { ip, ipv6 } = normalizeWireGuardInterface({ + ip: proxy['self-ip'] ?? proxy.ip ?? peers[0].ip, + ipv6: proxy['self-ip-v6'] ?? proxy.ipv6 ?? peers[0].ipv6, + }); + const keyField = isNotBlank(proxy['private-key-keystore-name']) + ? 'private-key-keystore-name' + : 'private-key'; + const keyValue = proxy[keyField]; + if (!hasNonBlankValue(keyValue) || (!ip && !ipv6)) { + throw new Error( + 'Surge WireGuard requires a local address and either private-key or private-key-keystore-name', + ); } + + const listenPort = proxy['listen-port']; + if ( + listenPort != null && + (!/^\d+$/.test(`${listenPort}`.trim()) || + listenPort < 1 || + listenPort > 65535) + ) { + throw new Error( + 'Surge WireGuard listen-port must be between 1 and 65535', + ); + } + + const sectionName = getIfNotBlank(proxy['section-name'], proxy.name).trim(); + const policy = wireguardPolicy({ + ...proxy, + 'section-name': sectionName, + 'underlying-proxy': + listenPort == null ? proxy['underlying-proxy'] : undefined, + }); const result = new Result(proxy); - result.append(`# > WireGuard Proxy ${proxy.name} -# ${proxy.name}=wireguard`); - - proxy['section-name'] = getIfNotBlank(proxy['section-name'], proxy.name); - - result.appendIfPresent( - `,section-name=${proxy['section-name']}`, - 'section-name', - ); - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - - appendShadowTLS(result, proxy); - - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - - result.append(` +# ${policy} # > WireGuard Section ${proxy.name} -[WireGuard ${proxy['section-name']}] -private-key = ${proxy['private-key']}`); +[WireGuard ${sectionName}] +${keyField} = ${keyValue}`); - result.appendIfPresent(`\nself-ip = ${proxy.ip}`, 'ip'); - result.appendIfPresent(`\nself-ip-v6 = ${proxy.ipv6}`, 'ipv6'); - if (proxy.dns) { - if (Array.isArray(proxy.dns)) { - proxy.dns = proxy.dns.join(', '); - } - result.append(`\ndns-server = ${proxy.dns}`); - } + if (ip) result.append(`\nself-ip = ${ip}`); + if (ipv6) result.append(`\nself-ip-v6 = ${ipv6}`); + const dns = proxy['dns-server'] ?? proxy.dns; + const dnsServers = Array.isArray(dns) ? dns.join(', ') : dns; + if (isNotBlank(dnsServers)) result.append(`\ndns-server = ${dnsServers}`); result.appendIfPresent(`\nmtu = ${proxy.mtu}`, 'mtu'); - if (ip_version === 'prefer-v6') { + if (isPresent(proxy, 'prefer-ipv6')) { + result.append(`\nprefer-ipv6 = ${proxy['prefer-ipv6']}`); + } else if (['ipv6-prefer', 'prefer-v6'].includes(proxy['ip-version'])) { result.append(`\nprefer-ipv6 = true`); } - const allowedIps = Array.isArray(proxy['allowed-ips']) - ? proxy['allowed-ips'].join(',') - : proxy['allowed-ips']; - let reserved = Array.isArray(proxy.reserved) - ? proxy.reserved.join('/') - : proxy.reserved; - let presharedKey = proxy['preshared-key'] ?? proxy['pre-shared-key']; + const allowPeerAccess = + proxy['allow-peer-access'] ?? proxy['accept-incoming']; + // A listening port already enables peer access. + if (listenPort == null && allowPeerAccess != null) { + result.append(`\nallow-peer-access = ${allowPeerAccess}`); + } + result.appendIfPresent(`\nlisten-port = ${listenPort}`, 'listen-port'); - const peer = { - 'public-key': proxy['public-key'], - 'allowed-ips': allowedIps ? `"${allowedIps}"` : undefined, - endpoint: `${proxy.server}:${proxy.port}`, - keepalive: proxy['persistent-keepalive'] || proxy.keepalive, - 'client-id': reserved, - 'preshared-key': presharedKey, - }; - result.append( - `\npeer = (${Object.keys(peer) - .filter((k) => peer[k] != null) - .map((k) => `${k} = ${peer[k]}`) - .join(', ')})`, - ); + const singlePeerDefaults = peers.length === 1 ? proxy : {}; + // When peers can initiate traffic, allowed-ips also limits their source addresses. + const defaultAllowedIps = + peers.length === 1 && + listenPort == null && + (allowPeerAccess == null || + /^false$/i.test(`${allowPeerAccess}`.trim())) + ? [ip && '0.0.0.0/0', ipv6 && '::/0'].filter(Boolean).join(',') + : undefined; + for (const peer of peers) { + const routes = peer['allowed-ips'] ?? singlePeerDefaults['allowed-ips']; + const allowedIps = + stripSurgeQuotes( + Array.isArray(routes) ? routes.join(',') : routes, + ) || defaultAllowedIps; + if (!hasNonBlankValue(peer['public-key']) || !allowedIps) { + throw new Error( + 'Surge WireGuard peers require public-key and allowed-ips', + ); + } + + let endpoint = peer.endpoint; + if ( + !isNotBlank(endpoint) && + isNotBlank(peer.server) && + hasNonBlankValue(peer.port) + ) { + const server = peer.server.trim(); + endpoint = `${isIPv6(server) ? `[${server}]` : server}:${ + peer.port + }`; + } + if (!isNotBlank(endpoint) && listenPort == null) { + throw new Error( + 'Surge WireGuard peers require endpoint without listen-port', + ); + } + + let clientId = stripSurgeQuotes(peer['client-id'] ?? peer.reserved); + if (Array.isArray(clientId)) { + clientId = clientId.join('/'); + } else if (/^[\da-f]{6}$/i.test(clientId)) { + clientId = `0x${clientId}`; + } + const fields = { + 'public-key': peer['public-key'], + 'allowed-ips': quoteSurgeValue(allowedIps), + endpoint, + keepalive: + peer['persistent-keepalive'] ?? + peer.keepalive ?? + peer['persistent-keepalive-interval'] ?? + proxy['persistent-keepalive'] ?? + proxy.keepalive, + 'client-id': clientId, + 'preshared-key': + peer['preshared-key'] ?? + peer['pre-shared-key'] ?? + singlePeerDefaults['preshared-key'] ?? + singlePeerDefaults['pre-shared-key'], + }; + const options = Object.entries(fields) + .filter(([, value]) => hasNonBlankValue(value)) + .map(([key, value]) => `${key} = ${value}`) + .join(', '); + result.append(`\npeer = (${options})`); + } return result.toString(); } -function wireguard_surge(proxy) { + +function wireguardPolicy(proxy) { + const sectionName = getIfNotBlank(proxy['section-name'])?.trim(); + if (!sectionName) throw new Error('Surge WireGuard requires section-name'); + const sectionNameValue = sectionName.includes(',') + ? quoteSurgeValue(sectionName) + : sectionName; const result = new Result(proxy); + result.append(`${proxy.name}=wireguard,section-name=${sectionNameValue}`); - result.append(`${proxy.name}=wireguard`); - - result.appendIfPresent( - `,section-name=${proxy['section-name']}`, - 'section-name', - ); - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - // test-url - result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - - appendShadowTLS(result, proxy); - - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } @@ -1422,76 +963,24 @@ function hysteria2(proxy) { result.appendIfPresent(`,password="${proxy.password}"`, 'password'); - if (hasNonBlankValue(proxy.ports)) { - result.append( - `,port-hopping="${String(proxy.ports).replace(/,/g, ';')}"`, - ); - } - - if (hasNonBlankValue(proxy['hop-interval'])) { - result.append(`,port-hopping-interval=${proxy['hop-interval']}`); - } + appendPortHopping(result, proxy); if (proxy['obfs-password'] && obfsPasswordField) { result.append(`,${obfsPasswordField}="${proxy['obfs-password']}"`); } - const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version']; - result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version'); - - result.appendIfPresent( - `,no-error-alert=${proxy['no-error-alert']}`, - 'no-error-alert', - ); - // tls verification appendTlsProxyParams(result, proxy); - // 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'); - result.appendIfPresent( - `,test-timeout=${proxy['test-timeout']}`, - 'test-timeout', - ); - result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp'); - result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid'); - result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos'); - result.appendIfPresent( - `,allow-other-interface=${proxy['allow-other-interface']}`, - 'allow-other-interface', - ); - result.appendIfPresent( - `,interface=${proxy['interface-name']}`, - 'interface-name', - ); - result.appendIfPresent(`,interface=${proxy['interface']}`, 'interface'); - appendShadowTLS(result, proxy); - // block-quic - result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic'); - - // underlying-proxy - result.appendIfPresent( - `,underlying-proxy=${proxy['underlying-proxy']}`, - 'underlying-proxy', - ); - // download-bandwidth result.appendIfPresent( `,download-bandwidth=${`${proxy['down']}`.match(/\d+/)?.[0] || 0}`, 'down', ); - result.appendIfPresent(`,ecn=${proxy.ecn}`, 'ecn'); - + appendSurgePolicyParameters(result, proxy); return result.toString(); } diff --git a/backend/src/core/proxy-utils/producers/surgemac.js b/backend/src/core/proxy-utils/producers/surgemac.js index 98a0d72e..e3c5abee 100644 --- a/backend/src/core/proxy-utils/producers/surgemac.js +++ b/backend/src/core/proxy-utils/producers/surgemac.js @@ -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 diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index ef5040a6..959c3d40 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -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',