From 495e88c0d35e5dbe242ac7d0b8a7bdd37c9be6c9 Mon Sep 17 00:00:00 2001 From: xream Date: Fri, 15 May 2026 15:05:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(surge):=20=E6=94=AF=E6=8C=81=20Surge=20hea?= =?UTF-8?q?ders=20=E5=A4=8D=E6=9D=82=E5=9C=BA=E6=99=AF=E7=9A=84=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=E4=B8=8E=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 解析器增强 Surge headers 的分段与转义处理,修复包含分号、逗号、引号、反斜杠的场景解析失败 - 支持 quoted header key/value 与 `headers="..."` / `headers='...'` 外层包裹的解析,避免误截断 - 生成器输出 headers 时统一加外层引号,并对值内双引号进行转义,降低往返转换不一致风险 - 通过 proxy parser/producers 测试覆盖复杂 headers(嵌套引号、quoted key、quote-start key)并新增 round-trip 校验 - 补充 README Surge 支持列表,加入 HTTPS 与 HTTP/2 CONNECT --- README.md | 2 +- backend/package.json | 2 +- .../core/proxy-utils/parsers/peggy/surge.js | 280 +++++++++++++++++- .../src/core/proxy-utils/producers/surge.js | 8 +- .../proxy-parsers/v2ray-and-platforms.spec.js | 84 ++++++ backend/src/test/proxy-producers/text.spec.js | 45 ++- 6 files changed, 404 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 2cd57b27..5ae9cfe5 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ sub.store = 127.0.0.1 > [NaiveProxy](https://t.me/zhetengsha/4308) - [x] QX (SS, SSR, VMess, Trojan, HTTP, SOCKS5, VLESS, AnyTLS) - [x] Loon (SS, SSR, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard, VLESS, Hysteria 2, AnyTLS) -- [x] Surge (Direct, SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, AnyTLS, TrustTunnel, TUIC, Snell, Hysteria 2, SSH(Password authentication only), External Proxy Program(only for macOS), WireGuard(Surge to Surge)) +- [x] Surge (Direct, SS, VMess, Trojan, HTTP, HTTPS, HTTP/2 CONNECT, SOCKS5, SOCKS5-TLS, AnyTLS, TrustTunnel, TUIC, Snell, Hysteria 2, SSH(Password authentication only), External Proxy Program(only for macOS), WireGuard(Surge to Surge)) - [x] mihomo(Clash.Meta) Compatible (Direct, SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC, SSH, mieru, sudoku, AnyTLS, MASQUE, Tailscale, OpenVPN) Deprecated(The frontend doesn't show it, but the backend still supports it, with the query parameter `target=Clash`): diff --git a/backend/package.json b/backend/package.json index 3e2ecd7e..c23fe890 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.23.5", + "version": "2.23.6", "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/peggy/surge.js b/backend/src/core/proxy-utils/parsers/peggy/surge.js index d3897661..c410cebd 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/surge.js +++ b/backend/src/core/proxy-utils/parsers/peggy/surge.js @@ -35,18 +35,273 @@ const grammars = String.raw` proxy['shadow-tls-version'] = 2; } } + function stripQuotes(value) { + const trimmed = value.trim(); + const quote = trimmed[0]; + if ( + (quote === '"' || quote === "'") && + trimmed[trimmed.length - 1] === quote + ) { + return trimmed.slice(1, -1).replace(/\\(["'\\])/g, "$1"); + } + + return trimmed.replace(/\\(["'\\])/g, "$1"); + } + function isEscaped(text, index) { + let count = 0; + let cursor = index - 1; + + while (cursor >= 0 && text[cursor] === "\\") { + count++; + cursor--; + } + + return count % 2 === 1; + } + function readQuotedHeaderKey(text, start) { + const quote = text[start]; + let index = start + 1; + let hasKey = false; + + while (index < text.length) { + const char = text[index]; + if (char === "\\" && index + 1 < text.length) { + hasKey = true; + index += 2; + continue; + } + if (char === quote) { + return hasKey ? index + 1 : -1; + } + + hasKey = true; + index++; + } + + return -1; + } + function startsWithQuotedHeaderKey(text) { + const trimmed = text.trim(); + if (trimmed[0] !== '"' && trimmed[0] !== "'") return false; + + const index = readQuotedHeaderKey(trimmed, 0); + if (index === -1) return false; + + let cursor = index; + while (cursor < trimmed.length && /\s/.test(trimmed[cursor])) cursor++; + return trimmed[cursor] === ":"; + } + function stripOuterHeadersQuotes(headers) { + const trimmed = headers.trim(); + const quote = trimmed[0]; + + if ( + (quote === '"' || quote === "'") && + trimmed[trimmed.length - 1] === quote && + !startsWithQuotedHeaderKey(trimmed) + ) { + return trimmed.slice(1, -1); + } + + return trimmed; + } + function isHeaderKeyStart(text, start) { + let index = start; + while (index < text.length && /\s/.test(text[index])) index++; + + if (text[index] === '"' || text[index] === "'") { + index = readQuotedHeaderKey(text, index); + if (index === -1) return false; + } else { + const keyStart = index; + while ( + index < text.length && + /[!#$%&'*+\-.^_|~0-9A-Za-z]/.test(text[index]) + ) + index++; + if (index === keyStart) return false; + } + + while (index < text.length && /\s/.test(text[index])) index++; + return text[index] === ":"; + } + function isHeaderValueQuoteEnd(text, index) { + let cursor = index + 1; + while (cursor < text.length && /\s/.test(text[cursor])) cursor++; + + return ( + cursor >= text.length || + text[cursor] === "," || + (text[cursor] === ";" && isHeaderKeyStart(text, cursor + 1)) + ); + } + function findHeaderSeparator(pair) { + let quote = ""; + + for (let index = 0; index < pair.length; index++) { + const char = pair[index]; + + if (quote) { + if (char === "\\" && index + 1 < pair.length) { + index++; + continue; + } + if (char === quote) { + quote = ""; + } + continue; + } + + if (char === '"' || char === "'") { + quote = char; + continue; + } + + if (char === ":") { + return index; + } + } + + return -1; + } + function readUnquotedHeadersEnd(text, start) { + let index = start; + let quote = ""; + let quoteRole = ""; + let seenSeparator = false; + + while (index < text.length) { + const char = text[index]; + + if (quote) { + if (char === "\\" && index + 1 < text.length) { + index += 2; + continue; + } + if (char === quote) { + if ( + quoteRole === "key" || + isHeaderValueQuoteEnd(text, index) + ) { + quote = ""; + quoteRole = ""; + } + } + index++; + continue; + } + + if (char === '"' || char === "'") { + quote = char; + quoteRole = seenSeparator ? "value" : "key"; + index++; + continue; + } + + if (char === ":" && !seenSeparator) { + seenSeparator = true; + index++; + continue; + } + + if (char === ";" && isHeaderKeyStart(text, index + 1)) { + seenSeparator = false; + index++; + continue; + } + + if (char === ",") break; + index++; + } + + return index; + } + function readQuotedHeadersEnd(text, start) { + const quote = text[start]; + let index = start + 1; + + while (index < text.length) { + if (text[index] === quote && !isEscaped(text, index)) { + let cursor = index + 1; + while (cursor < text.length && /\s/.test(text[cursor])) cursor++; + if (cursor >= text.length || text[cursor] === ",") { + return index + 1; + } + } + index++; + } + + return text.length; + } + function readHeadersEnd(text, start) { + let index = start; + while (index < text.length && /\s/.test(text[index])) index++; + + if ( + (text[index] === '"' || text[index] === "'") && + !startsWithQuotedHeaderKey(text.slice(index)) + ) { + return readQuotedHeadersEnd(text, index); + } + + return readUnquotedHeadersEnd(text, start); + } + function splitHeaders(headers) { + const result = []; + let start = 0; + let quote = ""; + let quoteRole = ""; + let seenSeparator = false; + + for (let index = 0; index < headers.length; index++) { + const char = headers[index]; + + if (quote) { + if (char === "\\" && index + 1 < headers.length) { + index++; + continue; + } + if (char === quote) { + if ( + quoteRole === "key" || + isHeaderValueQuoteEnd(headers, index) + ) { + quote = ""; + quoteRole = ""; + } + } + continue; + } + + if (char === '"' || char === "'") { + quote = char; + quoteRole = seenSeparator ? "value" : "key"; + continue; + } + + if (char === ":" && !seenSeparator) { + seenSeparator = true; + continue; + } + + if (char === ";" && isHeaderKeyStart(headers, index + 1)) { + result.push(headers.slice(start, index)); + start = index + 1; + seenSeparator = false; + } + } + + result.push(headers.slice(start)); + return result; + } function parseHeaders(headers) { const result = {}; - headers.split(";").forEach((pair) => { - const index = pair.indexOf(":"); + splitHeaders(stripOuterHeadersQuotes(headers)).forEach((pair) => { + const index = findHeaderSeparator(pair); if (index === -1) return; - const key = pair.slice(0, index).trim(); - const value = pair - .slice(index + 1) - .trim() - .replace(/^"(.*?)"$/, "$1") - .replace(/^'(.*?)'$/, "$1"); + const key = stripQuotes(pair.slice(0, index)); + const value = stripQuotes(pair.slice(index + 1)); if (key) { result[key] = value; @@ -250,7 +505,14 @@ ws_headers = comma "ws-headers" equals headers:$[^,]+ { obfs["ws-headers"] = result; } ws_path = comma "ws-path" equals path:uri { obfs.path = path.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); } -headers = comma "headers" equals headers:$[^,]+ { proxy.headers = parseHeaders(headers); } +headers = comma "headers" equals & { + const start = peg$currPos; + const index = readHeadersEnd(input, start); + + $.headers = input.substring(start, index); + peg$currPos = index; + return $.headers.trim().length > 0; +} { proxy.headers = parseHeaders($.headers); } obfs = comma "obfs" equals type:("http"/"tls") { obfs.type = type; } obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); }; diff --git a/backend/src/core/proxy-utils/producers/surge.js b/backend/src/core/proxy-utils/producers/surge.js index 2127fc0e..576d16df 100644 --- a/backend/src/core/proxy-utils/producers/surge.js +++ b/backend/src/core/proxy-utils/producers/surge.js @@ -887,7 +887,7 @@ function socks5(proxy) { function appendHeaders(result, proxy) { const value = formatHeaders(proxy.headers); if (isNotBlank(value)) { - result.append(`,headers=${value}`); + result.append(`,headers="${value}"`); } } @@ -898,10 +898,14 @@ function formatHeaders(headers) { return Object.entries(headers) .filter(([key, value]) => isNotBlank(key) && value != null) - .map(([key, value]) => `${key}:${value}`) + .map(([key, value]) => `${key}:"${escapeHeaderValue(value)}"`) .join(';'); } +function escapeHeaderValue(value) { + return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"'); +} + function snell(proxy) { const result = new Result(proxy); result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`); diff --git a/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js b/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js index 6e649c53..8bc9fc53 100644 --- a/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js +++ b/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js @@ -2893,6 +2893,90 @@ describe('Platform raw-format parser coverage', function () { 'skip-cert-verify': true, }, }, + { + title: 'keeps quoted Surge headers with semicolons inside User-Agent values', + input: '1=http,163.177.17.6,443,headers="Host:153.3.236.22:443;X-T5-Auth:683556433;Connection:Keep-Alive;User-Agent:okhttp/3.11.0 Dalvik/2.1.0 (Linux; U; Android 11; Redmi K30 5G Build/RKQ1.200826.002) baiduboxapp/11.0.5.12 (Baidu; P1 11)"', + expected: { + type: 'http', + name: '1', + server: '163.177.17.6', + port: 443, + headers: { + Host: '153.3.236.22:443', + 'X-T5-Auth': '683556433', + Connection: 'Keep-Alive', + 'User-Agent': + 'okhttp/3.11.0 Dalvik/2.1.0 (Linux; U; Android 11; Redmi K30 5G Build/RKQ1.200826.002) baiduboxapp/11.0.5.12 (Baidu; P1 11)', + }, + }, + }, + { + title: 'parses quoted Surge header keys and values', + input: `Surge Quoted Headers = https,quoted.example.com,443,headers='Host':'153.3.236.22:443';"X-T5-Auth":"683556433";Connection:"Keep-Alive";"User-Agent":"okhttp/3.11.0 Dalvik/2.1.0 (Linux; U; Android 11; Redmi K30 5G Build/RKQ1.200826.002) baiduboxapp/11.0.5.12 (Baidu; P1 11)",sni=sni.example.com`, + expected: { + type: 'http', + name: 'Surge Quoted Headers', + server: 'quoted.example.com', + port: 443, + tls: true, + headers: { + Host: '153.3.236.22:443', + 'X-T5-Auth': '683556433', + Connection: 'Keep-Alive', + 'User-Agent': + 'okhttp/3.11.0 Dalvik/2.1.0 (Linux; U; Android 11; Redmi K30 5G Build/RKQ1.200826.002) baiduboxapp/11.0.5.12 (Baidu; P1 11)', + }, + sni: 'sni.example.com', + }, + }, + { + title: 'parses Surge headers with nested quote values containing commas', + input: `Surge Nested Headers = https,nested.example.com,443,headers="Host:"nested.example.com";X-Comma:"a,b";User-Agent:"client/1.0 (Linux; U; Android 11)"",sni=sni.example.com`, + expected: { + type: 'http', + name: 'Surge Nested Headers', + server: 'nested.example.com', + port: 443, + tls: true, + headers: { + Host: 'nested.example.com', + 'X-Comma': 'a,b', + 'User-Agent': 'client/1.0 (Linux; U; Android 11)', + }, + sni: 'sni.example.com', + }, + }, + { + title: 'parses Surge headers with nested quote values containing quote characters', + input: `Surge Nested Quote Headers = https,quote.example.com,443,headers="X-Quote:"a"b";X-Semi:"x;y"",sni=sni.example.com`, + expected: { + type: 'http', + name: 'Surge Nested Quote Headers', + server: 'quote.example.com', + port: 443, + tls: true, + headers: { + 'X-Quote': 'a"b', + 'X-Semi': 'x;y', + }, + sni: 'sni.example.com', + }, + }, + { + title: 'parses unwrapped Surge headers that start with quoted keys', + input: `Surge Quoted Key Start = http,quoted-key.example.com,8080,headers='Host':'quoted-key.example.com';"X-Token":"abc",test-url=http://example.com`, + expected: { + type: 'http', + name: 'Surge Quoted Key Start', + server: 'quoted-key.example.com', + port: 8080, + headers: { + Host: 'quoted-key.example.com', + 'X-Token': 'abc', + }, + 'test-url': 'http://example.com', + }, + }, { title: 'parses ssh lines', input: 'Surge SSH = ssh,surge-ssh.example.com,22,user,pass,server-fingerprint=sshfp', diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index 0213ead8..f04aad69 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -508,13 +508,50 @@ describe('Proxy text producers', function () { ); expect(output.split('\n')).to.deep.equal([ - 'Surge HTTP Headers=http,http.example.com,8080,username="user",password="pass",headers=X-Client:Surge;X-Token:abc', - 'Surge HTTPS Headers=https,https.example.com,443,headers=X-Padding:,sni="sni.example.com"', - 'Surge H2 Headers=h2-connect,h2.example.com,443,headers=X-Padding:,sni="sni.example.com"', - 'Surge Trust Headers=trust-tunnel,trust.example.com,443,username="user",password="pass",headers=X-Client:Surge,sni="sni.example.com"', + 'Surge HTTP Headers=http,http.example.com,8080,username="user",password="pass",headers="X-Client:"Surge";X-Token:"abc""', + 'Surge HTTPS Headers=https,https.example.com,443,headers="X-Padding:""",sni="sni.example.com"', + 'Surge H2 Headers=h2-connect,h2.example.com,443,headers="X-Padding:""",sni="sni.example.com"', + 'Surge Trust Headers=trust-tunnel,trust.example.com,443,username="user",password="pass",headers="X-Client:"Surge"",sni="sni.example.com"', ]); }); + it('round-trips Surge root headers with nested quotes and separators', function () { + const output = ProxyUtils.produce( + [ + { + type: 'http', + name: 'Surge Nested Headers', + server: 'nested.example.com', + port: 443, + tls: true, + sni: 'sni.example.com', + headers: { + Host: 'nested.example.com', + 'X-Comma': 'a,b', + 'User-Agent': 'client/1.0 (Linux; U; Android 11)', + 'X-Quote': 'a",b', + 'X-Backslash': 'c\\d', + }, + }, + ], + 'Surge', + 'external', + ); + + const [proxy] = ProxyUtils.parse(output); + + expect(proxy.headers).to.deep.equal({ + Host: 'nested.example.com', + 'X-Comma': 'a,b', + 'User-Agent': 'client/1.0 (Linux; U; Android 11)', + 'X-Quote': 'a",b', + 'X-Backslash': 'c\\d', + }); + expect(output).to.include(String.raw`X-Quote:"a\",b"`); + expect(output).to.include(String.raw`X-Backslash:"c\\d"`); + expect(proxy.sni).to.equal('sni.example.com'); + }); + it('filters root proxy headers for unsupported text targets with an error log', function () { const { result, errors } = captureErrors(() => ProxyUtils.produce(