diff --git a/backend/package.json b/backend/package.json index b8b0dd1d..e0a5aea7 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.21.99", + "version": "2.22.0", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "scripts": { diff --git a/backend/src/core/proxy-utils/index.js b/backend/src/core/proxy-utils/index.js index bd850e0a..75c68003 100644 --- a/backend/src/core/proxy-utils/index.js +++ b/backend/src/core/proxy-utils/index.js @@ -23,7 +23,11 @@ import { findByName } from '@/utils/database'; import { produceArtifact } from '@/restful/sync'; import { getFlag, removeFlag, getISO, MMDB } from '@/utils/geo'; import Gist from '@/utils/gist'; -import { isPresent, isShadowsocksOverTls } from './producers/utils'; +import { + isPresent, + isShadowsocksOverTls, + normalizeWireGuardInterface, +} from './producers/utils'; import { doh } from '@/utils/dns'; import JSON5 from 'json5'; import { hex_md5 } from '@/vendor/md5'; @@ -313,6 +317,9 @@ function produce(proxies, targetPlatform, type, opts = {}) { proxy.port = getRandomPort(proxy.ports); } } + if (proxy.type === 'wireguard') { + normalizeWireGuardInterface(proxy); + } return proxy; }); @@ -745,18 +752,7 @@ function lastParse(proxy) { } } } - if (proxy.ip?.includes('/')) { - const [ip] = proxy.ip.split('/'); - if (isIPv4(ip)) { - proxy.ip = ip; - } - } - if (proxy.ipv6?.includes('/')) { - const [ip] = proxy.ipv6.split('/'); - if (isIPv6(ip)) { - proxy.ipv6 = ip; - } - } + normalizeWireGuardInterface(proxy); } return proxy; } diff --git a/backend/src/core/proxy-utils/parsers/index.js b/backend/src/core/proxy-utils/parsers/index.js index 53b85513..5ffc5034 100644 --- a/backend/src/core/proxy-utils/parsers/index.js +++ b/backend/src/core/proxy-utils/parsers/index.js @@ -42,6 +42,32 @@ function splitURIFragment(raw) { }; } +function parseWireGuardURIAddressValue(value) { + if (value == null) return null; + const raw = `${value}`.trim(); + if (!raw) return null; + const [, hostRaw = raw, cidrRaw] = /^(.*?)(?:\/(\d+))?$/.exec(raw) || []; + const host = `${hostRaw}`.trim().replace(/^\[/, '').replace(/\]$/, ''); + const normalizeCIDR = (cidr, max) => { + if (cidr == null) return undefined; + if (!/^\d+$/.test(cidr)) return undefined; + const parsed = parseInt(cidr, 10); + if (parsed < 0 || parsed > max) return undefined; + return parsed; + }; + if (isIPv4(host)) { + return { family: 'ipv4', address: host, cidr: normalizeCIDR(cidrRaw, 32) }; + } + if (isIPv6(host)) { + return { + family: 'ipv6', + address: host, + cidr: normalizeCIDR(cidrRaw, 128), + }; + } + return null; +} + function URI_PROXY() { // socks5+tls // socks5 @@ -1420,7 +1446,16 @@ function URI_WireGuard() { }; for (const addon of addons.split('&')) { if (addon) { - let [key, value] = addon.split('='); + const equalIndex = addon.indexOf('='); + let key; + let value; + if (equalIndex === -1) { + key = addon; + value = ''; + } else { + key = addon.slice(0, equalIndex); + value = addon.slice(equalIndex + 1); + } key = key.replace(/_/, '-'); value = decodeURIComponent(value); if (['reserved'].includes(key)) { @@ -1433,15 +1468,18 @@ function URI_WireGuard() { } } else if (['address', 'ip'].includes(key)) { value.split(',').map((i) => { - const ip = i - .trim() - .replace(/\/\d+$/, '') - .replace(/^\[/, '') - .replace(/\]$/, ''); - if (isIPv4(ip)) { - proxy.ip = ip; - } else if (isIPv6(ip)) { - proxy.ipv6 = ip; + const parsed = parseWireGuardURIAddressValue(i); + if (!parsed) return; + if (parsed.family === 'ipv4') { + proxy.ip = parsed.address; + if (typeof parsed.cidr !== 'undefined') { + proxy['ip-cidr'] = parsed.cidr; + } + } else if (parsed.family === 'ipv6') { + proxy.ipv6 = parsed.address; + if (typeof parsed.cidr !== 'undefined') { + proxy['ipv6-cidr'] = parsed.cidr; + } } }); } else if (['mtu'].includes(key)) { diff --git a/backend/src/core/proxy-utils/producers/clash.js b/backend/src/core/proxy-utils/producers/clash.js index 449b0dcb..b6f01330 100644 --- a/backend/src/core/proxy-utils/producers/clash.js +++ b/backend/src/core/proxy-utils/producers/clash.js @@ -200,6 +200,8 @@ export default function Clash_Producer() { delete proxy.id; delete proxy.resolved; delete proxy['no-resolve']; + delete proxy['ip-cidr']; + delete proxy['ipv6-cidr']; if (type !== 'internal') { for (const key in proxy) { if (proxy[key] == null || /^_/i.test(key)) { diff --git a/backend/src/core/proxy-utils/producers/clashmeta.js b/backend/src/core/proxy-utils/producers/clashmeta.js index 93c0e02f..da643f74 100644 --- a/backend/src/core/proxy-utils/producers/clashmeta.js +++ b/backend/src/core/proxy-utils/producers/clashmeta.js @@ -1,4 +1,5 @@ import { + getWireGuardAddressWithCIDR, isPresent, produceProxyListOutput, supportsShadowsocksV2rayPluginMode, @@ -163,6 +164,8 @@ export default function ClashMeta_Producer() { proxy['preshared-key'] = proxy['preshared-key'] ?? proxy['pre-shared-key']; proxy['pre-shared-key'] = proxy['preshared-key']; + proxy.ip = getWireGuardAddressWithCIDR(proxy, 'ipv4'); + proxy.ipv6 = getWireGuardAddressWithCIDR(proxy, 'ipv6'); } else if (proxy.type === 'snell' && proxy.version < 3) { delete proxy.udp; } else if (proxy.type === 'vless') { @@ -287,6 +290,8 @@ export default function ClashMeta_Producer() { delete proxy.id; delete proxy.resolved; delete proxy['no-resolve']; + delete proxy['ip-cidr']; + delete proxy['ipv6-cidr']; if (type !== 'internal' || opts['delete-underscore-fields']) { for (const key in proxy) { if (proxy[key] == null || /^_/i.test(key)) { diff --git a/backend/src/core/proxy-utils/producers/shadowrocket.js b/backend/src/core/proxy-utils/producers/shadowrocket.js index 25b92e89..b82c5ebc 100644 --- a/backend/src/core/proxy-utils/producers/shadowrocket.js +++ b/backend/src/core/proxy-utils/producers/shadowrocket.js @@ -1,4 +1,5 @@ import { + getWireGuardAddressWithCIDR, isPresent, isShadowsocksOverTls, produceProxyListOutput, @@ -146,6 +147,8 @@ export default function Shadowrocket_Producer() { proxy['preshared-key'] = proxy['preshared-key'] ?? proxy['pre-shared-key']; proxy['pre-shared-key'] = proxy['preshared-key']; + proxy.ip = getWireGuardAddressWithCIDR(proxy, 'ipv4'); + proxy.ipv6 = getWireGuardAddressWithCIDR(proxy, 'ipv6'); } else if (proxy.type === 'snell' && proxy.version < 3) { delete proxy.udp; } else if (proxy.type === 'vless') { @@ -277,6 +280,8 @@ export default function Shadowrocket_Producer() { delete proxy.id; delete proxy.resolved; delete proxy['no-resolve']; + delete proxy['ip-cidr']; + delete proxy['ipv6-cidr']; if (type !== 'internal') { for (const key in proxy) { if (proxy[key] == null || /^_/i.test(key)) { diff --git a/backend/src/core/proxy-utils/producers/sing-box.js b/backend/src/core/proxy-utils/producers/sing-box.js index 5977c91d..e22882a7 100644 --- a/backend/src/core/proxy-utils/producers/sing-box.js +++ b/backend/src/core/proxy-utils/producers/sing-box.js @@ -1,7 +1,7 @@ import ClashMeta_Producer from './clashmeta'; import $ from '@/core/app'; -import { isIPv4, isIPv6, isPlainObject } from '@/utils'; -import { normalizePluginMuxValue } from './utils'; +import { isPlainObject } from '@/utils'; +import { getWireGuardAddressWithCIDR, normalizePluginMuxValue } from './utils'; const ipVersions = { ipv4: 'ipv4_only', @@ -951,12 +951,8 @@ const tailscaleParser = (proxy = {}) => { }; const wireguardParser = (proxy = {}) => { - const address = ['ip', 'ipv6'] - .map((i) => proxy[i]) - .map((i) => { - if (isIPv4(i)) return `${i}/32`; - if (isIPv6(i)) return `${i}/128`; - }) + const address = ['ipv4', 'ipv6'] + .map((family) => getWireGuardAddressWithCIDR(proxy, family)) .filter((i) => i); const parsedProxy = { system: !!proxy.system, diff --git a/backend/src/core/proxy-utils/producers/stash.js b/backend/src/core/proxy-utils/producers/stash.js index f455d7d3..3e16b540 100644 --- a/backend/src/core/proxy-utils/producers/stash.js +++ b/backend/src/core/proxy-utils/producers/stash.js @@ -340,6 +340,8 @@ export default function Stash_Producer() { delete proxy.id; delete proxy.resolved; delete proxy['no-resolve']; + delete proxy['ip-cidr']; + delete proxy['ipv6-cidr']; if (type !== 'internal') { for (const key in proxy) { if (proxy[key] == null || /^_/i.test(key)) { diff --git a/backend/src/core/proxy-utils/producers/uri.js b/backend/src/core/proxy-utils/producers/uri.js index 2b7cf0ed..2e4e5621 100644 --- a/backend/src/core/proxy-utils/producers/uri.js +++ b/backend/src/core/proxy-utils/producers/uri.js @@ -1,7 +1,7 @@ /* eslint-disable no-case-declarations */ import { Base64 } from 'js-base64'; import { isIPv6 } from '@/utils'; -import { normalizePluginMuxValue } from './utils'; +import { getWireGuardAddressWithCIDR, normalizePluginMuxValue } from './utils'; import { normalizeXhttpScalarUpperBound } from '../xhttp-utils'; function isObject(value) { @@ -1168,6 +1168,8 @@ export default function URI_Producer() { 'port', 'ip', 'ipv6', + 'ip-cidr', + 'ipv6-cidr', 'private-key', ].includes(key) ) { @@ -1186,19 +1188,27 @@ export default function URI_Producer() { } } }); - if (proxy.ip && proxy.ipv6) { + const wireguardIPv4 = getWireGuardAddressWithCIDR( + proxy, + 'ipv4', + ); + const wireguardIPv6 = getWireGuardAddressWithCIDR( + proxy, + 'ipv6', + ); + if (wireguardIPv4 && wireguardIPv6) { wireguardParams.push( `address=${encodeURIComponent( - `${proxy.ip}/32,${proxy.ipv6}/128`, + `${wireguardIPv4},${wireguardIPv6}`, )}`, ); - } else if (proxy.ip) { + } else if (wireguardIPv4) { wireguardParams.push( - `address=${encodeURIComponent(`${proxy.ip}/32`)}`, + `address=${encodeURIComponent(wireguardIPv4)}`, ); - } else if (proxy.ipv6) { + } else if (wireguardIPv6) { wireguardParams.push( - `address=${encodeURIComponent(`${proxy.ipv6}/128`)}`, + `address=${encodeURIComponent(wireguardIPv6)}`, ); } result = `wireguard://${encodeURIComponent( diff --git a/backend/src/core/proxy-utils/producers/utils.js b/backend/src/core/proxy-utils/producers/utils.js index dab87b16..8ddf02a3 100644 --- a/backend/src/core/proxy-utils/producers/utils.js +++ b/backend/src/core/proxy-utils/producers/utils.js @@ -1,5 +1,6 @@ import _ from 'lodash'; import YAML from '@/utils/yaml'; +import { isIPv4, isIPv6 } from '@/utils'; export class Result { constructor(proxy) { @@ -65,6 +66,81 @@ export function supportsShadowsocksV2rayPluginMode(proxy, supportedModes) { return supportedModes.includes(normalizedMode); } +function parseWireGuardCIDR(cidr, max) { + if (cidr == null) return undefined; + const normalized = `${cidr}`.trim(); + if (!/^\d+$/.test(normalized)) return undefined; + const parsed = parseInt(normalized, 10); + if (parsed < 0 || parsed > max) return undefined; + return parsed; +} + +function parseWireGuardInterfaceAddress(value, family) { + if (value == null) return null; + const raw = `${value}`.trim(); + if (!raw) return null; + const [, hostRaw = raw, cidrRaw] = /^(.*?)(?:\/(\d+))?$/.exec(raw) || []; + const host = `${hostRaw}`.trim().replace(/^\[/, '').replace(/\]$/, ''); + const isIPv4Family = family === 'ipv4'; + const isValid = isIPv4Family ? isIPv4(host) : isIPv6(host); + if (!isValid) return null; + const max = isIPv4Family ? 32 : 128; + return { + address: host, + cidr: parseWireGuardCIDR(cidrRaw, max), + }; +} + +function normalizeWireGuardInterfaceAddress(proxy, config) { + const { addressKey, cidrKey, family, defaultCIDR } = config; + const parsed = parseWireGuardInterfaceAddress(proxy[addressKey], family); + if (!parsed) { + if ( + proxy[addressKey] == null || + `${proxy[addressKey]}`.trim().length === 0 + ) { + delete proxy[cidrKey]; + } + return; + } + proxy[addressKey] = parsed.address; + const normalizedCIDR = parseWireGuardCIDR(proxy[cidrKey], defaultCIDR); + proxy[cidrKey] = normalizedCIDR ?? parsed.cidr ?? defaultCIDR; +} + +export function normalizeWireGuardInterface(proxy = {}) { + normalizeWireGuardInterfaceAddress(proxy, { + addressKey: 'ip', + cidrKey: 'ip-cidr', + family: 'ipv4', + defaultCIDR: 32, + }); + normalizeWireGuardInterfaceAddress(proxy, { + addressKey: 'ipv6', + cidrKey: 'ipv6-cidr', + family: 'ipv6', + defaultCIDR: 128, + }); + return proxy; +} + +export function getWireGuardAddressWithCIDR(proxy = {}, family = 'ipv4') { + const config = + family === 'ipv6' + ? { addressKey: 'ipv6', cidrKey: 'ipv6-cidr', defaultCIDR: 128 } + : { addressKey: 'ip', cidrKey: 'ip-cidr', defaultCIDR: 32 }; + const parsed = parseWireGuardInterfaceAddress( + proxy[config.addressKey], + family, + ); + if (!parsed) return undefined; + const normalizedCIDR = parseWireGuardCIDR( + proxy[config.cidrKey], + config.defaultCIDR, + ); + return `${parsed.address}/${normalizedCIDR ?? parsed.cidr ?? config.defaultCIDR}`; +} + export function produceProxyListOutput(list, type, opts = {}) { if (type === 'internal') return list; diff --git a/backend/src/test/proxy-parsers/uri.spec.js b/backend/src/test/proxy-parsers/uri.spec.js index dbbf3bb3..289c9104 100644 --- a/backend/src/test/proxy-parsers/uri.spec.js +++ b/backend/src/test/proxy-parsers/uri.spec.js @@ -423,12 +423,50 @@ describe('Proxy URI parser coverage', function () { 'public-key': 'public-key', ip: '10.0.0.2', ipv6: 'fd00::2', + 'ip-cidr': 32, + 'ipv6-cidr': 128, reserved: [1, 2, 3], mtu: 1280, udp: false, }); }); + it('defaults WireGuard CIDR suffixes when address entries omit them', function () { + const proxy = parseOne( + 'wg://private-key@wg.example.com?publickey=public-key&address=10.0.0.2,[fd00::2]#WG%20Default%20CIDR', + ); + + expectSubset(proxy, { + type: 'wireguard', + name: 'WG Default CIDR', + ip: '10.0.0.2', + ipv6: 'fd00::2', + 'ip-cidr': 32, + 'ipv6-cidr': 128, + }); + }); + + it('preserves trailing base64 padding in WireGuard key query params', function () { + const proxy = parseOne( + 'wg://120.233.41.77:19368?publicKey=N+K9fXobvy0vy3VFbn8a7tPRgUNcQbGRwjlyOMx4WHc=&privateKey=QJjrFqqqpbIqfI5qhbYWrPXhaBFmFq71jCj8mMaQE04=&ip=10.0.20.45/16,fd10:10:10:0:10:0:20:45/64&mtu=1420&udp=1#HK-%E5%A4%A7%E5%B8%A6%E5%AE%BD4', + ); + + expectSubset(proxy, { + type: 'wireguard', + name: 'HK-大带宽4', + server: '120.233.41.77', + port: 19368, + 'public-key': 'N+K9fXobvy0vy3VFbn8a7tPRgUNcQbGRwjlyOMx4WHc=', + 'private-key': 'QJjrFqqqpbIqfI5qhbYWrPXhaBFmFq71jCj8mMaQE04=', + ip: '10.0.20.45', + 'ip-cidr': 16, + ipv6: 'fd10:10:10:0:10:0:20:45', + 'ipv6-cidr': 64, + mtu: 1420, + udp: true, + }); + }); + it('parses Trojan URIs with websocket transport', function () { const proxy = parseOne( 'trojan://trojan-pass@trojan-ws.example.com?type=ws&host=ws.example.com&path=%2Fws#Trojan%20WS', diff --git a/backend/src/test/proxy-producers/structured.spec.js b/backend/src/test/proxy-producers/structured.spec.js index 2e3a35b4..f39b00b2 100644 --- a/backend/src/test/proxy-producers/structured.spec.js +++ b/backend/src/test/proxy-producers/structured.spec.js @@ -941,6 +941,99 @@ describe('Proxy structured producers', function () { } }); + it('emits WireGuard interface CIDR suffixes for Mihomo and Shadowrocket outputs', function () { + const proxies = [ + { + type: 'wireguard', + name: 'WG Explicit CIDR', + server: 'wg-explicit.example.com', + port: 51820, + 'private-key': 'private-key-1', + 'public-key': 'public-key-1', + ip: '10.0.0.2', + ipv6: 'fd00::2', + 'ip-cidr': 24, + 'ipv6-cidr': 64, + }, + { + type: 'wireguard', + name: 'WG Default CIDR', + server: 'wg-default.example.com', + port: 51820, + 'private-key': 'private-key-2', + 'public-key': 'public-key-2', + ip: '10.0.0.3', + ipv6: 'fd00::3', + }, + ]; + + for (const platform of ['Mihomo', 'Shadowrocket']) { + const output = loadProducedYaml(platform, proxies); + const explicit = output.proxies.find( + (proxy) => proxy.name === 'WG Explicit CIDR', + ); + const defaults = output.proxies.find( + (proxy) => proxy.name === 'WG Default CIDR', + ); + + expectSubset(explicit, { + ip: '10.0.0.2/24', + ipv6: 'fd00::2/64', + }); + expectSubset(defaults, { + ip: '10.0.0.3/32', + ipv6: 'fd00::3/128', + }); + expect(explicit).to.not.have.property('ip-cidr'); + expect(explicit).to.not.have.property('ipv6-cidr'); + expect(defaults).to.not.have.property('ip-cidr'); + expect(defaults).to.not.have.property('ipv6-cidr'); + } + }); + + it('emits WireGuard address CIDR suffixes for sing-box exports', function () { + const output = loadProducedJson('sing-box', [ + { + type: 'wireguard', + name: 'Sing-box WG Explicit CIDR', + server: 'wg-explicit.example.com', + port: 51820, + 'private-key': 'private-key-1', + 'public-key': 'public-key-1', + ip: '10.0.0.2', + ipv6: 'fd00::2', + 'ip-cidr': 24, + 'ipv6-cidr': 64, + }, + { + type: 'wireguard', + name: 'Sing-box WG Default CIDR', + server: 'wg-default.example.com', + port: 51820, + 'private-key': 'private-key-2', + 'public-key': 'public-key-2', + ip: '10.0.0.3', + ipv6: 'fd00::3', + }, + ]); + + const explicit = output.endpoints.find( + (endpoint) => endpoint.tag === 'Sing-box WG Explicit CIDR', + ); + const defaults = output.endpoints.find( + (endpoint) => endpoint.tag === 'Sing-box WG Default CIDR', + ); + + expectSubset(explicit, { + type: 'wireguard', + address: ['10.0.0.2/24', 'fd00::2/64'], + }); + expectSubset(defaults, { + type: 'wireguard', + address: ['10.0.0.3/32', 'fd00::3/128'], + }); + }); + it('filters canonical shadowsocks over-tls nodes for unsupported client targets by default', function () { const proxy = { type: 'ss', diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index c53e156f..5e455b47 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -587,6 +587,47 @@ describe('Proxy text producers', function () { expect(output).to.not.include('Forced Mihomo=tuic-v5'); }); + it('produces URI WireGuard links with stored and default CIDR suffixes', function () { + const output = produceExternal('URI', [ + { + type: 'wireguard', + name: 'URI WG Explicit CIDR', + server: 'wg-explicit.example.com', + port: 51820, + 'private-key': 'private-key-1', + 'public-key': 'public-key-1', + ip: '10.0.0.2', + ipv6: 'fd00::2', + 'ip-cidr': 24, + 'ipv6-cidr': 64, + udp: true, + }, + { + type: 'wireguard', + name: 'URI WG Default CIDR', + server: 'wg-default.example.com', + port: 51820, + 'private-key': 'private-key-2', + 'public-key': 'public-key-2', + ip: '10.0.0.3', + ipv6: 'fd00::3', + udp: true, + }, + ]); + + const [explicit, defaults] = output.split('\n'); + expect(explicit).to.include( + 'address=10.0.0.2%2F24%2Cfd00%3A%3A2%2F64', + ); + expect(defaults).to.include( + 'address=10.0.0.3%2F32%2Cfd00%3A%3A3%2F128', + ); + expect(explicit).to.not.include('ip-cidr='); + expect(explicit).to.not.include('ipv6-cidr='); + expect(defaults).to.not.include('ip-cidr='); + expect(defaults).to.not.include('ipv6-cidr='); + }); + it('produces URI shadowsocks links with v2ray-plugin mux and tls flags', function () { const plugin = encodeURIComponent( 'v2ray-plugin;obfs=websocket;mode=websocket;obfs-host=cdn.example.com;host=cdn.example.com;path=/socket;tls;sni=sni.example.com;skip-cert-verify=true;mux=0', diff --git a/scripts/demo.js b/scripts/demo.js index 9eb6ce2e..ee426a4c 100644 --- a/scripts/demo.js +++ b/scripts/demo.js @@ -38,6 +38,7 @@ function operator(proxies = [], targetPlatform, context) { // 24. Surge for macOS 可手动指定链接参数 target=SurgeMac 或在 同步配置 中指定 SurgeMac 来启用 mihomo 支援 Surge 本身不支持的协议. 设置节点字段 `_mihomoExternal` 为 `true` 可强制指定使用 mihomo External Proxy Program 输出该节点 // 25. VLESS URI extra 字段复杂且其他客户端不一定跟进, 所以输出 URI 时, 若存在原始的 `_extra` 字段, 则直接使用该字段的值输出到 URI 的 extra 部分, 而不进行解析和重组 // 26. `_qx_obfs_http` 为 QX 的 http obfs 原始值, 例如 `http`, `vmess-http`, `vemss-http`, `shadowsocks-http`, 用于 QX 输入输出时保留原始写法. `vemss-http` 应该是 huaqian 的 typo, 没测过, 反正也支持, 报错就自己改成 `vmess-http` 吧 + // 27. WireGuard 支持 `ip-cidr`(IPv4 前缀长度) 和 `ipv6-cidr`(IPv6 前缀长度) 字段: 内部会保存前缀长度, 若未设置则默认分别为 `32` 和 `128`. 输出到 `mihomo`/`Shadowrocket`/`sing-box`/`URI` 时会带上该后缀 // require 为 Node.js 的 require, 在 Node.js 运行环境下 可以用来引入模块 // 例如在 Node.js 环境下, 将文件内容写入 /tmp/1.txt 文件