feat: 文件 mihomo 配置的来源新增远程/本地, 可作为 mihomo 配置或转换为 mihomo 节点; 文件路由支持参数覆盖

This commit is contained in:
xream committed 2026-06-21 02:19:05 +08:00
1 parent e9625a8844
commit f523002ecb
14 files changed
+1256 -643

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.30.0",
"version": "2.31.0",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"packageManager": "pnpm@11.0.9",
@@ -9,6 +9,7 @@ import $ from '@/core/app';
import { hex_md5 } from '@/vendor/md5';
import { ProxyUtils } from '@/core/proxy-utils';
import { produceArtifact } from '@/restful/sync';
import { isMihomoConfigFile } from '@/utils/file-type';
import { SETTINGS_KEY } from '@/constants';
import YAML from '@/utils/yaml';
@@ -397,7 +398,7 @@ function ScriptOperator(
name: 'Script Operator',
func: async (proxies) => {
let output = proxies;
if (output?.$file?.type === 'mihomoProfile') {
if (isMihomoConfigFile(output?.$file)) {
try {
let patch = YAML.safeLoad(script);
let config;
@@ -438,7 +439,7 @@ function ScriptOperator(
`async function operator(input = [], targetPlatform, context) {
if (input && (input.$files || input.$content)) {
let { $content, $files, $options, $file } = input
if($file.type === 'mihomoProfile') {
if (['mihomoConfig', 'mihomoProfile'].includes($file?.type)) {
${script}
if(typeof main === 'function') {
let config;
@@ -496,7 +497,7 @@ function AddProxiesFromSubscriptionOperator({
position = 'replace',
} = {}) {
const apply = async (input) => {
if (input?.$file?.type !== 'mihomoProfile') return input;
if (!isMihomoConfigFile(input?.$file)) return input;
const config = normalizeMihomoConfig(input.$content);
const currentProxies = getMihomoProfileProxies(config);
@@ -57,13 +57,13 @@ export default function ClashMeta_Producer() {
if (proxy.type === 'h2-connect') {
$.error(
`Mihomo does not support HTTP/2 CONNECT proxy type. Proxy ${proxy.name} has been filtered.`,
`mihomo does not support HTTP/2 CONNECT proxy type. Proxy ${proxy.name} has been filtered.`,
);
return false;
}
if (hasRootHeaders(proxy) && proxy.type === 'trusttunnel') {
$.error(
`Mihomo does not support headers for TrustTunnel proxy ${proxy.name}. Proxy has been filtered.`,
`mihomo does not support headers for TrustTunnel proxy ${proxy.name}. Proxy has been filtered.`,
);
return false;
}
@@ -32,7 +32,7 @@ export default function SurgeMac_Producer() {
throw e;
}
$.log(
`${proxy.name} is not supported on ${targetPlatform}, try to use Mihomo(SurgeMac - External Proxy Program) instead`,
`${proxy.name} is not supported on ${targetPlatform}, try to use mihomo(SurgeMac - External Proxy Program) instead`,
);
return output;
}
+1 -1
View File
@@ -194,7 +194,7 @@ async function doSync(arg = {}, { canUpload = true } = {}) {
if (useMihomoExternal) {
$.info(
`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`,
`手动指定了 target 为 SurgeMac, 将使用 mihomo External`,
);
}
const output = await produceSyncArtifactOutput(
+8 -8
View File
@@ -262,17 +262,17 @@ async function downloadSubscription(req, res) {
$.info(`指定输出易读 YAML: ${prettyYaml}`);
}
if (mihomoMerge) {
$.info(`指定合并 Mihomo External: ${mihomoMerge}`);
$.info(`指定合并 mihomo External: ${mihomoMerge}`);
}
if (mihomoMergeName) {
$.info(`指定合并 Mihomo External 名称: ${mihomoMergeName}`);
$.info(`指定合并 mihomo External 名称: ${mihomoMergeName}`);
}
if (useMihomoExternal) {
$.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`);
$.info(`手动指定了 target 为 SurgeMac, 将使用 mihomo External`);
}
if (mihomoExternal) {
$.info(`手动指定了 Mihomo External 链接参数: ${mihomoExternal}`);
$.info(`手动指定了 mihomo External 链接参数: ${mihomoExternal}`);
}
if (noCache) {
@@ -610,17 +610,17 @@ async function downloadCollection(req, res) {
$.info(`指定输出易读 YAML: ${prettyYaml}`);
}
if (mihomoMerge) {
$.info(`指定合并 Mihomo External: ${mihomoMerge}`);
$.info(`指定合并 mihomo External: ${mihomoMerge}`);
}
if (mihomoMergeName) {
$.info(`指定合并 Mihomo External 名称: ${mihomoMergeName}`);
$.info(`指定合并 mihomo External 名称: ${mihomoMergeName}`);
}
if (useMihomoExternal) {
$.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`);
$.info(`手动指定了 target 为 SurgeMac, 将使用 mihomo External`);
}
if (mihomoExternal) {
$.info(`手动指定了 Mihomo External 链接参数: ${mihomoExternal}`);
$.info(`手动指定了 mihomo External 链接参数: ${mihomoExternal}`);
}
if (noCache) {
$.info(`指定不使用缓存: ${noCache}`);
+197 -33
View File
@@ -25,6 +25,11 @@ import {
import { findShareToken } from '@/restful/token';
import { maskAgeSecretInUrl, normalizeAgePublicKeyConfig } from '@/utils/age';
import { normalizeEditorLanguageConfig } from '@/utils/editor-language';
import {
isMihomoConfigFile,
normalizeFileConfig,
normalizeFileType,
} from '@/utils/file-type';
export default function register($app) {
if (!$.read(FILES_KEY)) $.write([], FILES_KEY);
@@ -66,6 +71,11 @@ async function getFile(req, res, next) {
mergeSources,
ignoreFailedRemoteFile,
includeUnsupportedProxy,
type: fileType,
source: fileSource,
sourceType,
sourceName,
mode,
proxy,
noCache,
produceType,
@@ -119,15 +129,20 @@ async function getFile(req, res, next) {
}
if (
_fakeFile &&
(content == null || content === '') &&
(url == null || url === '')
!canFakeFileResolveSource({
content,
fileType,
sourceName,
sourceType,
url,
})
) {
$.warn(`fakeFile 缺少 content/url: ${name}`);
$.warn(`fakeFile 缺少可用来源: ${name}`);
failed(
res,
new RequestInvalidError(
'INVALID_FAKE_FILE_SOURCE',
'fakeFile 需要提供 content 或 url 参数',
'fakeFile 需要提供 content/url 或 mihomo 配置来源参数',
),
400,
);
@@ -148,6 +163,27 @@ async function getFile(req, res, next) {
);
return;
}
if (
isShareRoute &&
hasAnyQueryValue([
fileType,
fileSource,
sourceType,
sourceName,
mode,
])
) {
$.warn(`分享链接禁止使用文件来源配置覆盖: ${name}`);
failed(
res,
new RequestInvalidError(
'UNSUPPORTED_SHARE_FILE_RUNTIME_OVERRIDE',
'share/file 不支持文件来源配置覆盖参数',
),
400,
);
return;
}
if (isShareRoute && subInfoUrl != null && subInfoUrl !== '') {
$.warn(`分享链接禁止使用 subInfoUrl: ${name}`);
failed(
@@ -205,14 +241,29 @@ async function getFile(req, res, next) {
if (produceType) {
$.info(`指定生产类型: ${produceType}`);
}
if (fileType) {
$.info(`指定文件类型: ${fileType}`);
}
if (fileSource) {
$.info(`指定文件来源: ${fileSource}`);
}
if (sourceType) {
$.info(`指定 mihomo 配置来源: ${sourceType}`);
}
if (sourceName) {
$.info(`指定 mihomo 配置来源名称: ${sourceName}`);
}
if (mode) {
$.info(`指定 mihomo 配置处理方式: ${mode}`);
}
if (download) {
$.info('启用下载(文件名为显示名称)');
}
if (includeUnsupportedProxy) {
if (includeUnsupportedProxy != null && includeUnsupportedProxy !== '') {
$.info(`包含官方/商店版不支持的协议: ${includeUnsupportedProxy}`);
}
const allFiles = $.read(FILES_KEY);
const allFiles = $.read(FILES_KEY) || [];
const fakeFile = {
name: 'fakeFile',
source: 'remote',
@@ -221,14 +272,25 @@ async function getFile(req, res, next) {
const file = _fakeFile ? fakeFile : findByName(allFiles, name);
if (file) {
try {
const sourceFile = includeUnsupportedProxy
? {
...file,
includeUnsupportedProxy,
}
: _fakeFile
? fakeFile
: undefined;
const sourceFile = buildRuntimeFile(file, {
content,
download,
fileSource,
fileType,
ignoreFailedRemoteFile,
includeUnsupportedProxy,
mergeSources,
mode,
noCache,
sourceName,
sourceType,
produceType,
proxy,
subInfoUrl,
subInfoUserAgent,
ua,
url,
});
const output = await produceArtifact({
type: 'file',
name,
@@ -246,14 +308,14 @@ async function getFile(req, res, next) {
});
try {
subInfoUrl = subInfoUrl || file.subInfoUrl;
if (subInfoUrl) {
const flowSubInfoUrl = sourceFile.subInfoUrl;
if (flowSubInfoUrl) {
// forward flow headers
const flowInfo = await getFlowHeaders(
subInfoUrl,
subInfoUserAgent || file.subInfoUserAgent,
flowSubInfoUrl,
sourceFile.subInfoUserAgent,
undefined,
proxy || file.proxy,
sourceFile.proxy,
);
if (flowInfo) {
const headers = normalizeFlowHeader(flowInfo, true);
@@ -281,11 +343,11 @@ async function getFile(req, res, next) {
)}`,
);
}
if (file.download || download) {
if (sourceFile.download) {
res.set(
'Content-Disposition',
`attachment; filename*=UTF-8''${encodeURIComponent(
file.displayName || file.name,
sourceFile.displayName || sourceFile.name,
)}`,
);
}
@@ -307,8 +369,8 @@ async function getFile(req, res, next) {
const body = await applyResponseTransformers({
res,
body: output?.$content ?? '',
process: file.process,
source: { $file: file },
process: sourceFile.process,
source: { $file: sourceFile },
$options: output?.$options ?? $options,
});
res.send(
@@ -322,7 +384,7 @@ async function getFile(req, res, next) {
name,
findShareToken,
}),
file,
sourceFile,
],
}),
);
@@ -389,14 +451,14 @@ function getWholeFile(req, res) {
function updateFile(req, res) {
let { name } = req.params;
let file = req.body;
const allFiles = $.read(FILES_KEY);
const allFiles = $.read(FILES_KEY) || [];
const oldFile = findByName(allFiles, name);
if (oldFile) {
if (!file.name) file.name = oldFile.name;
const newFile = {
const newFile = normalizeFileConfig({
...oldFile,
...file,
};
});
normalizeAgePublicKeyConfig(newFile);
normalizeEditorLanguageConfig(newFile);
$.info(`正在更新文件:${name}...`);
@@ -445,7 +507,7 @@ function deleteFile(req, res) {
}
function getAllFiles(req, res) {
const allFiles = $.read(FILES_KEY);
const allFiles = $.read(FILES_KEY) || [];
success(
res, // eslint-disable-next-line no-unused-vars
allFiles.map(({ content, ...rest }) => rest),
@@ -453,13 +515,13 @@ function getAllFiles(req, res) {
}
function getAllWholeFiles(req, res) {
const allFiles = $.read(FILES_KEY);
const allFiles = $.read(FILES_KEY) || [];
success(res, allFiles);
}
function replaceFile(req, res) {
try {
const allFiles = req.body;
const allFiles = req.body.map(normalizeFileConfig);
allFiles.forEach((file) => {
normalizeAgePublicKeyConfig(file);
normalizeEditorLanguageConfig(file);
@@ -472,9 +534,9 @@ function replaceFile(req, res) {
}
function createFileItem(rawFile) {
const file = {
const file = normalizeFileConfig({
...rawFile,
};
});
normalizeAgePublicKeyConfig(file);
normalizeEditorLanguageConfig(file);
file.name = `${file.name ?? Date.now()}`;
@@ -494,7 +556,7 @@ function createFileItem(rawFile) {
}
function deleteFileItem(name) {
const allFiles = $.read(FILES_KEY);
const allFiles = $.read(FILES_KEY) || [];
const file = findByName(allFiles, name);
if (!file) {
throw new ResourceNotFoundError(
@@ -520,4 +582,106 @@ function shouldArchiveDeletion(mode) {
);
}
function buildRuntimeFile(
file,
{
content,
download,
fileSource,
fileType,
ignoreFailedRemoteFile,
includeUnsupportedProxy,
mergeSources,
mode,
noCache,
produceType,
proxy,
sourceName,
sourceType,
subInfoUrl,
subInfoUserAgent,
ua,
url,
} = {},
) {
const runtimeFile = { ...file };
assignQueryOverride(runtimeFile, 'content', content);
assignQueryOverride(runtimeFile, 'download', download);
assignQueryOverride(
runtimeFile,
'ignoreFailedRemoteFile',
ignoreFailedRemoteFile,
);
assignQueryOverride(runtimeFile, 'mergeSources', mergeSources);
assignQueryOverride(runtimeFile, 'noCache', noCache);
assignQueryOverride(runtimeFile, 'produceType', produceType);
assignQueryOverride(runtimeFile, 'proxy', proxy);
assignQueryOverride(runtimeFile, 'subInfoUrl', subInfoUrl);
assignQueryOverride(runtimeFile, 'subInfoUserAgent', subInfoUserAgent);
assignQueryOverride(runtimeFile, 'type', fileType);
runtimeFile.type = normalizeFileType(runtimeFile.type);
assignQueryOverride(runtimeFile, 'ua', ua);
assignQueryOverride(runtimeFile, 'url', url);
assignQueryOverride(runtimeFile, 'source', fileSource);
const isMihomoConfig = isMihomoConfigFile(runtimeFile);
if (isMihomoConfig) {
assignQueryOverride(runtimeFile, 'sourceType', sourceType);
assignQueryOverride(runtimeFile, 'sourceName', sourceName);
assignQueryOverride(runtimeFile, 'mode', mode);
if (!runtimeFile.sourceType) {
if (hasQueryValue(url)) {
runtimeFile.sourceType = 'remote';
} else if (hasQueryValue(content)) {
runtimeFile.sourceType = 'local';
}
}
}
assignQueryOverride(
runtimeFile,
'includeUnsupportedProxy',
includeUnsupportedProxy,
);
return runtimeFile;
}
function canFakeFileResolveSource({
content,
fileType,
sourceName,
sourceType,
url,
}) {
if (hasAnyQueryValue([content, url])) return true;
if (!isMihomoConfigFile(getLastQueryValue(fileType))) return false;
const runtimeSourceType = getLastQueryValue(sourceType);
if (runtimeSourceType === 'none') return true;
return (
['subscription', 'collection'].includes(runtimeSourceType) &&
hasQueryValue(sourceName)
);
}
function assignQueryOverride(target, key, value) {
if (!hasQueryValue(value)) return;
target[key] = getLastQueryValue(value);
}
function getLastQueryValue(value) {
return Array.isArray(value) ? value[value.length - 1] : value;
}
function hasQueryValue(value) {
const normalized = getLastQueryValue(value);
return normalized != null && normalized !== '';
}
function hasAnyQueryValue(values) {
return values.some(hasQueryValue);
}
export { createFileItem, deleteFileItem };
+13 -61
View File
@@ -11,9 +11,13 @@ import {
resolveIgnoreFailedRemoteSubMode,
shouldFallbackIgnoreFailedRemoteSub,
} from '@/restful/ignore-failed-remote-sub';
import { prepareMihomoProfileContent } from '@/restful/sync';
import {
prepareMihomoProfileContent,
resolveFileRawContent,
} from '@/restful/sync';
import { normalizeClashYaml } from '@/core/proxy-utils/preprocessors';
import { maskAgeSecretInUrl } from '@/utils/age';
import { isMihomoConfigFile, normalizeFileConfig } from '@/utils/file-type';
function formatAgeSafeUrls(errors) {
return Object.keys(errors).map(maskAgeSecretInUrl).join(', ');
@@ -27,68 +31,16 @@ export default function register($app) {
async function previewFile(req, res) {
try {
const file = req.body;
const file = normalizeFileConfig(req.body);
let content = '';
if (file.type === 'mihomoProfile') {
content = await prepareMihomoProfileContent(file);
if (isMihomoConfigFile(file)) {
content = await prepareMihomoProfileContent(file, {
notifyTitle: '🌍 Sub-Store 预览文件失败',
});
} else {
if (
file.source === 'local' &&
!['localFirst', 'remoteFirst'].includes(file.mergeSources)
) {
content = file.content;
} else {
const errors = {};
content = await Promise.all(
file.url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
file.ua,
undefined,
file.proxy,
);
} catch (err) {
errors[url] = err;
$.error(
`文件 ${file.name} 的远程文件 ${maskAgeSecretInUrl(
url,
)} 发生错误: ${err}`,
);
return '';
}
}),
);
if (Object.keys(errors).length > 0) {
if (!file.ignoreFailedRemoteFile) {
throw new Error(
`文件 ${
file.name
} 的远程文件 ${formatAgeSafeUrls(
errors,
)} 发生错误, 请查看日志`,
);
} else if (file.ignoreFailedRemoteFile === 'enabled') {
$.notify(
`🌍 Sub-Store 预览文件失败`,
`❌ ${file.name}`,
`远程文件 ${formatAgeSafeUrls(
errors,
)} 发生错误, 请查看日志`,
);
}
}
if (file.mergeSources === 'localFirst') {
content.unshift(file.content);
} else if (file.mergeSources === 'remoteFirst') {
content.push(file.content);
}
}
content = await resolveFileRawContent(file, {
notifyTitle: '🌍 Sub-Store 预览文件失败',
});
}
// parse proxies
const files = (Array.isArray(content) ? content : [content]).flat();
+229 -138
View File
@@ -31,6 +31,7 @@ import {
import { normalizeClashYaml } from '@/core/proxy-utils/preprocessors';
import { applyAgeOutputEncryption } from '@/restful/age-output';
import { maskAgeSecretInUrl } from '@/utils/age';
import { isMihomoConfigFile, normalizeFileConfig } from '@/utils/file-type';
export default function register($app) {
// Initialization
@@ -41,15 +42,212 @@ export default function register($app) {
$app.get('/api/sync/artifact/:name', syncArtifact);
}
const MERGE_SOURCE_MODES = ['localFirst', 'remoteFirst'];
const MIHOMO_PROFILE_FILE_SOURCE_TYPES = ['local', 'remote'];
const MIHOMO_CONFIG_SOURCE_TYPES = [
'collection',
'local',
'none',
'remote',
'subscription',
];
function formatAgeSafeUrls(errors) {
return Object.keys(errors).map(maskAgeSecretInUrl).join(', ');
}
async function prepareMihomoProfileContent(file) {
function isMergeSourceMode(mode) {
return MERGE_SOURCE_MODES.includes(mode);
}
function normalizeFileSourceType(file) {
if (isMihomoConfigFile(file)) {
return normalizeMihomoConfigSourceType(file);
}
return file?.source;
}
function normalizeMihomoConfigSourceType(file) {
return MIHOMO_CONFIG_SOURCE_TYPES.includes(file?.sourceType)
? file.sourceType
: 'collection';
}
function normalizeRawFiles(raw) {
return (Array.isArray(raw) ? raw : [raw]).flat();
}
function joinRawFileContent(raw) {
return normalizeRawFiles(raw)
.filter((i) => i != null && i !== '')
.join('\n');
}
function resolveFileIgnoreFailedRemoteFile(file, ignoreFailedRemoteFile) {
if (ignoreFailedRemoteFile != null && ignoreFailedRemoteFile !== '') {
return ignoreFailedRemoteFile;
}
return file.ignoreFailedRemoteFile;
}
async function downloadFileSources({
file,
sourceUrl,
ua,
proxy,
noCache,
ignoreFailedRemoteFile,
notifyTitle = '🌍 Sub-Store 处理文件失败',
}) {
const errors = {};
const urls = `${sourceUrl || ''}`
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length);
if (urls.length === 0) {
throw new Error(`文件 ${file.name} 未配置远程文件 URL`);
}
const raw = await Promise.all(
urls.map(async (url) => {
try {
return await download(
url,
ua || file.ua,
undefined,
file.proxy || proxy,
undefined,
undefined,
noCache,
);
} catch (err) {
errors[url] = err;
$.error(
`文件 ${file.name} 的远程文件 ${maskAgeSecretInUrl(
url,
)} 发生错误: ${err}`,
);
return '';
}
}),
);
const fileIgnoreFailedRemoteFile = resolveFileIgnoreFailedRemoteFile(
file,
ignoreFailedRemoteFile,
);
if (Object.keys(errors).length > 0) {
if (!fileIgnoreFailedRemoteFile) {
throw new Error(
`文件 ${file.name} 的远程文件 ${formatAgeSafeUrls(
errors,
)} 发生错误, 请查看日志`,
);
} else if (fileIgnoreFailedRemoteFile === 'enabled') {
$.notify(
notifyTitle,
`❌ ${file.name}`,
`远程文件 ${formatAgeSafeUrls(errors)} 发生错误, 请查看日志`,
);
}
}
return raw;
}
async function resolveFileRawContent(
file,
{
url,
ua,
content,
mergeSources,
ignoreFailedRemoteFile,
proxy,
noCache,
notifyTitle,
} = {},
) {
if (content && !isMergeSourceMode(mergeSources)) {
return content;
}
if (url) {
const raw = await downloadFileSources({
file,
sourceUrl: url,
ua,
proxy,
noCache,
ignoreFailedRemoteFile,
notifyTitle,
});
if (mergeSources === 'localFirst') {
raw.unshift(content);
} else if (mergeSources === 'remoteFirst') {
raw.push(content);
}
return raw;
}
if (
normalizeFileSourceType(file) === 'local' &&
!isMergeSourceMode(file.mergeSources)
) {
return file.content;
}
const raw = await downloadFileSources({
file,
sourceUrl: file.url,
ua,
proxy,
noCache,
ignoreFailedRemoteFile,
notifyTitle,
});
if (file.mergeSources === 'localFirst') {
raw.unshift(file.content);
} else if (file.mergeSources === 'remoteFirst') {
raw.push(file.content);
}
return raw;
}
async function prepareMihomoProfileContent(file, sourceOptions = {}) {
const config = {};
if (file?.sourceType !== 'none') {
const sourceType = normalizeMihomoConfigSourceType(file);
if (sourceType === 'none') {
return ProxyUtils.yaml.safeDump(config);
}
if (MIHOMO_PROFILE_FILE_SOURCE_TYPES.includes(sourceType)) {
const raw = await resolveFileRawContent(file, sourceOptions);
if (file?.mode !== 'proxy') {
return joinRawFileContent(raw);
}
const proxies = normalizeRawFiles(raw)
.map((i) => ProxyUtils.parse(i))
.flat();
if (proxies.length === 0) {
throw new Error(`文件 ${file.name} 中不含有效节点`);
}
config.proxies = ProxyUtils.produce(
proxies,
'mihomo',
'internal',
{
'delete-underscore-fields': true,
'include-unsupported-proxy': file?.includeUnsupportedProxy,
},
);
} else {
config.proxies = await produceArtifact({
type: file?.sourceType || 'collection',
type: sourceType,
name: file?.sourceName,
platform: 'mihomo',
produceType: 'internal',
@@ -597,145 +795,37 @@ async function produceArtifact({
return RuleUtils.produce(rules, platform);
} else if (type === 'file') {
const allFiles = $.read(FILES_KEY);
const file = sourceFile || findByName(allFiles, name);
const file = normalizeFileConfig(
sourceFile || findByName(allFiles, name),
);
if (!file) throw new Error(`找不到文件 ${name}`);
let raw = '';
if (file.type === 'mihomoProfile') {
raw = await prepareMihomoProfileContent(file);
if (isMihomoConfigFile(file)) {
raw = await prepareMihomoProfileContent(file, {
url,
ua,
content,
mergeSources,
ignoreFailedRemoteFile,
proxy,
noCache,
});
} else {
if (
content &&
!['localFirst', 'remoteFirst'].includes(mergeSources)
) {
raw = content;
} else if (url) {
const errors = {};
raw = await Promise.all(
url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
ua || file.ua,
undefined,
file.proxy || proxy,
undefined,
undefined,
noCache,
);
} catch (err) {
errors[url] = err;
$.error(
`文件 ${file.name} 的远程文件 ${maskAgeSecretInUrl(
url,
)} 发生错误: ${err}`,
);
return '';
}
}),
);
let fileIgnoreFailedRemoteFile = file.ignoreFailedRemoteFile;
if (
ignoreFailedRemoteFile != null &&
ignoreFailedRemoteFile !== ''
) {
fileIgnoreFailedRemoteFile = ignoreFailedRemoteFile;
}
if (
!fileIgnoreFailedRemoteFile &&
Object.keys(errors).length > 0
) {
throw new Error(
`文件 ${
file.name
} 的远程文件 ${formatAgeSafeUrls(
errors,
)} 发生错误, 请查看日志`,
);
}
if (mergeSources === 'localFirst') {
raw.unshift(content);
} else if (mergeSources === 'remoteFirst') {
raw.push(content);
}
} else if (
file.source === 'local' &&
!['localFirst', 'remoteFirst'].includes(file.mergeSources)
) {
raw = file.content;
} else {
const errors = {};
raw = await Promise.all(
file.url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
ua || file.ua,
undefined,
file.proxy || proxy,
undefined,
undefined,
noCache,
);
} catch (err) {
errors[url] = err;
$.error(
`文件 ${file.name} 的远程文件 ${maskAgeSecretInUrl(
url,
)} 发生错误: ${err}`,
);
return '';
}
}),
);
let fileIgnoreFailedRemoteFile = file.ignoreFailedRemoteFile;
if (
ignoreFailedRemoteFile != null &&
ignoreFailedRemoteFile !== ''
) {
fileIgnoreFailedRemoteFile = ignoreFailedRemoteFile;
}
if (Object.keys(errors).length > 0) {
if (!fileIgnoreFailedRemoteFile) {
throw new Error(
`文件 ${
file.name
} 的远程文件 ${formatAgeSafeUrls(
errors,
)} 发生错误, 请查看日志`,
);
} else if (fileIgnoreFailedRemoteFile === 'enabled') {
$.notify(
`🌍 Sub-Store 处理文件失败`,
`❌ ${file.name}`,
`远程文件 ${formatAgeSafeUrls(
errors,
)} 发生错误, 请查看日志`,
);
}
}
if (file.mergeSources === 'localFirst') {
raw.unshift(file.content);
} else if (file.mergeSources === 'remoteFirst') {
raw.push(file.content);
}
}
raw = await resolveFileRawContent(file, {
url,
ua,
content,
mergeSources,
ignoreFailedRemoteFile,
proxy,
noCache,
});
}
if (produceType === 'raw') {
return JSON.stringify((Array.isArray(raw) ? raw : [raw]).flat());
return JSON.stringify(normalizeRawFiles(raw));
}
const files = (Array.isArray(raw) ? raw : [raw]).flat();
let filesContent = files
.filter((i) => i != null && i !== '')
.join('\n');
const files = normalizeRawFiles(raw);
let filesContent = joinRawFileContent(files);
// apply processors
const processed =
@@ -1024,7 +1114,7 @@ async function syncArtifacts(options = {}) {
if (useMihomoExternal) {
$.info(
`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`,
`手动指定了 target 为 SurgeMac, 将使用 mihomo External`,
);
}
@@ -1150,7 +1240,7 @@ async function syncArtifactItem(name) {
const useMihomoExternal = artifact.platform === 'SurgeMac';
if (useMihomoExternal) {
$.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`);
$.info(`手动指定了 target 为 SurgeMac, 将使用 mihomo External`);
}
const output = await produceSyncArtifactOutput(artifact);
@@ -1242,6 +1332,7 @@ export {
prepareMihomoProfileContent,
produceArtifact,
produceSyncArtifactOutput,
resolveFileRawContent,
shouldUploadArtifact,
syncArtifactItem,
syncArtifacts,
+70
View File
@@ -210,6 +210,54 @@ describe('file routes', function () {
expect(res.sent).to.equal('base-script-carried');
});
it('passes runtime file overrides to response transformers', async function () {
state[FILES_KEY][0] = {
name: 'local-file',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'stored-sub',
process: [
{
type: 'Response Transformer',
args: {
mode: 'script',
content:
'$res.body = JSON.stringify({\n' +
' contentHasRuntimeNode: context.source.$file.content.includes("Runtime Supported"),\n' +
' download: context.source.$file.download,\n' +
' mode: context.source.$file.mode,\n' +
' proxy: context.source.$file.proxy,\n' +
' sourceType: context.source.$file.sourceType,\n' +
' type: context.source.$file.type,\n' +
'})',
},
},
],
};
const res = await requestFile({
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' - {name: Runtime Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}',
download: '1',
mode: 'proxy',
proxy: 'runtime-proxy',
sourceType: 'local',
type: 'mihomoConfig',
});
const body = JSON.parse(res.sent);
expect(body).to.deep.equal({
contentHasRuntimeNode: true,
download: '1',
mode: 'proxy',
proxy: 'runtime-proxy',
sourceType: 'local',
type: 'mihomoConfig',
});
});
it('uses fakeFile without requiring a stored file', async function () {
state[FILES_KEY] = [];
@@ -349,6 +397,28 @@ describe('file routes', function () {
expect(res.sent.error.type).to.equal('RequestInvalidError');
});
it('rejects runtime file source overrides on share routes', async function () {
const res = await requestShareFile({
query: {
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
mode: 'proxy',
},
shareToken: {
type: 'file',
name: 'local-file',
},
});
expect(res.statusCode).to.equal(400);
expect(res.sent.status).to.equal('failed');
expect(res.sent.error.code).to.equal(
'UNSUPPORTED_SHARE_FILE_RUNTIME_OVERRIDE',
);
expect(res.sent.error.type).to.equal('RequestInvalidError');
});
it('encrypts transformed file output with file age-public-key', async function () {
const pair = await ageUtils.generateKeyPair();
state[FILES_KEY][0]['age-public-key'] = pair['age-public-key'];
@@ -3,7 +3,7 @@ import { afterEach, describe, it } from 'mocha';
import { Base64 } from 'js-base64';
import $ from '@/core/app';
import { GIST_BACKUP_FILE_NAME, SETTINGS_KEY } from '@/constants';
import { GIST_BACKUP_FILE_NAME } from '@/constants';
import { gistBackupAction } from '@/restful/miscs';
import Gist from '@/utils/gist';
import {
@@ -23,6 +23,7 @@ describe('Gist backup age encryption', function () {
const originalUpload = Gist.prototype.upload;
const originalDownload = Gist.prototype.download;
const originalCache = $.cache;
const originalPersistCache = $.persistCache.bind($);
afterEach(function () {
$.read = originalRead;
@@ -32,26 +33,24 @@ describe('Gist backup age encryption', function () {
Gist.prototype.upload = originalUpload;
Gist.prototype.download = originalDownload;
$.cache = originalCache;
$.persistCache = originalPersistCache;
});
function installState(initialContent) {
$.cache = JSON.parse(JSON.stringify(initialContent));
$.read = (key) => {
if (key === SETTINGS_KEY) return $.cache.settings;
if (key === '#sub-store') return JSON.stringify($.cache);
return originalRead(key);
return $.cache[key];
};
$.write = (data, key) => {
if (key === SETTINGS_KEY) {
$.cache.settings = data;
return true;
}
if (key === '#sub-store') {
$.cache = JSON.parse(data);
return true;
}
return originalWrite(data, key);
$.cache[key] = data;
return true;
};
$.persistCache = () => {};
$.info = () => {};
$.error = () => {};
}
@@ -0,0 +1,688 @@
import { expect } from 'chai';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { after, afterEach, before, beforeEach, describe, it } from 'mocha';
import { FILES_KEY, SUBS_KEY } from '@/constants';
let $;
let registerFileRoutes;
let registerPreviewRoutes;
let originalError;
let originalInfo;
let originalNotify;
let originalRead;
let originalWarn;
let originalWrite;
let remoteFilePath;
let state;
function cleanupRemoteFile() {
if (remoteFilePath && fs.existsSync(remoteFilePath)) {
fs.unlinkSync(remoteFilePath);
}
remoteFilePath = null;
}
function createRouteApp() {
const handlers = new Map();
const methods = ['get', 'post', 'put', 'patch', 'delete'];
const app = {
handlers,
route(pattern) {
const chain = {};
methods.forEach((method) => {
chain[method] = (handler) => {
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
return chain;
};
});
return chain;
},
};
methods.forEach((method) => {
app[method] = (pattern, handler) => {
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
return app;
};
});
return app;
}
function getHandler(pattern) {
const app = createRouteApp();
registerFileRoutes(app);
return app.handlers.get(`GET ${pattern}`);
}
function createResponse(routePath) {
return {
headers: {},
req: {
route: {
path: routePath,
},
},
sent: null,
statusCode: 200,
removeHeader(key) {
delete this.headers[key];
return this;
},
send(payload) {
this.sent = payload;
return this;
},
json(payload) {
this.sent = payload;
return this;
},
set(key, value) {
this.headers[key] = value;
return this;
},
status(code) {
this.statusCode = code;
return this;
},
};
}
async function requestFile(name, query = {}) {
const handler = getHandler('/api/file/:name');
const res = createResponse('/api/file/:name');
await handler(
{
body: {},
headers: {},
method: 'GET',
params: { name },
path: `/api/file/${name}`,
query,
socket: {},
url: `/api/file/${name}`,
},
res,
);
return res;
}
async function requestWholeFiles() {
const handler = getHandler('/api/wholeFiles');
const res = createResponse('/api/wholeFiles');
await handler(
{
body: {},
headers: {},
method: 'GET',
params: {},
path: '/api/wholeFiles',
query: {},
socket: {},
url: '/api/wholeFiles',
},
res,
);
return res;
}
async function previewFile(file) {
const app = createRouteApp();
registerPreviewRoutes(app);
const handler = app.handlers.get('POST /api/preview/file');
const res = createResponse('/api/preview/file');
await handler(
{
body: file,
headers: {},
method: 'POST',
path: '/api/preview/file',
query: {},
socket: {},
url: '/api/preview/file',
},
res,
);
return res;
}
describe('mihomo config file routes', function () {
before(async function () {
({ default: $ } = require('@/core/app'));
({ default: registerFileRoutes } = require('@/restful/file'));
({ default: registerPreviewRoutes } = require('@/restful/preview'));
originalRead = $.read.bind($);
originalWrite = $.write.bind($);
originalInfo = $.info.bind($);
originalWarn = $.warn.bind($);
originalError = $.error.bind($);
originalNotify = $.notify.bind($);
});
after(function () {
if ($) {
$.read = originalRead;
$.write = originalWrite;
$.info = originalInfo;
$.warn = originalWarn;
$.error = originalError;
$.notify = originalNotify;
}
cleanupRemoteFile();
});
afterEach(function () {
cleanupRemoteFile();
});
beforeEach(function () {
remoteFilePath = path.join(
os.tmpdir(),
`sub-store-mihomo-config-${Date.now()}.yaml`,
);
fs.writeFileSync(
remoteFilePath,
'mixed-port: 7890\n' +
'proxies:\n' +
' - {name: Remote Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}',
'utf8',
);
state = {
[SUBS_KEY]: [
{
name: 'demo-sub',
source: 'local',
content:
'proxies:\n' +
' - {name: Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}\n' +
' - {name: Unsupported, type: naive, server: naive.example.com, port: 443, username: user, password: pass, sni: naive.example.com}',
process: [],
},
],
[FILES_KEY]: [],
};
$.read = (key) => state[key] || [];
$.write = (data, key) => {
state[key] = data;
return true;
};
$.info = () => {};
$.warn = () => {};
$.error = () => {};
$.notify = () => {};
});
it('keeps legacy mihomoProfile file type unchanged when reading files', async function () {
state[FILES_KEY] = [
{
name: 'legacy-file',
type: 'mihomoProfile',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [],
},
];
const res = await requestWholeFiles();
expect(res.statusCode).to.equal(200);
expect(res.sent.data[0].type).to.equal('mihomoProfile');
expect(state[FILES_KEY][0].type).to.equal('mihomoProfile');
});
it('builds legacy mihomoProfile files without rewriting stored type', async function () {
state[FILES_KEY] = [
{
name: 'legacy-runtime-file',
type: 'mihomoProfile',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [],
},
];
const res = await requestFile('legacy-runtime-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('proxies:');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
expect(state[FILES_KEY][0].type).to.equal('mihomoProfile');
});
it('builds mihomoConfig proxies before file processors run', async function () {
state[FILES_KEY] = [
{
name: 'base-file',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [],
},
];
const res = await requestFile('base-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('proxies:');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('previews mihomoConfig proxies before file processors run', async function () {
const res = await previewFile({
name: 'preview-file',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [],
});
expect(res.statusCode).to.equal(200);
expect(res.sent.status).to.equal('success');
expect(res.sent.data.original).to.include('proxies:');
expect(res.sent.data.original).to.include('name: Supported');
expect(res.sent.data.original).to.not.include('name: Unsupported');
expect(res.sent.data.processed).to.include('name: Supported');
});
it('keeps unsupported proxies for YAML mihomoConfig overrides when enabled', async function () {
state[FILES_KEY] = [
{
name: 'yaml-file',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: true,
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content: 'mixed-port: 7890',
},
},
],
},
];
const res = await requestFile('yaml-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7890');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.include('name: Unsupported');
});
it('filters unsupported proxies for JS mihomoConfig overrides when disabled', async function () {
state[FILES_KEY] = [
{
name: 'js-file',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content:
'async function main(config) { config["mixed-port"] = 7891; return config; }',
},
},
],
},
];
const res = await requestFile('js-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7891');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('query includeUnsupportedProxy presence enables unsupported proxies for mihomoConfig files', async function () {
state[FILES_KEY] = [
{
name: 'query-true-file',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content: 'mixed-port: 7892',
},
},
],
},
];
const res = await requestFile('query-true-file', {
includeUnsupportedProxy: 'false',
});
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7892');
expect(res.sent).to.include('name: Unsupported');
});
it('query mihomoConfig fields override the stored file source when downloading', async function () {
state[FILES_KEY] = [
{
name: 'override-file',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [],
},
];
const res = await requestFile('override-file', {
sourceType: 'local',
mode: 'proxy',
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' - {name: Query Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}\n' +
' - {name: Query Unsupported, type: naive, server: naive.example.com, port: 443, username: user, password: pass, sni: naive.example.com}',
});
expect(res.statusCode).to.equal(200);
expect(res.sent).to.not.include('mixed-port: 7890');
expect(res.sent).to.include('name: Query Supported');
expect(res.sent).to.not.include('name: Query Unsupported');
expect(res.sent).to.not.include('name: Supported');
});
it('fakeFile can parse provided local content as mihomoConfig proxies', async function () {
state[FILES_KEY] = [];
const res = await requestFile('missing-file', {
fakeFile: '1',
type: 'mihomoConfig',
sourceType: 'local',
mode: 'proxy',
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' - {name: Fake Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}\n' +
' - {name: Fake Unsupported, type: naive, server: naive.example.com, port: 443, username: user, password: pass, sni: naive.example.com}',
});
expect(res.statusCode).to.equal(200);
expect(res.sent).to.not.include('mixed-port: 7890');
expect(res.sent).to.include('name: Fake Supported');
expect(res.sent).to.not.include('name: Fake Unsupported');
});
it('fakeFile can build a mihomoConfig from a subscription source', async function () {
state[FILES_KEY] = [];
const res = await requestFile('missing-file', {
fakeFile: '1',
type: 'mihomoConfig',
sourceType: 'subscription',
sourceName: 'demo-sub',
});
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('uses local mihomoConfig source content as a full mihomo config by default', async function () {
state[FILES_KEY] = [
{
name: 'local-config-file',
type: 'mihomoConfig',
sourceType: 'local',
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' - {name: Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}\n' +
' - {name: Unsupported, type: naive, server: naive.example.com, port: 443, username: user, password: pass, sni: naive.example.com}',
process: [],
},
];
const res = await requestFile('local-config-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7890');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.include('name: Unsupported');
});
it('uses remote mihomoConfig source url instead of stale content by default', async function () {
state[FILES_KEY] = [
{
name: 'remote-config-file',
type: 'mihomoConfig',
sourceType: 'remote',
url: remoteFilePath,
content:
'mixed-port: 7891\n' +
'proxies:\n' +
' - {name: Stale Local, type: ss, server: stale.example.com, port: 8388, cipher: aes-128-gcm, password: secret}',
process: [],
},
];
const res = await requestFile('remote-config-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7890');
expect(res.sent).to.include('name: Remote Supported');
expect(res.sent).to.not.include('mixed-port: 7891');
expect(res.sent).to.not.include('name: Stale Local');
});
it('uses local mihomoConfig source content instead of url by default', async function () {
state[FILES_KEY] = [
{
name: 'local-config-with-url-file',
type: 'mihomoConfig',
sourceType: 'local',
url: remoteFilePath,
content:
'mixed-port: 7892\n' +
'proxies:\n' +
' - {name: Local Supported, type: ss, server: local.example.com, port: 8388, cipher: aes-128-gcm, password: secret}',
process: [],
},
];
const res = await requestFile('local-config-with-url-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7892');
expect(res.sent).to.include('name: Local Supported');
expect(res.sent).to.not.include('mixed-port: 7890');
expect(res.sent).to.not.include('name: Remote Supported');
});
it('merges local and remote mihomoConfig file sources when requested', async function () {
state[FILES_KEY] = [
{
name: 'merged-local-config-file',
type: 'mihomoConfig',
sourceType: 'local',
mergeSources: 'localFirst',
url: remoteFilePath,
content:
'mixed-port: 7892\n' +
'proxies:\n' +
' - {name: Local Supported, type: ss, server: local.example.com, port: 8388, cipher: aes-128-gcm, password: secret}',
process: [],
},
];
const res = await requestFile('merged-local-config-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7892');
expect(res.sent).to.include('name: Local Supported');
expect(res.sent).to.include('mixed-port: 7890');
expect(res.sent).to.include('name: Remote Supported');
expect(res.sent.indexOf('mixed-port: 7892')).to.be.lessThan(
res.sent.indexOf('mixed-port: 7890'),
);
});
it('parses local mihomoConfig source content as proxies when selected', async function () {
state[FILES_KEY] = [
{
name: 'local-proxy-file',
type: 'mihomoConfig',
sourceType: 'local',
mode: 'proxy',
includeUnsupportedProxy: false,
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' - {name: Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}\n' +
' - {name: Unsupported, type: naive, server: naive.example.com, port: 443, username: user, password: pass, sni: naive.example.com}',
process: [],
},
];
const res = await requestFile('local-proxy-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.not.include('mixed-port: 7890');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('keeps unsupported proxies when parsing local mihomoConfig source content as proxies with the option enabled', async function () {
state[FILES_KEY] = [
{
name: 'local-proxy-unsupported-file',
type: 'mihomoConfig',
sourceType: 'local',
mode: 'proxy',
includeUnsupportedProxy: true,
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' - {name: Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}\n' +
' - {name: Unsupported, type: naive, server: naive.example.com, port: 443, username: user, password: pass, sni: naive.example.com}',
process: [],
},
];
const res = await requestFile('local-proxy-unsupported-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.include('name: Unsupported');
});
it('adds subscription proxies to mihomoConfig files without moving an existing proxies key', async function () {
state[FILES_KEY] = [
{
name: 'add-proxies-file',
type: 'mihomoConfig',
sourceType: 'none',
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' note: not-array\n' +
'proxy-groups:\n' +
' - name: Auto\n' +
' type: select\n' +
' proxies: [Supported]',
},
},
{
type: 'Add Proxies From Subscription Operator',
args: {
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
position: 'back',
},
},
],
},
];
const res = await requestFile('add-proxies-file');
expect(res.statusCode).to.equal(200);
expect(res.sent.indexOf('mixed-port:')).to.be.lessThan(
res.sent.indexOf('proxies:'),
);
expect(res.sent.indexOf('proxies:')).to.be.lessThan(
res.sent.indexOf('proxy-groups:'),
);
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('can insert subscription proxies before existing mihomoConfig proxies', async function () {
state[FILES_KEY] = [
{
name: 'insert-proxies-file',
type: 'mihomoConfig',
sourceType: 'none',
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content:
'proxies:\n' +
' - name: Existing\n' +
' type: direct',
},
},
{
type: 'Add Proxies From Subscription Operator',
args: {
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
position: 'front',
},
},
],
},
];
const res = await requestFile('insert-proxies-file');
expect(res.statusCode).to.equal(200);
expect(res.sent.indexOf('name: Supported')).to.be.lessThan(
res.sent.indexOf('name: Existing'),
);
});
});
@@ -1,387 +0,0 @@
import { expect } from 'chai';
import { after, before, beforeEach, describe, it } from 'mocha';
import { FILES_KEY, SUBS_KEY } from '@/constants';
let $;
let registerFileRoutes;
let registerPreviewRoutes;
let originalError;
let originalInfo;
let originalNotify;
let originalRead;
let originalWarn;
let originalWrite;
let state;
function createRouteApp() {
const handlers = new Map();
const methods = ['get', 'post', 'put', 'patch', 'delete'];
const app = {
handlers,
route(pattern) {
const chain = {};
methods.forEach((method) => {
chain[method] = (handler) => {
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
return chain;
};
});
return chain;
},
};
methods.forEach((method) => {
app[method] = (pattern, handler) => {
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
return app;
};
});
return app;
}
function getHandler(pattern) {
const app = createRouteApp();
registerFileRoutes(app);
return app.handlers.get(`GET ${pattern}`);
}
function createResponse(routePath) {
return {
headers: {},
req: {
route: {
path: routePath,
},
},
sent: null,
statusCode: 200,
removeHeader(key) {
delete this.headers[key];
return this;
},
send(payload) {
this.sent = payload;
return this;
},
json(payload) {
this.sent = payload;
return this;
},
set(key, value) {
this.headers[key] = value;
return this;
},
status(code) {
this.statusCode = code;
return this;
},
};
}
async function requestFile(name, query = {}) {
const handler = getHandler('/api/file/:name');
const res = createResponse('/api/file/:name');
await handler(
{
body: {},
headers: {},
method: 'GET',
params: { name },
path: `/api/file/${name}`,
query,
socket: {},
url: `/api/file/${name}`,
},
res,
);
return res;
}
async function previewFile(file) {
const app = createRouteApp();
registerPreviewRoutes(app);
const handler = app.handlers.get('POST /api/preview/file');
const res = createResponse('/api/preview/file');
await handler(
{
body: file,
headers: {},
method: 'POST',
path: '/api/preview/file',
query: {},
socket: {},
url: '/api/preview/file',
},
res,
);
return res;
}
describe('mihomo profile file routes', function () {
before(async function () {
({ default: $ } = require('@/core/app'));
({ default: registerFileRoutes } = require('@/restful/file'));
({ default: registerPreviewRoutes } = require('@/restful/preview'));
originalRead = $.read.bind($);
originalWrite = $.write.bind($);
originalInfo = $.info.bind($);
originalWarn = $.warn.bind($);
originalError = $.error.bind($);
originalNotify = $.notify.bind($);
});
after(function () {
if ($) {
$.read = originalRead;
$.write = originalWrite;
$.info = originalInfo;
$.warn = originalWarn;
$.error = originalError;
$.notify = originalNotify;
}
});
beforeEach(function () {
state = {
[SUBS_KEY]: [
{
name: 'demo-sub',
source: 'local',
content:
'proxies:\n' +
' - {name: Supported, type: ss, server: ss.example.com, port: 8388, cipher: aes-128-gcm, password: secret}\n' +
' - {name: Unsupported, type: naive, server: naive.example.com, port: 443, username: user, password: pass, sni: naive.example.com}',
process: [],
},
],
[FILES_KEY]: [],
};
$.read = (key) => state[key] || [];
$.write = (data, key) => {
state[key] = data;
return true;
};
$.info = () => {};
$.warn = () => {};
$.error = () => {};
$.notify = () => {};
});
it('builds mihomoProfile proxies before file processors run', async function () {
state[FILES_KEY] = [
{
name: 'base-file',
type: 'mihomoProfile',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [],
},
];
const res = await requestFile('base-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('proxies:');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('previews mihomoProfile proxies before file processors run', async function () {
const res = await previewFile({
name: 'preview-file',
type: 'mihomoProfile',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [],
});
expect(res.statusCode).to.equal(200);
expect(res.sent.status).to.equal('success');
expect(res.sent.data.original).to.include('proxies:');
expect(res.sent.data.original).to.include('name: Supported');
expect(res.sent.data.original).to.not.include('name: Unsupported');
expect(res.sent.data.processed).to.include('name: Supported');
});
it('keeps unsupported proxies for YAML mihomoProfile overrides when enabled', async function () {
state[FILES_KEY] = [
{
name: 'yaml-file',
type: 'mihomoProfile',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: true,
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content: 'mixed-port: 7890',
},
},
],
},
];
const res = await requestFile('yaml-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7890');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.include('name: Unsupported');
});
it('filters unsupported proxies for JS mihomoProfile overrides when disabled', async function () {
state[FILES_KEY] = [
{
name: 'js-file',
type: 'mihomoProfile',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content:
'async function main(config) { config["mixed-port"] = 7891; return config; }',
},
},
],
},
];
const res = await requestFile('js-file');
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7891');
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('query includeUnsupportedProxy overrides stored false for mihomoProfile files', async function () {
state[FILES_KEY] = [
{
name: 'query-true-file',
type: 'mihomoProfile',
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content: 'mixed-port: 7892',
},
},
],
},
];
const res = await requestFile('query-true-file', {
includeUnsupportedProxy: 'true',
});
expect(res.statusCode).to.equal(200);
expect(res.sent).to.include('mixed-port: 7892');
expect(res.sent).to.include('name: Unsupported');
});
it('adds subscription proxies to mihomoProfile files without moving an existing proxies key', async function () {
state[FILES_KEY] = [
{
name: 'add-proxies-file',
type: 'mihomoProfile',
sourceType: 'none',
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content:
'mixed-port: 7890\n' +
'proxies:\n' +
' note: not-array\n' +
'proxy-groups:\n' +
' - name: Auto\n' +
' type: select\n' +
' proxies: [Supported]',
},
},
{
type: 'Add Proxies From Subscription Operator',
args: {
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
position: 'back',
},
},
],
},
];
const res = await requestFile('add-proxies-file');
expect(res.statusCode).to.equal(200);
expect(res.sent.indexOf('mixed-port:')).to.be.lessThan(
res.sent.indexOf('proxies:'),
);
expect(res.sent.indexOf('proxies:')).to.be.lessThan(
res.sent.indexOf('proxy-groups:'),
);
expect(res.sent).to.include('name: Supported');
expect(res.sent).to.not.include('name: Unsupported');
});
it('can insert subscription proxies before existing mihomoProfile proxies', async function () {
state[FILES_KEY] = [
{
name: 'insert-proxies-file',
type: 'mihomoProfile',
sourceType: 'none',
process: [
{
type: 'Script Operator',
args: {
mode: 'script',
content:
'proxies:\n' +
' - name: Existing\n' +
' type: direct',
},
},
{
type: 'Add Proxies From Subscription Operator',
args: {
sourceType: 'subscription',
sourceName: 'demo-sub',
includeUnsupportedProxy: false,
position: 'front',
},
},
],
},
];
const res = await requestFile('insert-proxies-file');
expect(res.statusCode).to.equal(200);
expect(res.sent.indexOf('name: Supported')).to.be.lessThan(
res.sent.indexOf('name: Existing'),
);
});
});
+35
View File
@@ -0,0 +1,35 @@
const MIHOMO_CONFIG_FILE_TYPE = 'mihomoConfig';
const LEGACY_MIHOMO_CONFIG_FILE_TYPE = 'mihomoProfile';
const MIHOMO_CONFIG_FILE_TYPES = [
MIHOMO_CONFIG_FILE_TYPE,
LEGACY_MIHOMO_CONFIG_FILE_TYPE,
];
function isMihomoConfigFile(fileOrType) {
const type =
typeof fileOrType === 'string' ? fileOrType : fileOrType?.type;
return MIHOMO_CONFIG_FILE_TYPES.includes(type);
}
function normalizeFileType(type) {
return isMihomoConfigFile(type) ? MIHOMO_CONFIG_FILE_TYPE : type;
}
function normalizeFileConfig(file) {
if (!file) return file;
if (!isMihomoConfigFile(file)) return file;
if (file.type === MIHOMO_CONFIG_FILE_TYPE) return file;
return {
...file,
type: MIHOMO_CONFIG_FILE_TYPE,
};
}
export {
LEGACY_MIHOMO_CONFIG_FILE_TYPE,
MIHOMO_CONFIG_FILE_TYPE,
MIHOMO_CONFIG_FILE_TYPES,
isMihomoConfigFile,
normalizeFileConfig,
normalizeFileType,
};