diff --git a/backend/package.json b/backend/package.json index 37c4b0ef..b75267d0 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.44.5", + "version": "2.44.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/preprocessors/index.js b/backend/src/core/proxy-utils/preprocessors/index.js index 317d6a58..15e5fd73 100644 --- a/backend/src/core/proxy-utils/preprocessors/index.js +++ b/backend/src/core/proxy-utils/preprocessors/index.js @@ -1,40 +1,99 @@ import { safeLoad } from '@/utils/yaml'; import { Base64 } from 'js-base64'; +import { isAlias, isScalar, isSeq, parseDocument, visit } from 'yaml'; import $ from '@/core/app'; export function normalizeClashYaml(raw) { - if ( - typeof raw !== 'string' || - !raw.includes('proxies:') || - !raw.includes('short-id:') - ) { + if (typeof raw !== 'string' || !raw.includes('short-id')) { return raw; } + let document; try { - const content = safeLoad(raw); - if (!Array.isArray(content.proxies) || content.proxies.length === 0) + document = parseDocument(raw, { + merge: true, + logLevel: 'error', + }); + // legacy ! 可由 safeLoad 恢复;AST 仅用于定位原文。 + const content = + document.errors.length > 0 ? safeLoad(raw) : document.toJS(); + if ( + ![content.proxies, content.listeners].some( + (items) => Array.isArray(items) && items.length > 0, + ) + ) return raw; } catch (e) { return raw; } - // 防止 VLESS 节点 reality-opts 里的 short-id 被 YAML 标量推断成数字 - // 例如 08 / 0088 在部分内核重新解析时会触发 invalid REALITY short ID - return raw.replace(/short-id:([ \t]*[^#\n,}]*)/g, (matched, value) => { - const afterTrim = value.trim(); - - if (!afterTrim || afterTrim === '') { - return 'short-id: ""'; - } - - if (/^(['"]).*\1$/.test(afterTrim)) { - return `short-id: ${afterTrim}`; - } else if (['null'].includes(afterTrim)) { - return `short-id: ${afterTrim}`; - } else { - return `short-id: "${afterTrim}"`; - } + const anchors = new Map(); + const aliases = new Map(); + visit(document, { + Node(_, node) { + if (isAlias(node)) { + aliases.set(node.range[0], anchors.get(node.source)); + } else if (node.anchor) { + anchors.set(node.anchor, node); + } + }, }); + const resolveAlias = (node) => + isAlias(node) ? aliases.get(node.range[0]) : node; + const needsQuotes = (node) => + isScalar(node) && + typeof node.value !== 'string' && + node.value !== null && + !node.tag && + node.source; + const realityConfigs = new Set(); + visit(document, { + Pair(_, { key, value }) { + const name = resolveAlias(key)?.value; + if (['reality-opts', 'reality-config'].includes(name)) { + realityConfigs.add(value); + } + }, + }); + // alias 和 merge 引用的节点也属于 REALITY 上下文。 + for (const config of realityConfigs) { + visit(config, { + Alias(_, alias) { + realityConfigs.add(resolveAlias(alias)); + }, + }); + } + + const shortIds = new Set(); + visit(document, { + Pair(_, { key, value }, path) { + if ( + resolveAlias(key)?.value === 'short-id' && + path.some((node) => realityConfigs.has(node)) + ) { + shortIds.add(value); + } + }, + }); + const replacements = new Map(); + // shortcut: 直接修改 anchor;跨字段共享时若需保留原类型,再隔离引用。 + for (const value of shortIds) { + const node = resolveAlias(value); + if (isSeq(node)) { + for (const item of node.items) shortIds.add(item); + } else if (needsQuotes(node)) { + replacements.set(node, JSON.stringify(node.source)); + } + } + + const chunks = []; + let offset = 0; + for (const [node, content] of [...replacements].sort( + ([left], [right]) => left.range[0] - right.range[0], + )) { + chunks.push(raw.slice(offset, node.range[0]), content); + offset = node.range[1]; + } + return chunks.join('') + raw.slice(offset); } function HTML() { diff --git a/backend/src/test/proxy-preprocessors/preprocessors.spec.js b/backend/src/test/proxy-preprocessors/preprocessors.spec.js index ab3164f9..9c5746aa 100644 --- a/backend/src/test/proxy-preprocessors/preprocessors.spec.js +++ b/backend/src/test/proxy-preprocessors/preprocessors.spec.js @@ -1,10 +1,12 @@ import { expect } from 'chai'; import { Base64 } from 'js-base64'; import { describe, it } from 'mocha'; +import { Alias } from 'yaml'; import PREPROCESSORS, { normalizeClashYaml, } from '@/core/proxy-utils/preprocessors'; +import { safeLoad } from '@/utils/yaml'; function getPreprocessor(name) { const processor = PREPROCESSORS.find((item) => item.name === name); @@ -47,6 +49,331 @@ describe('Proxy preprocessors', function () { expect(output).to.include('short-id: null'); }); + it('limits scalar normalization to reality options', function () { + const input = `metadata: {short-id: 1234} +proxies: + - name: test + short-id: 5678 + reality-opts: {short-id: 0088} +`; + + expect(normalizeClashYaml(input)).to.equal( + input.replace('short-id: 0088', 'short-id: "0088"'), + ); + }); + + it('resolves aliases without rescanning the document for each use', function () { + const resolve = Alias.prototype.resolve; + const contexts = []; + Alias.prototype.resolve = function (document, context) { + contexts.push(context); + return resolve.call(this, document, context); + }; + + try { + const input = `opts: &opts {short-id: 0088} +proxies: + - reality-opts: *opts + - reality-opts: *opts +`; + + expect(normalizeClashYaml(input)).to.include( + 'short-id: "0088"', + ); + expect(contexts.every((context) => context != null)).to.equal( + true, + ); + } finally { + Alias.prototype.resolve = resolve; + } + }); + + for (const [name, input] of [ + [ + 'scalar alias', + `id: &id 0011 +proxies: [{reality-opts: {short-id: *id}}] +`, + ], + [ + 'multiple merges', + `base: &base {short-id: 0011} +mid: &mid {<<: *base} +opts: &opts {<<: *mid} +proxies: [{reality-opts: *opts}] +`, + ], + [ + 'proxy template merge sequence', + `template: &template {reality-opts: {short-id: 0011}} +templates: &templates [*template] +node: &node {<<: *templates} +proxies: [*node] +`, + ], + [ + 'inherited profile', + `opts: &opts {short-id: 0011} +node: &node {reality-opts: *opts} +nodes: &nodes [*node] +profile: &profile {proxies: *nodes} +inherited: &inherited {<<: *profile} +<<: *inherited +`, + ], + ]) { + it(`normalizes short-ids through a ${name}`, function () { + const output = normalizeClashYaml(input); + + expect(output).to.equal(input.replace('0011', '"0011"')); + expect( + safeLoad(output).proxies[0]['reality-opts']['short-id'], + ).to.equal('0011'); + expect(normalizeClashYaml(output)).to.equal(output); + }); + } + + for (const [field, options, shortId, expected] of [ + ['listeners', 'reality-config', '[0011]', ['0011']], + ['proxies', 'reality-opts', '0011', '0011'], + ]) { + it(`normalizes ${field} inherited through an aliased merge sequence`, function () { + const input = `profile: &profile {${field}: [{${options}: {short-id: ${shortId}}}]} +profiles: &profiles [*profile] +<<: *profiles +`; + const output = normalizeClashYaml(input); + + expect(output).to.equal(input.replace('0011', '"0011"')); + expect( + safeLoad(output)[field][0][options]['short-id'], + ).to.deep.equal(expected); + expect(normalizeClashYaml(output)).to.equal(output); + }); + } + + it('preserves the YAML version when quoting anchored short-ids', function () { + const input = `%YAML 1.1 +--- +ids: &ids [0011] +listeners: [{reality-config: {short-id: *ids}}] +`; + const output = normalizeClashYaml(input); + + expect(output).to.equal(input.replace('0011', '"0011"')); + expect( + safeLoad(output).listeners[0]['reality-config']['short-id'], + ).to.deep.equal(['0011']); + expect(normalizeClashYaml(output)).to.equal(output); + }); + + it('preserves explicit tags and nulls in aliased short-id lists', function () { + const input = `ids: &ids [0088, !!int 0011, !!str 0088, null] +listeners: [{reality-config: {short-id: *ids}}] +`; + const output = normalizeClashYaml(input); + + expect(output).to.equal(input.replace('[0088,', '["0088",')); + expect( + safeLoad(output).listeners[0]['reality-config']['short-id'], + ).to.deep.equal(['0088', 11, '0088', null]); + expect(normalizeClashYaml(output)).to.equal(output); + }); + + for (const [name, definition, reference, expected] of [ + ['scalar comment', 'ids: &ids 0011 # keep', '[*ids]', ['0011']], + ['list comment', 'ids: &ids [0011] # keep', '*ids', ['0011']], + ['item comment', 'ids: &ids [0011 # keep\n]', '*ids', ['0011']], + [ + 'leading comment', + 'ids: &ids\n # keep\n - 0011', + '*ids', + ['0011'], + ], + [ + 'blank line', + 'ids: &ids\n - 0011\n\n - 0022', + '*ids', + ['0011', '0022'], + ], + ]) { + it(`quotes a short-id anchor with a ${name}`, function () { + const input = `${definition}\nlisteners: [{reality-config: {short-id: ${reference}}}]\n`; + const output = normalizeClashYaml(input); + const content = safeLoad(output); + + expect(output).to.equal( + expected.reduce( + (text, id) => text.replace(id, JSON.stringify(id)), + input, + ), + ); + expect( + content.listeners[0]['reality-config']['short-id'], + ).to.deep.equal(expected); + expect(normalizeClashYaml(output)).to.equal(output); + }); + } + + for (const [name, proxies, ids] of [ + [ + 'listener-only block', + '', + '\n - 11111111111\n - 0000000000000001\n - 9007199254740993', + ], + [ + 'empty proxies flow', + 'proxies: []\n', + ' [11111111111, 0000000000000001, 9007199254740993]', + ], + [ + 'nonempty proxies block', + 'proxies: [{name: test}]\n', + '\n - 11111111111\n - 0000000000000001\n - 9007199254740993', + ], + ]) { + it(`quotes numeric listener short-id items in ${name}`, function () { + const input = `${proxies}listeners: + - name: relay-proxy + type: vless + reality-config: + short-id:${ids} +`; + const expected = [ + '11111111111', + '0000000000000001', + '9007199254740993', + ]; + const output = normalizeClashYaml(input); + + expect(output).to.equal( + expected.reduce( + (content, id) => content.replace(id, `"${id}"`), + input, + ), + ); + expect( + safeLoad(output).listeners[0]['reality-config']['short-id'], + ).to.deep.equal(expected); + }); + } + + it('quotes numeric items in aliased listener short-id lists', function () { + const input = `ids: &ids [11111111111, 0000000000000001] +listeners: + - reality-config: {short-id: *ids} + - reality-config: {short-id: *ids} +`; + + const output = normalizeClashYaml(input); + const content = safeLoad(output); + + expect(output).to.include( + 'ids: &ids ["11111111111", "0000000000000001"]', + ); + expect(content.ids).to.deep.equal([ + '11111111111', + '0000000000000001', + ]); + for (const listener of content.listeners) { + expect(listener['reality-config']['short-id']).to.deep.equal([ + '11111111111', + '0000000000000001', + ]); + } + }); + + for (const value of [ + 'abcdef0123456789', + '!!str 0088', + '!!int 0088', + '!custom 0088', + ]) { + it(`preserves resolved strings and explicit tags: ${value}`, function () { + const input = `proxies: + - name: test + reality-opts: {short-id: ${value}} +`; + + expect(normalizeClashYaml(input)).to.equal(input); + }); + } + + for (const [name, value, expected] of [ + ['block', '\n - 6a0f0e0ede903cad', ['6a0f0e0ede903cad']], + [ + 'commented block', + ' # ids\n - 6a0f0e0ede903cad', + ['6a0f0e0ede903cad'], + ], + [ + 'anchored block', + ' &ids\n - 6a0f0e0ede903cad', + ['6a0f0e0ede903cad'], + ], + ['empty flow', ' []', []], + ['flow', ' [6a0f0e0ede903cad, "08"]', ['6a0f0e0ede903cad', '08']], + ['anchored flow', ' &ids [6a0f0e0ede903cad]', ['6a0f0e0ede903cad']], + ]) { + it(`preserves ${name} reality short-id sequences`, function () { + const input = `proxies: + - name: test + type: vless + reality-opts: + short-id: 0088 +listeners: + - type: vless + reality-config: + short-id:${value} +`; + + const output = normalizeClashYaml(input); + const content = safeLoad(output); + + expect(output).to.equal( + input.replace('short-id: 0088', 'short-id: "0088"'), + ); + expect(content.proxies[0]['reality-opts']['short-id']).to.equal( + '0088', + ); + expect( + content.listeners[0]['reality-config']['short-id'], + ).to.deep.equal(expected); + }); + } + + it('preserves aliases, comments, strings and null values', function () { + const input = `# short-id: 0011 +proxies: + - {name: test, reality-opts: {short-id: 0088}} +short-ids: &ids [6a0f0e0ede903cad] +listeners: + - reality-config: {short-id: *ids} +description: 'short-id: 0022' +script: | + short-id: 0033 +empty: + short-id: +`; + + expect(normalizeClashYaml(input)).to.equal( + input.replace('short-id: 0088', 'short-id: "0088"'), + ); + }); + + it('keeps literal merge-looking keys valid when normalizing aliases', function () { + const input = `opts: &opts {short-id: 0011, "<<": keep} +metadata: *opts +proxies: [{reality-opts: *opts}] +`; + const output = normalizeClashYaml(input); + + expect(safeLoad(output).metadata['<<']).to.equal('keep'); + expect(output).to.equal( + input.replace('short-id: 0011', 'short-id: "0011"'), + ); + }); + it('keeps non-clash or invalid yaml input untouched', function () { const invalid = 'proxies:\n - name: broken\n short-id: ['; const unrelated = 'ss://YWVzLTEyOC1nY206c2VjcmV0@example.com:8388'; @@ -114,6 +441,100 @@ describe('Proxy preprocessors', function () { }); describe('Clash preprocessor', function () { + it('preserves short-ids when REALITY field names are aliases', function () { + const processor = getPreprocessor('Clash Pre-processor'); + const input = `proxies: + - name: first + &opts reality-opts: {&sid short-id: 0088} + - name: second + *opts : {*sid : 0011} +`; + + const proxies = processor + .parse(input) + .trim() + .split('\n') + .map(JSON.parse); + + expect( + proxies.map((proxy) => proxy['reality-opts']['short-id']), + ).to.deep.equal(['0088', '0011']); + }); + + it('resolves redefined anchors at each alias position', function () { + const processor = getPreprocessor('Clash Pre-processor'); + const input = `first: &opts {short-id: 0088} +proxies: + - reality-opts: *opts + - reality-opts: &opts {short-id: 0011} + - reality-opts: *opts +`; + + const proxies = processor + .parse(input) + .trim() + .split('\n') + .map(JSON.parse); + + expect( + proxies.map((proxy) => proxy['reality-opts']['short-id']), + ).to.deep.equal(['0088', '0011', '0011']); + }); + + for (const merge of [false, true]) { + it(`preserves short-ids in ${ + merge ? 'merged' : 'aliased' + } reality options`, function () { + const processor = getPreprocessor('Clash Pre-processor'); + const raw = `first: &first {short-id: 0011} +second: &second {short-id: 0022} +proxies: + - name: second + reality-opts: *second + - name: first + reality-opts: ${merge ? '{<<: *first}' : '*first'} + - name: second-again + reality-opts: *second +`; + + expect(normalizeClashYaml(raw)).to.equal( + raw + .replace('short-id: 0011', 'short-id: "0011"') + .replace('short-id: 0022', 'short-id: "0022"'), + ); + const proxies = processor + .parse(raw) + .trim() + .split('\n') + .map(JSON.parse); + + expect( + proxies.map((p) => p['reality-opts']['short-id']), + ).to.deep.equal(['0022', '0011', '0022']); + }); + } + + it('preserves numeric short-ids through legacy tag recovery', function () { + const processor = getPreprocessor('Clash Pre-processor'); + const raw = `proxies: + - name: !Legacy + type: vless + server: !example.com + reality-opts: + short-id: 0088 +`; + + expect(processor.test(raw)).to.equal(true); + expect(normalizeClashYaml(raw)).to.equal( + raw.replace('short-id: 0088', 'short-id: "0088"'), + ); + const proxy = JSON.parse(processor.parse(raw)); + + expect(proxy.name).to.equal('Legacy'); + expect(proxy.server).to.equal('example.com'); + expect(proxy['reality-opts']['short-id']).to.equal('0088'); + }); + it('accepts an empty proxies field', function () { const processor = getPreprocessor('Clash Pre-processor'); const raw = `proxies: diff --git a/backend/src/test/restful/mihomo-config.spec.js b/backend/src/test/restful/mihomo-config.spec.js index 00f2a47a..b8e67bee 100644 --- a/backend/src/test/restful/mihomo-config.spec.js +++ b/backend/src/test/restful/mihomo-config.spec.js @@ -5,6 +5,7 @@ import path from 'path'; import { after, afterEach, before, beforeEach, describe, it } from 'mocha'; import { FILES_KEY, SUBS_KEY } from '@/constants'; +import { safeLoad } from '@/utils/yaml'; let $; let registerFileRoutes; @@ -302,6 +303,138 @@ describe('mihomo config file routes', function () { expect(res.sent.data.processed).to.include('name: Supported'); }); + it('preserves listener short-id lists added by scripts in downloads and previews', async function () { + const file = { + name: 'reality-config-file', + type: 'mihomoConfig', + sourceType: 'local', + content: 'proxies:\n - {name: Direct, type: direct}\n', + process: [ + { + type: 'Script Operator', + args: { + mode: 'script', + content: ` +const yaml = ProxyUtils.yaml.safeLoad($content); +yaml.listeners = [{ + type: 'vless', + 'reality-config': { 'short-id': ['6a0f0e0ede903cad', 11111111111] }, +}]; +$content = ProxyUtils.yaml.dump(yaml); +`, + }, + }, + ], + }; + state[FILES_KEY] = [file]; + + const downloaded = await requestFile(file.name); + const previewed = await previewFile(file); + + expect(downloaded.statusCode).to.equal(200); + expect(previewed.sent.status).to.equal('success'); + for (const output of [downloaded.sent, previewed.sent.data.processed]) { + const content = safeLoad(output); + expect( + content.listeners[0]['reality-config']['short-id'], + ).to.deep.equal(['6a0f0e0ede903cad', '11111111111']); + } + }); + + it('quotes numeric listener short-id items in downloads and previews without proxies', async function () { + const file = { + name: 'listener-only-file', + type: 'mihomoConfig', + sourceType: 'local', + content: `listeners: + - name: relay-proxy + type: vless + port: 4443 + listen: 0.0.0.0 + users: + - username: u + uuid: xxxx + flow: xtls-rprx-vision + reality-config: + dest: 127.0.0.1:443 + server-names: + - example.com + private-key: xxxx + short-id: + - 11111111111 +`, + process: [], + }; + state[FILES_KEY] = [file]; + + const downloaded = await requestFile(file.name); + const previewed = await previewFile(file); + + expect(downloaded.statusCode).to.equal(200); + expect(previewed.sent.status).to.equal('success'); + for (const output of [downloaded.sent, previewed.sent.data.processed]) { + expect(output).to.equal( + file.content.replace('11111111111', '"11111111111"'), + ); + expect( + safeLoad(output).listeners[0]['reality-config']['short-id'], + ).to.deep.equal(['11111111111']); + } + }); + + it('keeps commented short-id aliases valid in file downloads and previews', async function () { + const file = { + name: 'commented-alias-file', + type: 'mihomoConfig', + sourceType: 'local', + content: + 'ids: &ids 0011 # keep\nlisteners: [{reality-config: {short-id: [*ids]}}]\n', + process: [], + }; + state[FILES_KEY] = [file]; + + const downloaded = await requestFile(file.name); + const previewed = await previewFile(file); + + expect(downloaded.statusCode).to.equal(200); + expect(previewed.sent.status).to.equal('success'); + for (const output of [downloaded.sent, previewed.sent.data.processed]) { + expect(output.startsWith('ids: &ids "0011" # keep\n')).to.equal( + true, + ); + expect( + safeLoad(output).listeners[0]['reality-config']['short-id'], + ).to.deep.equal(['0011']); + } + }); + + it('normalizes listeners from an aliased merge sequence in downloads and previews', async function () { + const file = { + name: 'merge-sequence-file', + type: 'mihomoConfig', + sourceType: 'local', + content: `profile: &profile {listeners: [{reality-config: {short-id: [0011]}}]} +profiles: &profiles [*profile] +<<: *profiles +`, + process: [], + }; + state[FILES_KEY] = [file]; + + const downloaded = await requestFile(file.name); + const previewed = await previewFile(file); + + expect(downloaded.statusCode).to.equal(200); + expect(previewed.sent.status).to.equal('success'); + for (const output of [downloaded.sent, previewed.sent.data.processed]) { + const content = safeLoad(output); + expect( + content.listeners[0]['reality-config']['short-id'], + ).to.deep.equal(['0011']); + expect(output).to.equal(file.content.replace('0011', '"0011"')); + } + }); + it('keeps unsupported proxies for YAML mihomoConfig overrides when enabled', async function () { state[FILES_KEY] = [ {