feat: 兼容 Surge headers/ws-headers 的嵌套引号与逗号值,优化解析和输出

- Surge parser 重构 headers/ws-headers 分隔与引号边界识别,新增可配置分隔符并修复带嵌套引号/逗号值时的误切分问题(含 vmess ws-headers 的 pipe 场景)
- Surge producer 调整 headers 与 ws-headers 的序列化规则,统一用原值加引号输出并避免额外转义导致的值变化
- 补充/更新 parser 与 producer 测试用例,覆盖嵌套引号、逗号值与 ws-headers round-trip
This commit is contained in:
xream committed 2026-05-27 19:56:17 +08:00
1 parent 10a80e3bd2
commit b6969e7c2f
5 files changed
+183 -98

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.23.23",
"version": "2.23.25",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"packageManager": "pnpm@11.0.9",
@@ -42,21 +42,10 @@ const grammars = String.raw`
(quote === '"' || quote === "'") &&
trimmed[trimmed.length - 1] === quote
) {
return trimmed.slice(1, -1).replace(/\\(["'\\])/g, "$1");
return trimmed.slice(1, -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;
return trimmed;
}
function readQuotedHeaderKey(text, start) {
const quote = text[start];
@@ -65,11 +54,6 @@ const grammars = String.raw`
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;
}
@@ -125,15 +109,35 @@ const grammars = String.raw`
while (index < text.length && /\s/.test(text[index])) index++;
return text[index] === ":";
}
function isHeaderValueQuoteEnd(text, index) {
function isOptionStart(text, start) {
let index = start;
while (index < text.length && /\s/.test(text[index])) index++;
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, pairSeparator, allowCommaEnd, containerQuote) {
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))
);
if (cursor >= text.length) return true;
if (allowCommaEnd && text[cursor] === "," && isOptionStart(text, cursor + 1)) {
return true;
}
if (text[cursor] === pairSeparator && isHeaderKeyStart(text, cursor + 1)) {
return true;
}
if (containerQuote && text[cursor] === containerQuote) {
let next = cursor + 1;
while (next < text.length && /\s/.test(text[next])) next++;
return next >= text.length || text[next] === ",";
}
return false;
}
function findHeaderSeparator(pair) {
let quote = "";
@@ -142,10 +146,6 @@ const grammars = String.raw`
const char = pair[index];
if (quote) {
if (char === "\\" && index + 1 < pair.length) {
index++;
continue;
}
if (char === quote) {
quote = "";
}
@@ -164,7 +164,7 @@ const grammars = String.raw`
return -1;
}
function readUnquotedHeadersEnd(text, start) {
function readUnquotedHeadersEnd(text, start, pairSeparator) {
let index = start;
let quote = "";
let quoteRole = "";
@@ -174,14 +174,10 @@ const grammars = String.raw`
const char = text[index];
if (quote) {
if (char === "\\" && index + 1 < text.length) {
index += 2;
continue;
}
if (char === quote) {
if (
quoteRole === "key" ||
isHeaderValueQuoteEnd(text, index)
isHeaderValueQuoteEnd(text, index, pairSeparator, true)
) {
quote = "";
quoteRole = "";
@@ -204,7 +200,7 @@ const grammars = String.raw`
continue;
}
if (char === ";" && isHeaderKeyStart(text, index + 1)) {
if (char === pairSeparator && isHeaderKeyStart(text, index + 1)) {
seenSeparator = false;
index++;
continue;
@@ -216,24 +212,62 @@ const grammars = String.raw`
return index;
}
function readQuotedHeadersEnd(text, start) {
function readQuotedHeadersEnd(text, start, pairSeparator) {
const quote = text[start];
let index = start + 1;
let innerQuote = "";
let quoteRole = "";
let seenSeparator = false;
while (index < text.length) {
if (text[index] === quote && !isEscaped(text, index)) {
const char = text[index];
if (innerQuote) {
if (char === innerQuote) {
if (
quoteRole === "key" ||
isHeaderValueQuoteEnd(text, index, pairSeparator, false, quote)
) {
innerQuote = "";
quoteRole = "";
}
}
index++;
continue;
}
if (char === quote) {
let cursor = index + 1;
while (cursor < text.length && /\s/.test(text[cursor])) cursor++;
if (cursor >= text.length || text[cursor] === ",") {
return index + 1;
}
}
if (char === '"' || char === "'") {
innerQuote = char;
quoteRole = seenSeparator ? "value" : "key";
index++;
continue;
}
if (char === ":" && !seenSeparator) {
seenSeparator = true;
index++;
continue;
}
if (char === pairSeparator && isHeaderKeyStart(text, index + 1)) {
seenSeparator = false;
index++;
continue;
}
index++;
}
return text.length;
}
function readHeadersEnd(text, start) {
function readHeadersEnd(text, start, pairSeparator) {
let index = start;
while (index < text.length && /\s/.test(text[index])) index++;
@@ -241,12 +275,12 @@ const grammars = String.raw`
(text[index] === '"' || text[index] === "'") &&
!startsWithQuotedHeaderKey(text.slice(index))
) {
return readQuotedHeadersEnd(text, index);
return readQuotedHeadersEnd(text, index, pairSeparator);
}
return readUnquotedHeadersEnd(text, start);
return readUnquotedHeadersEnd(text, start, pairSeparator);
}
function splitHeaders(headers) {
function splitHeaders(headers, pairSeparator) {
const result = [];
let start = 0;
let quote = "";
@@ -257,14 +291,10 @@ const grammars = String.raw`
const char = headers[index];
if (quote) {
if (char === "\\" && index + 1 < headers.length) {
index++;
continue;
}
if (char === quote) {
if (
quoteRole === "key" ||
isHeaderValueQuoteEnd(headers, index)
isHeaderValueQuoteEnd(headers, index, pairSeparator, false)
) {
quote = "";
quoteRole = "";
@@ -284,7 +314,7 @@ const grammars = String.raw`
continue;
}
if (char === ";" && isHeaderKeyStart(headers, index + 1)) {
if (char === pairSeparator && isHeaderKeyStart(headers, index + 1)) {
result.push(headers.slice(start, index));
start = index + 1;
seenSeparator = false;
@@ -294,9 +324,9 @@ const grammars = String.raw`
result.push(headers.slice(start));
return result;
}
function parseHeaders(headers) {
function parseHeaders(headers, pairSeparator) {
const result = {};
splitHeaders(stripOuterHeadersQuotes(headers)).forEach((pair) => {
splitHeaders(stripOuterHeadersQuotes(headers), pairSeparator).forEach((pair) => {
const index = findHeaderSeparator(pair);
if (index === -1) return;
@@ -496,24 +526,23 @@ method = comma "encrypt-method" equals cipher:cipher {
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
ws = comma "ws" equals flag:bool { obfs.type = "ws"; }
ws_headers = comma "ws-headers" equals headers:$[^,]+ {
const pairs = headers.split("|");
const result = {};
pairs.forEach(pair => {
const [key, value] = pair.trim().split(":");
result[key.trim()] = value.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1');
})
obfs["ws-headers"] = result;
}
ws_path = comma "ws-path" equals path:uri { obfs.path = path.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
headers = comma "headers" equals & {
ws_headers = comma "ws-headers" equals & {
const start = peg$currPos;
const index = readHeadersEnd(input, start);
const index = readHeadersEnd(input, start, "|");
$.headers = input.substring(start, index);
peg$currPos = index;
return $.headers.trim().length > 0;
} { proxy.headers = parseHeaders($.headers); }
} { obfs["ws-headers"] = parseHeaders($.headers, "|"); }
ws_path = comma "ws-path" equals path:uri { obfs.path = path.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
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'); };
+13 -22
View File
@@ -32,16 +32,15 @@ function stripSurgeQuotes(value) {
(quote === '"' || quote === "'") &&
trimmed[trimmed.length - 1] === quote
) {
return trimmed.slice(1, -1).replace(/\\(["'\\])/g, '$1');
return trimmed.slice(1, -1);
}
return trimmed.replace(/\\(["'\\])/g, '$1');
return trimmed;
}
function quoteSurgeValue(value) {
return `"${String(stripSurgeQuotes(value))
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')}"`;
const text = String(stripSurgeQuotes(value));
return `"${text}"`;
}
function hasNonBlankValue(value) {
@@ -961,23 +960,23 @@ function socks5(proxy) {
function appendHeaders(result, proxy) {
const value = formatHeaders(proxy.headers);
if (isNotBlank(value)) {
result.append(`,headers="${value}"`);
result.append(`,headers=${quoteSurgeValue(value)}`);
}
}
function formatHeaders(headers) {
return formatHeaderMap(headers, ';');
}
function formatHeaderMap(headers, separator) {
if (!headers || typeof headers !== 'object') {
return '';
}
return Object.entries(headers)
.filter(([key, value]) => isNotBlank(key) && value != null)
.map(([key, value]) => `${key}:"${escapeHeaderValue(value)}"`)
.join(';');
}
function escapeHeaderValue(value) {
return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
.map(([key, value]) => `${key}:${quoteSurgeValue(value)}`)
.join(separator);
}
function snell(proxy) {
@@ -1458,17 +1457,9 @@ function handleTransport(result, proxy, includeUnsupportedProxy) {
);
if (isPresent(proxy, 'ws-opts.headers')) {
const headers = proxy['ws-opts'].headers;
const value = Object.keys(headers)
.map((k) => {
let v = headers[k];
// if (['Host'].includes(k)) {
v = `"${v}"`;
// }
return `${k}:${v}`;
})
.join('|');
const value = formatHeaderMap(headers, '|');
if (isNotBlank(value)) {
result.append(`,ws-headers=${value}`);
result.append(`,ws-headers=${quoteSurgeValue(value)}`);
}
}
}
@@ -3023,8 +3023,8 @@ describe('Platform raw-format parser coverage', function () {
},
},
{
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)"',
title: 'keeps quoted Surge headers with nested quoted 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',
@@ -3060,7 +3060,7 @@ describe('Platform raw-format parser coverage', function () {
},
{
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`,
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',
@@ -3161,6 +3161,32 @@ describe('Platform raw-format parser coverage', function () {
},
},
},
{
title: 'parses vmess websocket headers with quoted comma values and pipe separators',
input: `Surge VMess WS Headers = vmess,surge-vmess.example.com,443,username=${UUID},ws=true,ws-path=/vmess,ws-headers="Host:"cdn.example.com" | X-Comma:"a,b" | User-Agent:"okhttp/3.11.0 Dalvik/2.1.0 (Linux; U; Android 11)"",skip-cert-verify=true,sni=sni.example.com,tls=true,vmess-aead=true`,
expected: {
type: 'vmess',
name: 'Surge VMess WS Headers',
server: 'surge-vmess.example.com',
port: 443,
uuid: UUID,
aead: true,
alterId: 0,
tls: true,
sni: 'sni.example.com',
'skip-cert-verify': true,
network: 'ws',
'ws-opts': {
path: '/vmess',
headers: {
Host: 'cdn.example.com',
'X-Comma': 'a,b',
'User-Agent':
'okhttp/3.11.0 Dalvik/2.1.0 (Linux; U; Android 11)',
},
},
},
},
{
title: 'parses trojan websocket tls lines',
input: 'Surge Trojan = trojan,surge-trojan.example.com,443,password=secret,ws=true,ws-path=/trojan,ws-headers=Host:cdn.example.com,skip-cert-verify=true,sni=sni.example.com,tls=true',
+49 -10
View File
@@ -637,10 +637,10 @@ 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:"<random-string(16)>"",sni="sni.example.com"',
'Surge H2 Headers=h2-connect,h2.example.com,443,headers="X-Padding:"<random-string(16-32)>"",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:"<random-string(16)>"",sni="sni.example.com"`,
`Surge H2 Headers=h2-connect,h2.example.com,443,headers="X-Padding:"<random-string(16-32)>"",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"`,
]);
});
@@ -678,8 +678,8 @@ describe('Proxy text producers', function () {
);
expect(output.split('\n')).to.deep.equal([
'Surge H2 Max Streams=h2-connect,h2.example.com,443,headers="X-Padding:"<random-string(16-32)>"",max-streams=1,sni="sni.example.com"',
'Surge Trust Max Streams=trust-tunnel,trust.example.com,443,username="user",password="pass",headers="X-Client:"Surge"",max-streams=3,sni="sni.example.com"',
`Surge H2 Max Streams=h2-connect,h2.example.com,443,headers="X-Padding:"<random-string(16-32)>"",max-streams=1,sni="sni.example.com"`,
`Surge Trust Max Streams=trust-tunnel,trust.example.com,443,username="user",password="pass",headers="X-Client:"Surge"",max-streams=3,sni="sni.example.com"`,
]);
});
@@ -732,8 +732,8 @@ describe('Proxy text producers', function () {
const output = ProxyUtils.produce(proxies, 'Surge', 'external');
expect(output.split('\n')).to.deep.equal([
'Surge H2 Round Trip=h2-connect,h2.example.com,443,headers="X-Padding:"<random-string(16-32)>"",max-streams=1,sni="sni.example.com"',
'Surge Trust Round Trip=trust-tunnel,trust.example.com,443,username="user",password="pass",headers="X-Client:"Surge"",max-streams=3,sni="sni.example.com"',
`Surge H2 Round Trip=h2-connect,h2.example.com,443,headers="X-Padding:"<random-string(16-32)>"",max-streams=1,sni="sni.example.com"`,
`Surge Trust Round Trip=trust-tunnel,trust.example.com,443,username="user",password="pass",headers="X-Client:"Surge"",max-streams=3,sni="sni.example.com"`,
]);
});
@@ -769,11 +769,50 @@ describe('Proxy text producers', function () {
'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(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('round-trips Surge websocket headers with pipe separators', function () {
const output = ProxyUtils.produce(
[
{
type: 'vmess',
name: 'Surge WS Headers',
server: 'ws.example.com',
port: 443,
uuid: UUID,
aead: true,
tls: true,
sni: 'sni.example.com',
network: 'ws',
'ws-opts': {
path: '/ws',
headers: {
Host: 'cdn.example.com',
'X-Comma': 'a,b',
'X-Quote': 'a",b',
},
},
},
],
'Surge',
'external',
);
const [proxy] = ProxyUtils.parse(output);
expect(proxy['ws-opts'].headers).to.deep.equal({
Host: 'cdn.example.com',
'X-Comma': 'a,b',
'X-Quote': 'a",b',
});
expect(output).to.include(
String.raw`ws-headers="Host:"cdn.example.com"|X-Comma:"a,b"|X-Quote:"a",b""`,
);
});
it('filters root proxy headers for unsupported text targets with an error log', function () {
const { result, errors } = captureErrors(() =>
ProxyUtils.produce(