diff --git a/docs/en/guide/subscriptions.md b/docs/en/guide/subscriptions.md index c6e1e0919..3710837da 100644 --- a/docs/en/guide/subscriptions.md +++ b/docs/en/guide/subscriptions.md @@ -323,7 +323,7 @@ The panel touches three keys of the root and leaves the rest as you wrote it, wi | Key | What the panel does | |:--|:--| | `proxies` | Puts the person's servers **first**, before the proxies you wrote. A missing key (or `null`) is created. | -| `proxy-groups` | Adds the group `Auto` at the end while **Automatic server choice** is on and the template has no group of that name, even for a person with one server, so that your groups can refer to it. It is a `url-test` over the person's servers (not over your own `proxies`). | +| `proxy-groups` | Expands groups that opt in to panel order (see below). Also adds `Auto` at the end while **Automatic server choice** is on and the template has no group of that name, even for a person with one server, so your groups can refer to it. It is a `url-test` over the person's servers (not over your own `proxies`). | | `dns` | Only when the template has none: the resolvers of the person's DNS preset, with `respect-rules: true`. Nothing else of the preset is added (see below). | Everything else is yours: `rules`, `rule-providers`, `proxy-providers`, `tun`, the ports. The rules of the person's DNS preset (blocked ads, the split, countries) are **not** added to a template, because the order of the rules and the `MATCH` are yours; write them in the template if you need them. When the template has its own `dns`, the person's DNS preset and their pick on the page do not apply to the Mihomo apps (the other apps keep them). @@ -332,12 +332,19 @@ The panel names the person's servers by the [server name template](#names-texts) ### Getting the servers into your groups -Do not write a server's name in a group: the servers differ from person to person, and a name a person does not have makes Mihomo refuse the whole file. The save refuses it too. Ask Mihomo for the servers instead: +Do not write a person's server name in a group: the servers differ from person to person, and a name a person does not have makes Mihomo refuse the whole file. The save refuses it too. You can refer to `Auto` for speed-based selection over the person's servers when the panel adds that group. -- `include-all-proxies: true` takes the person's servers and the proxies of your template; -- `filter` and `exclude-filter` (regular expressions) narrow them by name, for example `filter: "Germany"`; -- `include-all: true` also takes the groups of your `proxy-providers`; -- the group `Auto` is the person's servers by speed. +To use panel order, set `mistgate-ordered-proxies: true` on each proxy group you want to change. New templates start with this flag in their `Proxy` group. When rendering a subscription or preview, Mistgate keeps the entries already listed in the group's `proxies`, then appends the person's matching servers in panel order, then matching proxies declared in the template in declaration order, without adding names already present. Mistgate leaves the flag in the saved template but removes it from the rendered YAML. If no members match and the group has neither explicit members nor providers, the panel uses `empty-fallback`, or `COMPATIBLE` if it is not set. + +Saved templates are not migrated. Without the opt-in, `include-all-proxies` and `include-all` keep their native Mihomo behavior, which sorts the automatically included local proxies by name. To switch an existing group: + +- Replace `include-all-proxies: true` with `mistgate-ordered-proxies: true`. Keep any existing `include-all-providers` or `use` as written. +- Replace `include-all: true` with `mistgate-ordered-proxies: true` and `include-all-providers: true` to keep all providers. To use only selected providers in a specific order instead, leave `include-all-providers` off and list them in `use`. When all providers are enabled, Mihomo ignores `use`. +- Remove or set to `false` both native local inclusion flags, including any inherited through `<<`: the panel rejects either one set to `true` alongside the opt-in. Check the preview, save, then refresh the subscription in the app. + +With the opt-in, the panel applies `filter` to the final names of the proxies it adds, not to the members you listed explicitly. Providers stay dynamic in Mihomo; the panel leaves `filter`, `exclude-filter` and `exclude-type` in the output. Use `filter: "Germany"` to match by name, not by IP or actual location. With providers and multiple backtick-separated expressions, Mihomo collects matches in expression order across all sources, including explicit members: `Auto` may no longer be first in a `select` group. A client's display sort by name or latency can differ from the order the core uses, including for `fallback`. + +**Before downgrading:** Replace the new flag with `include-all-proxies: true` in groups that rely on it. An older panel does not expand the flag, so a group can be left without members and Mihomo can reject the profile. A template for the group `ROUTER`, written with made-up names: @@ -351,11 +358,11 @@ mode: rule proxy-groups: - name: Proxy type: select - include-all-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - include-all-proxies: true + mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -376,21 +383,25 @@ rules: - MATCH,Proxy ``` -A person in `ROUTER` gets this text with their servers at the top of `proxies`, `Auto` at the end of `proxy-groups` and a `dns` section, and nothing else changed. +A person in `ROUTER` gets their servers at the top of `proxies`, expanded `Proxy` and `Germany` member lists, `Auto` at the end of `proxy-groups`, and a `dns` section. ### What a save checks The limits: 20 templates, 64 KiB each and 256 KiB in all; a name of 1 to 60 characters (the same name in another letter case counts as the same); at most 100 groups in one template; a group in one template only. A group you delete drops out of its template at the next save. -The save refuses a template, with the line in the message, when: +The save refuses a template when: - the text is not valid UTF-8 or YAML, holds a second document (`---`), a key given twice, or aliases that expand far beyond the text; - the root is not a mapping or has `<<`, or `proxies` or `proxy-groups` is not a plain list (an alias there would let the panel change the anchor too); - a proxy has no `name`, a group has no `name` or `type`, names repeat, or one is a core name; - a group refers in its `proxies` to a name that is no proxy or group of the template, no core name and not `Auto` (while the panel adds that group), or in `use` to a provider you did not define; -- the panel cannot build a profile from it with two sample servers. +- `mistgate-ordered-proxies` is not a YAML boolean, or a group enables it alongside `include-all-proxies` or `include-all` or shares its name with a proxy provider; +- an opted-in group has an invalid `filter` regular expression or matching exceeds the time limit; +- the panel cannot build a profile from it with three sample servers, one with a long name. + +If matching runs out of time, the preview reports an error and the subscription refresh fails instead of sending the built-in profile. On Cloudflare Workers the clock does not advance during matching, so the Worker's CPU limit is the backstop. -Other findings do not stop a save and show in the preview as **Worth a look**: no group takes the person's servers (add `include-all-proxies` or refer to `Auto`); the template has its own `dns`; the person's DNS preset has ad, split or country rules that the template does not get; the template has its own `Auto`, so the panel adds none; a rule sends to a name that is nothing in the template; no group is chosen. The panel does not check the rest of Mihomo's keys: run the file in Mihomo for that. +Other findings do not stop a save and show in the preview as **Worth a look**: no group takes the person's servers (add `mistgate-ordered-proxies: true` or refer to `Auto`); the template has its own `dns`; the person's DNS preset has ad, split or country rules that the template does not get; the template has its own `Auto`, so the panel adds none; a rule sends to a name that is nothing in the template; no group is chosen. The panel does not check the rest of Mihomo's keys: run the file in Mihomo for that. ### Preview diff --git a/docs/ru/guide/subscriptions.md b/docs/ru/guide/subscriptions.md index 788b90524..eddcef328 100644 --- a/docs/ru/guide/subscriptions.md +++ b/docs/ru/guide/subscriptions.md @@ -323,7 +323,7 @@ tproxy-port: 1181 | Ключ | Что делает панель | |:--|:--| | `proxies` | Ставит серверы человека **в начало**, перед вашими прокси. Если ключа нет (или он `null`), создаёт его. | -| `proxy-groups` | Добавляет в конец группу `Auto`, пока включён **Автоматический выбор сервера** и в шаблоне нет группы с таким именем, — даже человеку с одним сервером, чтобы ваши группы могли на неё ссылаться. Это `url-test` по серверам человека (не по вашим `proxies`). | +| `proxy-groups` | Формирует списки участников тех групп, для которых включён порядок панели (см. ниже). Пока включён **Автовыбор сервера** и в шаблоне нет группы `Auto`, добавляет её в конец — даже человеку с одним сервером, чтобы ваши группы могли на неё ссылаться. Это `url-test` по серверам человека (не по вашим `proxies`). | | `dns` | Только если в шаблоне его нет: резолверы из DNS-пресета человека с `respect-rules: true`. Ничего больше из пресета не добавляется (см. ниже). | Всё остальное ваше: `rules`, `rule-providers`, `proxy-providers`, `tun`, порты. Правила DNS-пресета человека (блокировка рекламы, разделение, страны) в шаблон **не** добавляются: порядок правил и `MATCH` ваши, нужное напишите в шаблоне. Если в шаблоне есть свой `dns`, DNS-пресет человека и его выбор на странице к приложениям Mihomo не применяются (остальные приложения их сохраняют). @@ -332,12 +332,19 @@ tproxy-port: 1181 ### Как попасть серверам в ваши группы -Не пишите в группе имя сервера: у людей разные серверы, а имя, которого у человека нет, заставит Mihomo отвергнуть весь файл. Сохранение такое тоже отклонит. Серверы запрашивайте средствами Mihomo: +Не пишите в группе имя сервера человека: у людей разные серверы, а имя, которого у человека нет, заставит Mihomo отвергнуть весь файл. Сохранение такое тоже отклонит. Когда панель добавляет `Auto`, на эту группу можно сослаться для выбора сервера человека по скорости. -- `include-all-proxies: true` берёт серверы человека и прокси вашего шаблона; -- `filter` и `exclude-filter` (регулярные выражения) отбирают их по имени, например `filter: "Germany"`; -- `include-all: true` берёт ещё и группы из ваших `proxy-providers`; -- группа `Auto` — серверы человека по скорости. +Чтобы использовать порядок панели, задайте `mistgate-ordered-proxies: true` в каждой нужной группе прокси. В новом шаблоне этот флаг уже стоит в группе `Proxy`. При сборке подписки или превью Mistgate сохраняет явно перечисленных участников группы, затем добавляет подходящие серверы человека в порядке панели, а после них — подходящие прокси шаблона в порядке объявления. Имена, которые уже есть в списке, не добавляются повторно. Флаг остаётся в сохранённом шаблоне, но не попадает в итоговый YAML. Если нет ни совпадений, ни явных участников, ни подключённых провайдеров, панель подставляет `empty-fallback`, а если он не задан — `COMPATIBLE`. + +Сохранённые шаблоны не меняются автоматически. Без нового флага `include-all-proxies` и `include-all` работают как обычно: Mihomo сортирует автоматически добавленные локальные прокси по имени. Чтобы перевести существующую группу на порядок панели: + +- Замените `include-all-proxies: true` на `mistgate-ordered-proxies: true`. Оставьте имеющиеся `include-all-providers` и `use` как есть. +- Замените `include-all: true` на `mistgate-ordered-proxies: true` и `include-all-providers: true`, чтобы сохранить всех провайдеров. Если нужно выбрать только отдельных провайдеров в заданном порядке, не включайте `include-all-providers` и перечислите их в `use`. Когда включены все провайдеры, Mihomo игнорирует `use`. +- Удалите оба встроенных флага автодобавления локальных прокси или задайте им `false`, в том числе если они унаследованы через `<<`: панель отклоняет сочетание нового флага с любым из них, если оба включены. Проверьте превью, сохраните шаблон и обновите подписку в приложении. + +С новым флагом панель применяет `filter` к итоговым именам добавляемых прокси, но не к участникам, которых вы перечислили сами. Провайдеры по-прежнему обновляются в Mihomo; панель оставляет в итоговом YAML `filter`, `exclude-filter` и `exclude-type`. Например, `filter: "Germany"` проверяет имя, а не IP или фактическое местоположение. Если в группе есть провайдеры, а в `filter` — несколько выражений через обратную кавычку, Mihomo собирает совпадения по порядку выражений из всех источников и переставляет даже явных участников: `Auto` может перестать быть первым в группе `select`. Сортировка в приложении по имени или задержке может отличаться от порядка ядра, в том числе для `fallback`. + +**Перед откатом:** замените новый флаг на `include-all-proxies: true` в группах, которые от него зависят. Старая панель не добавит участников по этому флагу, и Mihomo может отклонить профиль с пустой группой. Шаблон для группы `ROUTER` на выдуманных именах: @@ -351,11 +358,11 @@ mode: rule proxy-groups: - name: Proxy type: select - include-all-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - include-all-proxies: true + mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -376,21 +383,25 @@ rules: - MATCH,Proxy ``` -Человек из `ROUTER` получит этот текст с его серверами в начале `proxies`, `Auto` в конце `proxy-groups` и секцией `dns`, остальное без изменений. +Человек из `ROUTER` получит свои серверы в начале `proxies`, заполненные списки участников групп `Proxy` и `Germany`, группу `Auto` в конце `proxy-groups` и секцию `dns`. ### Что проверяет сохранение Пределы: 20 шаблонов, по 64 КиБ каждый и 256 КиБ всего; название от 1 до 60 символов (то же название в другом регистре считается тем же); не больше 100 групп в одном шаблоне; группа — только в одном шаблоне. Удалённая группа выпадает из шаблона при следующем сохранении. -Сохранение отклоняет шаблон, называя строку, если: +Сохранение отклоняет шаблон, если: - текст не является корректным UTF-8 или YAML, содержит второй документ (`---`), дважды заданный ключ или алиасы, которые раскрываются намного больше самого текста; - корень не словарь или содержит `<<`, либо `proxies` или `proxy-groups` не обычный список (алиас там позволил бы панели изменить и якорь); - у прокси нет `name`, у группы нет `name` или `type`, имена повторяются или совпадают с именем ядра; - в `proxies` группы названо то, чего нет среди прокси и групп шаблона, имён ядра и `Auto` (пока панель эту группу добавляет), или в `use` — провайдер, которого вы не описали; -- панель не может собрать из него профиль с двумя пробными серверами. +- `mistgate-ordered-proxies` задан не логическим значением YAML, либо группа включает его вместе с `include-all-proxies` или `include-all` либо называется так же, как прокси-провайдер; +- в группе с новым флагом `filter` содержит недопустимое регулярное выражение или сопоставление превышает лимит времени; +- панель не может собрать профиль с тремя пробными серверами, один из которых имеет длинное имя. + +Если время на сопоставление истекло, превью показывает ошибку, а обновление подписки завершается ошибкой вместо выдачи встроенного профиля. В Cloudflare Workers часы не идут во время сопоставления, поэтому там выполнение ограничивает лимит процессорного времени Worker. -Остальные находки сохранение не останавливают и показываются в превью как **Стоит посмотреть**: ни одна группа не берёт серверы человека (добавьте `include-all-proxies` или сошлитесь на `Auto`); в шаблоне свой `dns`; в DNS-пресете человека есть правила рекламы, разделения или стран, которых в шаблоне не будет; в шаблоне свой `Auto`, поэтому панель своего не добавляет; правило ведёт к имени, которого нет в шаблоне; не выбрана ни одна группа. Остальные ключи Mihomo панель не проверяет: для этого прогоните файл через Mihomo. +Остальные находки сохранение не останавливают и показываются в превью как **Стоит посмотреть**: ни одна группа не берёт серверы человека (добавьте `mistgate-ordered-proxies: true` или сошлитесь на `Auto`); в шаблоне свой `dns`; в DNS-пресете человека есть правила рекламы, разделения или стран, которых в шаблоне не будет; в шаблоне свой `Auto`, поэтому панель своего не добавляет; правило ведёт к имени, которого нет в шаблоне; не выбрана ни одна группа. Остальные ключи Mihomo панель не проверяет: для этого прогоните файл через Mihomo. ### Превью diff --git a/docs/zh/guide/subscriptions.md b/docs/zh/guide/subscriptions.md index a40cf62b3..c1b4d9e00 100644 --- a/docs/zh/guide/subscriptions.md +++ b/docs/zh/guide/subscriptions.md @@ -321,7 +321,7 @@ tproxy-port: 1181 | 键 | 面板的处理 | |:--|:--| | `proxies` | 把用户的服务器放在**最前面**,排在你写的代理之前。没有该键(或为 `null`)时会创建。 | -| `proxy-groups` | 只要**自动选择服务器**已开启且模板里没有同名分组,就在末尾加入 `Auto` 分组,即使用户只有一台服务器,这样你的分组才能引用它。它是针对用户服务器(而不是你自己的 `proxies`)的 `url-test`。 | +| `proxy-groups` | 为启用了面板顺序的代理组生成成员列表(见下文)。只要**自动选择服务器**已开启且模板里没有同名分组,就在末尾加入 `Auto` 分组,即使用户只有一台服务器,这样你的分组也能引用它。它是针对用户服务器(而不是你自己的 `proxies`)的 `url-test`。 | | `dns` | 仅当模板里没有时:使用该用户 DNS 预设的解析器,并带 `respect-rules: true`。预设的其他内容都不会加入(见下)。 | 其余一切由你决定:`rules`、`rule-providers`、`proxy-providers`、`tun`、端口。用户 DNS 预设的规则(屏蔽广告、分流、国家)**不会**加入模板,因为规则的顺序和 `MATCH` 由你决定;需要的话请自己写进模板。模板里有自己的 `dns` 时,用户的 DNS 预设及其在页面上的选择不会作用于 Mihomo 类应用(其他应用仍然使用)。 @@ -330,12 +330,19 @@ tproxy-port: 1181 ### 让服务器进入你的分组 -不要在分组里写服务器名称:每个人的服务器不同,用户没有的名称会让 Mihomo 拒绝整个文件,保存时也会被拒绝。请让 Mihomo 自己取服务器: +不要在分组里写用户的服务器名称:每个人的服务器不同,用户没有的名称会让 Mihomo 拒绝整个文件,保存时也会被拒绝。如果面板会添加 `Auto`,可以引用该分组,按速度选择用户的服务器。 -- `include-all-proxies: true` 取用户的服务器和你模板里的代理; -- `filter` 和 `exclude-filter`(正则表达式)按名称筛选,例如 `filter: "Germany"`; -- `include-all: true` 还会取你的 `proxy-providers` 里的分组; -- `Auto` 分组是按速度选择的用户服务器。 +要使用面板顺序,请在每个需要的代理组中设置 `mistgate-ordered-proxies: true`。新模板的 `Proxy` 组默认带有此标记。生成订阅或预览时,Mistgate 保留组内 `proxies` 中明确列出的成员,再按面板顺序加入匹配的用户服务器,最后按声明顺序加入模板中匹配的代理,不重复添加已有名称。该标记保留在已保存的模板中,不会出现在生成的 YAML 中。如果没有匹配项、没有显式成员,也没有启用任何提供者,面板会使用 `empty-fallback`,未设置时则使用 `COMPATIBLE`。 + +已保存的模板不会自动迁移。未启用新标记时,`include-all-proxies` 和 `include-all` 保持 Mihomo 的原有行为:自动加入的本地代理按名称排序。要将现有代理组改为使用面板顺序: + +- 将 `include-all-proxies: true` 替换为 `mistgate-ordered-proxies: true`。保留已有的 `include-all-providers` 和 `use`。 +- 将 `include-all: true` 替换为 `mistgate-ordered-proxies: true` 和 `include-all-providers: true`,以保留所有提供者。如果只想按指定顺序使用选定的提供者,请不要开启 `include-all-providers`,而是在 `use` 中列出它们。启用全部提供者时,Mihomo 会忽略 `use`。 +- 移除两个原生的本地代理自动加入选项,或将它们设为 `false`,包括通过 `<<` 继承的选项。启用新标记时,这两个选项中任意一个为 `true` 都会被面板拒绝。检查预览并保存,然后在应用中刷新订阅。 + +启用新标记后,面板会用 `filter` 匹配自动加入的代理的最终名称,不筛选你明确列出的成员。提供者仍由 Mihomo 动态更新,面板会在输出中保留 `filter`、`exclude-filter` 和 `exclude-type`。例如,`filter: "Germany"` 匹配的是名称,而不是 IP 或实际位置。如果分组使用了提供者,且 `filter` 包含多个用反引号分隔的表达式,Mihomo 会按表达式的顺序收集所有来源的匹配项,包括明确列出的成员:`Auto` 可能不再是 `select` 组的第一项。应用按名称或延迟显示的顺序可能不同于内核使用的顺序,`fallback` 组也是如此。 + +**降级前:** 将依赖新标记的分组改用 `include-all-proxies: true`。旧版面板不会根据新标记添加成员,Mihomo 可能拒绝包含空分组的配置。 下面是用虚构名称写的 `ROUTER` 分组模板: @@ -349,11 +356,11 @@ mode: rule proxy-groups: - name: Proxy type: select - include-all-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - include-all-proxies: true + mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -374,21 +381,25 @@ rules: - MATCH,Proxy ``` -`ROUTER` 中的用户会得到这段文本:其服务器位于 `proxies` 开头,`Auto` 在 `proxy-groups` 末尾,并多出一个 `dns` 段,其余不变。 +`ROUTER` 中的用户会在 `proxies` 开头收到自己的服务器,得到已填入成员的 `Proxy` 和 `Germany` 组、位于 `proxy-groups` 末尾的 `Auto` 组,以及 `dns` 段。 ### 保存时会检查什么 限制:最多 20 个模板,每个最多 64 KiB,合计最多 256 KiB;名称 1 至 60 个字符(同名但大小写不同视为同一个名称);一个模板最多 100 个分组;一个分组只能在一个模板中。你删除的分组会在下次保存时从模板中去掉。 -出现以下情况时,保存会拒绝该模板,并在提示中给出行号: +出现以下情况时,保存会拒绝该模板: - 文本不是有效的 UTF-8 或 YAML,含有第二个文档(`---`)、重复的键,或展开后远大于文本本身的别名; - 根不是映射或含有 `<<`,或 `proxies`、`proxy-groups` 不是普通列表(那里用别名会让面板连锚点一起改掉); - 代理没有 `name`,分组没有 `name` 或 `type`,名称重复,或与内核名称相同; - 分组的 `proxies` 里引用了既不是模板中的代理或分组、也不是内核名称、更不是 `Auto`(只要面板会添加该分组)的名称,或 `use` 里引用了你没有定义的 provider; -- 面板无法用两台示例服务器据此生成配置。 +- `mistgate-ordered-proxies` 不是 YAML 布尔值,或分组启用该标记时也启用了 `include-all-proxies` 或 `include-all`,或与代理提供者重名; +- 启用了新标记的分组含有无效的 `filter` 正则表达式,或匹配超出时间限制; +- 面板无法用三个示例服务器(其中一个名称较长)生成配置。 + +匹配超时后,预览会报告错误,订阅更新也会失败,而不是返回面板自带的配置。Cloudflare Workers 的时钟在匹配期间不会推进,因此最终由 Worker 的 CPU 时间限制中止执行。 -其他发现不会阻止保存,会在预览中显示为**值得一看**:没有分组取用户的服务器(请加 `include-all-proxies` 或引用 `Auto`);模板有自己的 `dns`;用户的 DNS 预设含有模板得不到的广告、分流或国家规则;模板有自己的 `Auto`,所以面板不再添加;某条规则指向模板里不存在的名称;没有选择任何分组。面板不检查 Mihomo 的其余键:请用 Mihomo 自己运行一遍该文件。 +其他发现不会阻止保存,会在预览中显示为**值得一看**:没有分组取用户的服务器(请加 `mistgate-ordered-proxies: true` 或引用 `Auto`);模板有自己的 `dns`;用户的 DNS 预设含有模板得不到的广告、分流或国家规则;模板有自己的 `Auto`,所以面板不再添加;某条规则指向模板里不存在的名称;没有选择任何分组。面板不检查 Mihomo 的其余键:请用 Mihomo 自己运行一遍该文件。 ### 预览 diff --git a/gen/mistgate/admin/v1/subscription.pb.go b/gen/mistgate/admin/v1/subscription.pb.go index 66699ce23..08c90bd7e 100644 --- a/gen/mistgate/admin/v1/subscription.pb.go +++ b/gen/mistgate/admin/v1/subscription.pb.go @@ -789,9 +789,9 @@ func (x *RoutingInfo) GetHeaderBytes() uint32 { // One Mihomo YAML profile of the owner. The panel puts the servers of the person at the start of its `proxies` and, while // link_auto_select is on and the template has no group of that name, adds a url-test group `Auto` over them at the end of its -// `proxy-groups`; groups take the servers with `include-all-proxies` or `filter`. `dns` is added (resolvers of the person's preset, -// respect-rules on) only when the template has none. Everything else is left as written, comments included. The panel never -// fetches a URL of a template. +// `proxy-groups`. Groups can opt in to panel order with `mistgate-ordered-proxies: true`, or let Mihomo include and sort +// servers with `include-all-proxies` or `include-all`. `dns` is added (preset resolvers, respect-rules on) only when the +// template has none. The panel never fetches a URL of a template. // // A save is refused (INVALID_ARGUMENT, the text names the line) unless the text is one valid YAML document that parses in full (no // alias bomb, no repeated key), has a mapping at its root, `proxies` and `proxy-groups` that are lists (or absent) with named @@ -2188,9 +2188,9 @@ func (x *PreviewMihomoTemplateRequest) GetGroupIds() []string { } // One finding that does not stop a save (SubscriptionService words them by code). code is one of: no_server_group (no group takes the -// servers of the person: include-all-proxies, or Auto), own_dns (the person's DNS preset is not applied to this template), -// preset_rules_skipped (the preset has ad, split or country rules that a template does not get), own_auto (the template has its own -// Auto, so the panel adds none), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). +// servers of the person: `mistgate-ordered-proxies`, `include-all-proxies`, `include-all`, or `Auto`), own_dns (the person's +// DNS preset is not applied), preset_rules_skipped (the preset's ad, split or country rules are not applied), own_auto (the +// template has its own Auto), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). type MihomoWarning struct { state protoimpl.MessageState `protogen:"open.v1"` Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` diff --git a/go.mod b/go.mod index cc7255f51..b6b024ba6 100644 --- a/go.mod +++ b/go.mod @@ -26,6 +26,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 github.com/coder/websocket v1.8.15 github.com/descope/virtualwebauthn v1.0.5 + github.com/dlclark/regexp2 v1.12.0 github.com/go-webauthn/webauthn v0.18.2 github.com/google/jsonschema-go v0.4.3 github.com/mdlayher/genetlink v1.4.0 diff --git a/go.sum b/go.sum index a7f859729..0e7503620 100644 --- a/go.sum +++ b/go.sum @@ -140,6 +140,8 @@ github.com/descope/virtualwebauthn v1.0.5 h1:fMXji5UMepJC51Ge6d4v5IAjiJQRKmXE9hl github.com/descope/virtualwebauthn v1.0.5/go.mod h1:lLCfN+DpCM3iisM4bCILZlFEWkC1Zo7ZgsxC45CUapI= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8= +github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/docker/cli v29.8.0+incompatible h1:ih0c2jq/nN7QfES8zIfwSzIhRScjs4ehER+kZ60aeSk= diff --git a/internal/panel/subs/mihomo.go b/internal/panel/subs/mihomo.go index 367492f0e..6a65ecf59 100644 --- a/internal/panel/subs/mihomo.go +++ b/internal/panel/subs/mihomo.go @@ -125,15 +125,17 @@ func (p mihomoProfile) servers() []subsettings.MihomoServer { // render is the profile of one person: the template of their group around their servers, else the built-in profile. The built-in one // is what a person gets when there is no template (tplText ""), when they get a note instead of servers (the note must be seen: a -// template's groups would hide it), when none of their servers can be used, and when the template does not build (a stored text that -// this version cannot read: a log line with the template's name, never its text). tplName is for that line only. -// selected is the source after group selection, for preview warnings even if no servers could be inserted. +// template's groups would hide it), when none of their servers can be used, and when the template cannot be read. If matching +// runs out of time, return an error instead of replacing the person's profile. selected is the source after group selection, +// for preview warnings even if no servers could be inserted. func (p mihomoProfile) render(tplName, tplText string) (body []byte, selected string, templated bool, err error) { if tplText != "" && !p.note { body, selected, err = p.buildFromTemplate(tplText) switch { case err == nil: return body, selected, true, nil + case errors.Is(err, subsettings.ErrMihomoFilterBudget): + return nil, selected, false, err case errors.Is(err, subsettings.ErrNoServers): default: if p.log != nil { diff --git a/internal/panel/subs/mihomo_node_order_test.go b/internal/panel/subs/mihomo_node_order_test.go index d20a50521..0b4579753 100644 --- a/internal/panel/subs/mihomo_node_order_test.go +++ b/internal/panel/subs/mihomo_node_order_test.go @@ -73,6 +73,13 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { t.Fatalf("Mihomo proxies = %v, want %v", got, want) } } + proxyNames := func(proxies []endpoint) []string { + names := make([]string, 0, len(proxies)) + for _, p := range proxies { + names = append(names, p.name) + } + return names + } geoAnswer := answerOf(t, r.body(t, token)) geo := endpoints(geoAnswer) // C's direct proxy precedes the two protocols and their paths on D in the original geographic order. @@ -93,6 +100,12 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { !strings.HasPrefix(geo[0].name, "p") || !strings.HasPrefix(geo[1].name, "p") { t.Fatalf("expected relay port and disambiguated direct names: %v", geo) } + geoNames := proxyNames(geo) + selectMembers := append(append([]string{"Auto"}, geoNames...), "DIRECT") + if len(geoAnswer.Groups) != 2 || !slices.Equal(geoAnswer.Groups[0].Proxies, selectMembers) || + geoAnswer.Groups[1].Name != "Auto" || !slices.Equal(geoAnswer.Groups[1].Proxies, geoNames) { + t.Fatalf("built-in groups = %+v, want select %v and Auto %v", geoAnswer.Groups, selectMembers, geoNames) + } // Compare ordered labels, not credentials. Read again after cache expiry, so an unchanged stale view cannot hide a bug. otherOrders := func() [4][]string { @@ -161,20 +174,34 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { } const draft = `proxies: - {name: authored-z, type: socks5, server: z.example.com, port: 1080} + - {name: authored-y, type: socks5, server: y.example.com, port: 1080} - {name: authored-a, type: socks5, server: a.example.com, port: 1080} proxy-groups: - name: Work type: select - include-all-proxies: true - proxies: [authored-z, DIRECT, authored-a] + mistgate-ordered-proxies: true + proxies: [authored-z, DIRECT] rules: - MATCH,Work ` - templateEndpoints := func(generated []endpoint) []endpoint { - return append(slices.Clone(generated), endpoint{"authored-z", "socks5", "z.example.com", 1080}, endpoint{"authored-a", "socks5", "a.example.com", 1080}) + authored := []endpoint{ + {"authored-z", "socks5", "z.example.com", 1080}, + {"authored-y", "socks5", "y.example.com", 1080}, + {"authored-a", "socks5", "a.example.com", 1080}, } - previewAnswer := func() tplAnswer { + assertTemplate := func(a tplAnswer, generated []endpoint) { + t.Helper() + assertEndpoints(a, slices.Concat(generated, authored)) + names := proxyNames(generated) + workMembers := append(append([]string{"authored-z", "DIRECT"}, names...), "authored-y", "authored-a") + if len(a.Groups) != 2 || + a.Groups[0].Name != "Work" || !slices.Equal(a.Groups[0].Proxies, workMembers) || + a.Groups[1].Name != "Auto" || !slices.Equal(a.Groups[1].Proxies, names) { + t.Fatalf("template groups = %+v, want Work %v and Auto %v", a.Groups, workMembers, names) + } + } + previewAnswer := func(user string) tplAnswer { t.Helper() resp, err := r.preview(t, preview, user, draft, r.group2) if err != nil { @@ -182,62 +209,55 @@ rules: } return answerOf(t, resp.Yaml) } + // Save the opted-in template once; neither order change should require editing it. + r.save(t, nameByProfile, &adminv1.MihomoTemplate{Name: "work", Yaml: draft, GroupIds: []string{r.group2}}) + assertTemplate(answerOf(t, r.body(t, token)), geo) + assertTemplate(previewAnswer(user), geo) order := []string{"nod_b", d, "nod_a", "nod_c"} if err := r.st.SetNodeOrder(r.ctx, nil, order); err != nil { t.Fatal(err) } // Only D and C are usable; the relay through C still travels with D. manual := append(slices.Clone(geo[1:]), geo[0]) - assertEndpoints(previewAnswer(), templateEndpoints(manual)) + assertTemplate(previewAnswer(user), manual) clock = clock.Add(ttl - time.Nanosecond) - assertEndpoints(answerOf(t, r.body(t, token)), geo) + assertTemplate(answerOf(t, r.body(t, token)), geo) clock = clock.Add(time.Nanosecond) - actual := answerOf(t, r.body(t, token)) - assertEndpoints(actual, manual) - names := make([]string, 0, len(manual)) - for _, p := range manual { - names = append(names, p.name) - } - selectMembers := append(append([]string{"Auto"}, names...), "DIRECT") - if len(actual.Groups) != 2 || !slices.Equal(actual.Groups[0].Proxies, selectMembers) || - actual.Groups[1].Name != "Auto" || !slices.Equal(actual.Groups[1].Proxies, names) { - t.Fatalf("built-in groups = %+v, want select %v and Auto %v", actual.Groups, selectMembers, names) - } + assertTemplate(answerOf(t, r.body(t, token)), manual) assertManualOtherFormats() - r.save(t, nameByProfile, &adminv1.MihomoTemplate{Name: "work", Yaml: draft, GroupIds: []string{r.group2}}) - for _, a := range []tplAnswer{answerOf(t, r.body(t, token)), previewAnswer()} { - assertEndpoints(a, templateEndpoints(manual)) - if len(a.Groups) != 2 || !slices.Equal(a.Groups[0].Proxies, []string{"authored-z", "DIRECT", "authored-a"}) || - a.Groups[1].Name != "Auto" || !slices.Equal(a.Groups[1].Proxies, names) { - t.Fatalf("template groups = %+v", a.Groups) - } - } - // Unlisted nodes follow the saved IDs in geographic order (F before E, opposite their IDs). - r.save(t, nameByProfile) addNode("nod_f", "node-f", "AU") addNode("nod_e", "node-e", "FR") - _, newToken := r.newUser("bob", func(c *adminv1.CreateUserRequest) { + bob, bobToken := r.newUser("bob", func(c *adminv1.CreateUserRequest) { c.Nodes = &adminv1.NodeSelection{NodeIds: []string{d, "nod_c", "nod_e", "nod_f"}} }) - withAdditions := endpoints(answerOf(t, r.body(t, newToken))) - if len(withAdditions) != len(manual)+2 || !slices.Equal(withAdditions[:len(manual)], manual) || - withAdditions[len(manual)].server != "node-f.example.com" || withAdditions[len(manual)+1].server != "node-e.example.com" { - t.Fatalf("manual order with unlisted nodes = %v", withAdditions) + bobManual := answerOf(t, r.body(t, bobToken)) + bobEndpoints := endpoints(bobManual) + if len(bobEndpoints) != len(manual)+2+len(authored) { + t.Fatalf("Bob's proxies = %v, want two more nodes than Alice", bobEndpoints) + } + f, e := bobEndpoints[len(manual)], bobEndpoints[len(manual)+1] + if f.server != "node-f.example.com" || e.server != "node-e.example.com" || + f.kind != "hysteria2" || e.kind != "hysteria2" { + t.Fatalf("Bob's extra proxies = %v, %v; want Hysteria2 on F then E", f, e) } - f, e := withAdditions[len(manual)], withAdditions[len(manual)+1] + withAdditions := append(slices.Clone(manual), f, e) + assertTemplate(bobManual, withAdditions) + assertTemplate(previewAnswer(bob), withAdditions) + bobGeo := append([]endpoint{f, geo[0], e}, geo[1:]...) if err := r.st.SetNodeOrder(r.ctx, order, nil); err != nil { t.Fatal(err) } // Preview builds a fresh view, even while repeated HTTP requests still use the previous order. - assertEndpoints(previewAnswer(), templateEndpoints(geo)) + assertTemplate(previewAnswer(user), geo) + assertTemplate(previewAnswer(bob), bobGeo) clock = clock.Add(ttl - time.Nanosecond) - assertEndpoints(answerOf(t, r.body(t, token)), manual) - assertEndpoints(answerOf(t, r.body(t, newToken)), withAdditions) + assertTemplate(answerOf(t, r.body(t, token)), manual) + assertTemplate(answerOf(t, r.body(t, bobToken)), withAdditions) clock = clock.Add(time.Nanosecond) - assertEndpoints(answerOf(t, r.body(t, token)), geo) - assertEndpoints(answerOf(t, r.body(t, newToken)), append([]endpoint{f, geo[0], e}, geo[1:]...)) + assertTemplate(answerOf(t, r.body(t, token)), geo) + assertTemplate(answerOf(t, r.body(t, bobToken)), bobGeo) for i, got := range otherOrders() { if !slices.Equal(got, original[i]) { t.Errorf("format %d order after reset = %v, want %v", i, got, original[i]) diff --git a/internal/panel/subs/mihomo_order_core_test.go b/internal/panel/subs/mihomo_order_core_test.go new file mode 100644 index 000000000..a8b7cd69c --- /dev/null +++ b/internal/panel/subs/mihomo_order_core_test.go @@ -0,0 +1,364 @@ +package subs + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "testing" + "time" +) + +// Observe the effective order in the core, not merely the order of the rendered YAML. +// Mihomo v1.19.34 reapplies multi-part filter priorities across providers after assembling a group. +func TestMihomoCoreOrderedGroups(t *testing.T) { + bin := os.Getenv("MIHOMO_BIN") + if bin == "" { + t.Skip("set MIHOMO_BIN to the Mihomo v1.19.34 executable") + } + + health := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodHead || r.URL.Path != "/health" { + http.NotFound(w, r) + return + } + w.Header().Set("Connection", "close") + w.WriteHeader(http.StatusNoContent) + })) + t.Cleanup(health.Close) + healthURL := health.URL + "/health" + target := health.Listener.Addr().(*net.TCPAddr) + httpPort := orderedMihomoHTTPProxy(t, target.String()) + socksPort := orderedMihomoSOCKSProxy(t, target.Port) + proxy := func(name, kind string, port int) string { + return fmt.Sprintf("- {name: %q, type: %s, server: 127.0.0.1, port: %d}\n", name, kind, port) + } + p := mihomoProfile{title: "Order fixture"} + for _, node := range []string{"DE-2", "LV", "DE-1", "KZ", "RU"} { + // Both the country order and the order of transports deliberately differ from name sorting. + p.names = append(p.names, node+" socks5", node+" http") + p.lines = append(p.lines, proxy("fragment", "socks5", socksPort), proxy("fragment", "http", httpPort)) + } + + dir := t.TempDir() + for _, provider := range []struct{ file, name string }{ + {"pasha.yaml", "Pasha"}, {"oversecure.yaml", "Oversecure"}, + } { + var file strings.Builder + file.WriteString("proxies:\n") + for _, country := range []string{"DE", "KZ", "RU"} { + file.WriteString(proxy(provider.name+" "+country, "http", httpPort)) + } + if err := os.WriteFile(filepath.Join(dir, provider.file), []byte(file.String()), 0o600); err != nil { + t.Fatal(err) + } + } + + tpl := fmt.Sprintf(`external-controller: '127.0.0.1:0' +log-level: info +geo-auto-update: false +unified-delay: false +proxies: + - {name: '16', type: http, server: 127.0.0.1, port: %[3]d} +proxy-providers: + mistgate-ordered-proxies: + type: file + path: pasha.yaml + health-check: {enable: true, url: %[1]q, expected-status: '204'} + oversecure: + type: file + path: oversecure.yaml + health-check: {enable: true, url: %[1]q, expected-status: '204'} +proxy-groups: + - name: Auto + type: fallback + mistgate-ordered-proxies: true + use: [oversecure, mistgate-ordered-proxies] + url: %[1]q + expected-status: '204' + - name: AI Auto + type: fallback + mistgate-ordered-proxies: true + use: [mistgate-ordered-proxies, oversecure] + filter: %[2]q + exclude-filter: '(^| )RU( |$)' + url: %[1]q + expected-status: '204' + - name: Native all proxies + type: select + include-all-proxies: true + - name: Provider only + type: select + use: [mistgate-ordered-proxies, oversecure] + - name: Numeric filter and folded proxies key + type: select + mistgate-ordered-proxies: true + PROXIES: [DIRECT] + filter: 0x10 + - name: Numeric fallback + type: select + mistgate-ordered-proxies: true + filter: '^No match$' + empty-fallback: 0x10 + - name: Exact proxies key + type: select + mistgate-ordered-proxies: true + PROXIES: [REJECT] + proxies: [DIRECT] + filter: '^KZ' +rules: ['MATCH,Auto'] +`, healthURL, "KZ`.*", httpPort) + out, used := templated(t, tpl, p) + if !used { + t.Fatal("the built-in profile was sent") + } + if strings.Contains(out, "mistgate-ordered-proxies: true") || !strings.Contains(out, "include-all-proxies: true") { + t.Fatal("rendered profile must strip Mistgate's directive and retain the native flag") + } + + alphabetical := append(slices.Clone(p.names), "16") + slices.Sort(alphabetical) + + got := orderedMihomoCoreProxies(t, bin, dir, out, healthURL, p.names) + for _, want := range []struct { + group, kind string + all []string + }{ + {"Auto", "Fallback", []string{ + "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "KZ socks5", "KZ http", "RU socks5", "RU http", + "16", "Oversecure DE", "Oversecure KZ", "Oversecure RU", "Pasha DE", "Pasha KZ", "Pasha RU", + }}, + {"AI Auto", "Fallback", []string{ + "KZ socks5", "KZ http", "Pasha KZ", "Oversecure KZ", + "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "16", "Pasha DE", "Oversecure DE", + }}, + {"Provider only", "Selector", []string{"Pasha DE", "Pasha KZ", "Pasha RU", "Oversecure DE", "Oversecure KZ", "Oversecure RU"}}, + {"Native all proxies", "Selector", alphabetical}, + {"Numeric filter and folded proxies key", "Selector", []string{"DIRECT", "16"}}, + {"Numeric fallback", "Selector", []string{"16"}}, + {"Exact proxies key", "Selector", []string{"DIRECT", "KZ socks5", "KZ http"}}, + } { + g := got[want.group] + if g.Type != want.kind || !slices.Equal(g.All, want.all) || g.Now != want.all[0] { + t.Errorf("%s: type=%q all=%q now=%q; want type=%q all=%q now=%q", want.group, g.Type, g.All, g.Now, want.kind, want.all, want.all[0]) + } + } +} + +type orderedMihomoProxy struct { + Type string `json:"type"` + All []string `json:"all"` + Now string `json:"now"` + Extra map[string]struct { + Alive bool `json:"alive"` + History []struct { + Delay uint16 `json:"delay"` + } `json:"history"` + } `json:"extra"` +} + +func orderedMihomoCoreProxies(t *testing.T, bin, dir, config, healthURL string, locals []string) map[string]orderedMihomoProxy { + t.Helper() + cfg := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(cfg, []byte(config), 0o600); err != nil { + t.Fatal(err) + } + logFile, err := os.Create(filepath.Join(dir, "mihomo.log")) + if err != nil { + t.Fatal(err) + } + defer logFile.Close() + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + t.Cleanup(cancel) + cmd := exec.CommandContext(ctx, bin, "-d", dir, "-f", cfg) + // Don't inherit controller overrides, shell hooks or proxy environment variables. + cmd.Env = []string{"NO_COLOR=1"} + cmd.Stdout, cmd.Stderr = logFile, logFile + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + var exitErr error + go func() { + exitErr = cmd.Wait() + close(done) + }() + t.Cleanup(func() { + cancel() + <-done + if t.Failed() { + log, _ := os.ReadFile(logFile.Name()) + t.Logf("Mihomo output:\n%s", log) + } + }) + + // Let the core bind port zero itself; reserving and releasing a Go listener would race other tests. + bound := regexp.MustCompile(`RESTful API listening at: (127\.0\.0\.1:[0-9]+)`) + client := &http.Client{Transport: &http.Transport{}, Timeout: time.Second} + defer client.CloseIdleConnections() + tick := time.NewTicker(25 * time.Millisecond) + defer tick.Stop() + var status, endpoint string + for { + if endpoint == "" { + status = "waiting for the loopback controller" + log, err := os.ReadFile(logFile.Name()) + if err != nil { + t.Fatal(err) + } + if m := bound.FindSubmatch(log); m != nil { + endpoint = "http://" + string(m[1]) + "/proxies" + } + } + if endpoint != "" { + if got, err := orderedMihomoSnapshot(ctx, client, endpoint, healthURL, locals); err == nil { + return got + } else { + status = err.Error() + } + } + select { + case <-done: + t.Fatalf("Mihomo exited (%v): %s", exitErr, status) + case <-ctx.Done(): + t.Fatalf("Mihomo did not become ready: %s", status) + case <-tick.C: + } + } +} + +func orderedMihomoSnapshot(ctx context.Context, client *http.Client, endpoint, healthURL string, locals []string) (map[string]orderedMihomoProxy, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("GET /proxies: %s", resp.Status) + } + var snapshot struct { + Proxies map[string]orderedMihomoProxy `json:"proxies"` + } + if err := json.NewDecoder(resp.Body).Decode(&snapshot); err != nil { + return nil, err + } + // The controller can respond before provider loading or before the first health pass. + all := snapshot.Proxies["Provider only"].All + if !slices.Contains(all, "Pasha DE") || !slices.Contains(all, "Oversecure DE") { + return nil, fmt.Errorf("file providers not loaded: %q", all) + } + for _, name := range locals { + h := snapshot.Proxies[name].Extra[healthURL] + // Before the first actual check, Mihomo considers proxies alive by default. + if n := len(h.History); !h.Alive || n == 0 || h.History[n-1].Delay == 0 { + return nil, fmt.Errorf("%q has no successful health check at %s", name, healthURL) + } + } + return snapshot.Proxies, nil +} + +func orderedMihomoHTTPProxy(t *testing.T, target string) int { + t.Helper() + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodConnect || r.Host != target { + http.Error(w, "only the local health endpoint is allowed", http.StatusForbidden) + return + } + conn, rw, err := http.NewResponseController(w).Hijack() + if err != nil { + return + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(2 * time.Second)) + orderedMihomoTunnel(conn, rw, target, func() error { + if _, err := rw.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil { + return err + } + return rw.Flush() + }) + })) + t.Cleanup(s.Close) + return s.Listener.Addr().(*net.TCPAddr).Port +} + +func orderedMihomoSOCKSProxy(t *testing.T, targetPort int) int { + t.Helper() + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + target := fmt.Sprintf("127.0.0.1:%d", targetPort) + want := [10]byte{5, 1, 0, 1, 127, 0, 0, 1, byte(targetPort >> 8), byte(targetPort)} + var workers sync.WaitGroup + done := make(chan struct{}) + go func() { + defer close(done) + for { + conn, err := ln.Accept() + if err != nil { + return + } + workers.Go(func() { + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(2 * time.Second)) + // Accept only no-auth negotiation and an IPv4 CONNECT to the health fixture. + var hello [3]byte + if _, err := io.ReadFull(conn, hello[:]); err != nil || hello != [3]byte{5, 1, 0} { + return + } + if _, err := conn.Write([]byte{5, 0}); err != nil { + return + } + var request [10]byte + if _, err := io.ReadFull(conn, request[:]); err != nil || request != want { + return + } + orderedMihomoTunnel(conn, conn, target, func() error { + _, err := conn.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 0}) + return err + }) + }) + } + }() + t.Cleanup(func() { + _ = ln.Close() + <-done + workers.Wait() + }) + return ln.Addr().(*net.TCPAddr).Port +} + +func orderedMihomoTunnel(client net.Conn, in io.Reader, target string, ready func() error) { + upstream, err := net.DialTimeout("tcp4", target, time.Second) + if err != nil { + return + } + defer upstream.Close() + _ = upstream.SetDeadline(time.Now().Add(2 * time.Second)) + if err := ready(); err != nil { + return + } + done := make(chan struct{}) + go func() { + _, _ = io.Copy(upstream, in) + _ = upstream.(*net.TCPConn).CloseWrite() + close(done) + }() + _, _ = io.Copy(client, upstream) + _ = client.Close() + <-done +} diff --git a/internal/panel/subs/mihomo_preview.go b/internal/panel/subs/mihomo_preview.go index d62f74d90..8ef8368ef 100644 --- a/internal/panel/subs/mihomo_preview.go +++ b/internal/panel/subs/mihomo_preview.go @@ -84,6 +84,12 @@ func (s *Service) PreviewMihomoTemplate(ctx context.Context, req *connect.Reques } body, selected, templated, err := p.render("draft", m.Yaml) if err != nil { + if errors.Is(err, subsettings.ErrMihomoFilterBudget) { + if canceled := contextError(err); canceled != nil { + return nil, canceled + } + return nil, connect.NewError(connect.CodeInvalidArgument, err) + } return nil, internal("preview render", err) } if p.note { diff --git a/internal/panel/subs/mihomo_preview_test.go b/internal/panel/subs/mihomo_preview_test.go index 4360d5fed..151275619 100644 --- a/internal/panel/subs/mihomo_preview_test.go +++ b/internal/panel/subs/mihomo_preview_test.go @@ -113,7 +113,7 @@ func TestPreviewMihomoTemplate(t *testing.T) { func TestPreviewMihomoShowsEmojiInNames(t *testing.T) { r := newTemplateRig(t, nil) - const draft = "mode: rule\nproxy-groups:\n - name: 🌍 VPN\n type: select\n include-all-proxies: true\nrules:\n - MATCH,🌍 VPN\n" + const draft = "mode: rule\nproxy-groups:\n - name: 🌍 VPN\n type: select\n mistgate-ordered-proxies: true\nrules:\n - MATCH,🌍 VPN\n" r.save(t, func(s *adminv1.SubscriptionSettings) { s.ServerNameTemplate = "🇫🇮 {profile}" }, routerTemplate(r, r.group2)) alice, _ := r.newUser("alice", nil) resp, err := r.preview(t, r.previewService(t, plainPreset), alice, draft, r.group2) @@ -128,6 +128,9 @@ func TestPreviewMihomoShowsEmojiInNames(t *testing.T) { len(a.Groups) == 0 || a.Groups[0].Name != "🌍 VPN" || len(a.Rules) == 0 || a.Rules[0] != "MATCH,🌍 VPN" { t.Fatal("the Unicode preview did not preserve the names and rule") } + if got, want := a.Groups[0].Proxies, a.Proxies[0]["name"].(string); len(got) == 0 || got[0] != want { + t.Errorf("the Unicode proxy name was not preserved in the group: got %q, first member should be %q", got, want) + } } // A preview writes nothing: not a device, not a credential, not the mark that the link was fetched. diff --git a/internal/panel/subs/mihomo_template_core_test.go b/internal/panel/subs/mihomo_template_core_test.go index 87aeedd70..1446f9158 100644 --- a/internal/panel/subs/mihomo_template_core_test.go +++ b/internal/panel/subs/mihomo_template_core_test.go @@ -21,7 +21,8 @@ func TestMihomoCoreAcceptsTemplates(t *testing.T) { {"router with one server", router, func(p *mihomoProfile) { p.lines, p.names = p.lines[:1], p.names[:1] }}, {"router without Auto", strings.Replace(router, "proxies: [Auto, DIRECT] # the panel's Auto group", "proxies: [DIRECT]", 1), func(p *mihomoProfile) { p.autoSelect = false }}, {"pc with its own dns and a filter that matches nothing", pc, nil}, - {"a group of only the servers", "proxy-groups:\n - name: Proxy\n type: select\n include-all-proxies: true\nrules:\n - MATCH,Proxy\n", nil}, + {"a native include-all-proxies group", "proxy-groups:\n - name: Proxy\n type: select\n include-all-proxies: true\nrules:\n - MATCH,Proxy\n", nil}, + {"a native integer provider flag", "proxy-groups:\n - name: Proxy\n type: select\n include-all-providers: 1\n proxies: [DIRECT]\nrules:\n - MATCH,Proxy\n", nil}, {"a template of one key", "mixed-port: 7890\n", nil}, } { t.Run(c.name, func(t *testing.T) { diff --git a/internal/panel/subs/mihomo_template_internal_test.go b/internal/panel/subs/mihomo_template_internal_test.go index adc6736a6..5a6067377 100644 --- a/internal/panel/subs/mihomo_template_internal_test.go +++ b/internal/panel/subs/mihomo_template_internal_test.go @@ -312,7 +312,7 @@ func TestMihomoTemplateDNS(t *testing.T) { func TestMihomoTemplateKeepsTheText(t *testing.T) { out, _ := templated(t, templateText(t, "mihomo_template_router.yaml"), twoServers(t)) for _, want := range []string{ - "# Router: transparent proxy for the LAN.", "x-check: &check", "<<: *check", "bind-address: \"*\"", "proxies: [Auto, DIRECT] # the panel's Auto group", + "# Router: transparent proxy for the LAN.", "x-check: &check", "<<: *check", "bind-address: \"*\"", "# the panel's Auto group", "filter: \"(?i)de|nl\"", "- GEOIP,LAN,DIRECT,no-resolve", } { if !strings.Contains(out, want) { @@ -328,7 +328,7 @@ func TestMihomoTemplateKeepsTheText(t *testing.T) { func TestMihomoTemplateDoesNotFoldLongLines(t *testing.T) { long := "DOMAIN-SUFFIX," + strings.Repeat("a", 280) + ".example.com,Proxy" regex := "(?i)" + strings.Repeat("alpha|", 60) + "omega" - tpl := "proxy-groups:\n - name: Proxy\n type: select\n include-all-proxies: true\n filter: \"" + regex + "\"\nrules:\n - " + long + "\n - MATCH,Proxy\n" + tpl := "proxy-groups:\n - name: Proxy\n type: select\n mistgate-ordered-proxies: true\n filter: \"" + regex + "\"\nrules:\n - " + long + "\n - MATCH,Proxy\n" out, _ := templated(t, tpl, mihomoProfile{title: "T", lines: []string{fixture(t, hy2Line)}, autoSelect: true}) if !strings.Contains(out, "\n - "+long+"\n") || !strings.Contains(out, "filter: \""+regex+"\"\n") { t.Errorf("a long line was folded:\n%s", out) diff --git a/internal/panel/subs/mihomo_template_test.go b/internal/panel/subs/mihomo_template_test.go index 0c32b0c3e..93e17d7ab 100644 --- a/internal/panel/subs/mihomo_template_test.go +++ b/internal/panel/subs/mihomo_template_test.go @@ -2,6 +2,7 @@ package subs_test import ( "bytes" + "errors" "fmt" "log/slog" "net/http" @@ -9,6 +10,7 @@ import ( "os" "path/filepath" "reflect" + "runtime" "slices" "strings" "testing" @@ -302,7 +304,7 @@ dns: proxy-groups: - name: Proxy type: select - include-all-proxies: true + mistgate-ordered-proxies: true proxies: - DIRECT # @mistgate-if [%[2]q] @@ -357,15 +359,25 @@ rules: } else if _, present := doc["proxy-providers"]; present || strings.Contains(output, "comment.example") { t.Errorf("other group got the PC block:\n%s", output) } + wantMembers = append(wantMembers, "p") + if tc.name == "ROUTER" { + wantMembers = append(wantMembers, "awg31") + } dns, _ := doc["dns"].(map[string]any) if doc["find-process-mode"] != tc.process || !reflect.DeepEqual(doc["tun"], wantTun) || !reflect.DeepEqual(dns["fake-ip-filter"], wantFilter) || !reflect.DeepEqual(doc["rules"], wantRules) { t.Errorf("wrong effective profile:\n%s", output) } groups := doc["proxy-groups"].([]any) - if got := groups[0].(map[string]any)["proxies"]; !reflect.DeepEqual(got, wantMembers) { + proxyGroup := groups[0].(map[string]any) + if got := proxyGroup["proxies"]; !reflect.DeepEqual(got, wantMembers) { t.Errorf("Proxy members = %v, want %v", got, wantMembers) } + for _, key := range []string{"mistgate-ordered-proxies", "include-all-proxies", "include-all", "include-all-providers"} { + if v, present := proxyGroup[key]; present { + t.Errorf("rendered Proxy group has unexpected %s: %v", key, v) + } + } var desktop bool for _, g := range groups { m := g.(map[string]any) @@ -524,6 +536,48 @@ func TestMihomoTemplateUnreadableInTheDatabase(t *testing.T) { } } +func TestMihomoTemplateFilterBudget(t *testing.T) { + if runtime.GOOS == "js" { + t.Skip("regexp2 cannot enforce a deadline during synchronous WebAssembly matching") + } + const text = `proxy-groups: + - name: Pick + type: select + mistgate-ordered-proxies: true + filter: '^(b|bb)+$' +rules: ['MATCH,Pick'] +` + r := newTemplateRig(t, nil) + alice, token := r.newUser("alice", nil) + // The filter passes the trial build but not this person's real server name. + name := strings.Repeat("b", 64) + "!" + if _, err := r.st.W.Exec(`UPDATE node SET name = ? WHERE id = 'nod_1'`, name); err != nil { + t.Fatal(err) + } + r.save(t, func(s *adminv1.SubscriptionSettings) { s.ServerNameTemplate = "{node}" }, + &adminv1.MihomoTemplate{Name: "ordered", Yaml: text, GroupIds: []string{r.group2}}) + + t.Run("subscription", func(t *testing.T) { + rec := fetch(r.h, "/"+token, mihomoUA, "Accept-Encoding", "gzip") + if rec.Code != http.StatusInternalServerError || rec.Body.String() != "internal error\n" || + rec.Header().Get("Content-Encoding") != "" { + t.Fatalf("expected an HTTP error without a replacement profile, got %d, %v, %q", rec.Code, rec.Header(), rec.Body) + } + log := r.logs.String() + if !strings.Contains(log, "code=mihomo_template_filter_budget") || + !strings.Contains(log, subsettings.ErrMihomoFilterBudget.Error()) || + strings.Contains(log, "mihomo_template_unusable") || strings.Contains(log, name) || strings.Contains(log, "^(b|bb)+$") { + t.Errorf("expected a distinct, redacted filter budget log, got %q", log) + } + }) + t.Run("preview", func(t *testing.T) { + resp, err := r.preview(t, r.previewService(t, plainPreset), alice, text, r.group2) + if resp != nil || connect.CodeOf(err) != connect.CodeInvalidArgument || !errors.Is(err, subsettings.ErrMihomoFilterBudget) { + t.Fatalf("preview returned %v, %v; want InvalidArgument for the filter budget and no profile", resp, err) + } + }) +} + // The template is read only as text: the panel opens no connection of its own for the URLs in it (the providers are the apps'). func TestMihomoTemplateNeverFetchesItsURLs(t *testing.T) { hit := make(chan string, 4) diff --git a/internal/panel/subs/subs.go b/internal/panel/subs/subs.go index a61010335..26f844122 100644 --- a/internal/panel/subs/subs.go +++ b/internal/panel/subs/subs.go @@ -784,7 +784,11 @@ func (h *handler) writeMihomo(w http.ResponseWriter, r *http.Request, token stri } body, _, _, err := p.render(tplName, tplText) if err != nil { - h.cfg.Log.Error("mihomo profile", "code", "subscription_mihomo_render_failed", "err", err) + code := "subscription_mihomo_render_failed" + if errors.Is(err, subsettings.ErrMihomoFilterBudget) { + code = "mihomo_template_filter_budget" + } + h.cfg.Log.Error("mihomo profile", "code", code, "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } diff --git a/internal/panel/subs/testdata/mihomo_template_pc.out.yaml b/internal/panel/subs/testdata/mihomo_template_pc.out.yaml index 2c7ed7b5e..9fbddbe1e 100644 --- a/internal/panel/subs/testdata/mihomo_template_pc.out.yaml +++ b/internal/panel/subs/testdata/mihomo_template_pc.out.yaml @@ -67,15 +67,19 @@ proxies: proxy-groups: - name: Servers type: select - include-all-proxies: true + proxies: + - "\U0001F1E9\U0001F1EA de1 · hy2" + - "\U0001F1F3\U0001F1F1 nl1 · awg" + - "office-socks" - name: Work type: select use: [office] proxies: [office-socks, DIRECT] - name: Nobody type: url-test - include-all-proxies: true filter: "no-such-server" + proxies: + - "COMPATIBLE" - name: "Auto" type: url-test proxies: diff --git a/internal/panel/subs/testdata/mihomo_template_pc.yaml b/internal/panel/subs/testdata/mihomo_template_pc.yaml index 1b973c30b..af13d9113 100644 --- a/internal/panel/subs/testdata/mihomo_template_pc.yaml +++ b/internal/panel/subs/testdata/mihomo_template_pc.yaml @@ -18,14 +18,14 @@ proxies: proxy-groups: - name: Servers type: select - include-all-proxies: true + mistgate-ordered-proxies: true - name: Work type: select use: [office] proxies: [office-socks, DIRECT] - name: Nobody type: url-test - include-all-proxies: true + mistgate-ordered-proxies: true filter: "no-such-server" dns: diff --git a/internal/panel/subs/testdata/mihomo_template_router.out.yaml b/internal/panel/subs/testdata/mihomo_template_router.out.yaml index 1ab3ea310..97d798aa2 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.out.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.out.yaml @@ -13,8 +13,7 @@ x-check: &check proxy-groups: - name: Proxy type: select - include-all-proxies: true - proxies: [Auto, DIRECT] # the panel's Auto group + proxies: [Auto, DIRECT, "\U0001F1E9\U0001F1EA de1 · hy2", "\U0001F1F3\U0001F1F1 nl1 · awg"] # the panel's Auto group - name: Fast <<: *check type: url-test diff --git a/internal/panel/subs/testdata/mihomo_template_router.yaml b/internal/panel/subs/testdata/mihomo_template_router.yaml index 4d9684129..b87432398 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.yaml @@ -15,7 +15,7 @@ x-check: &check proxy-groups: - name: Proxy type: select - include-all-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # the panel's Auto group - name: Fast <<: *check diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index 4d9943fa1..cfbd1680b 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -22,9 +22,9 @@ import ( // the save is the trust boundary. Names of servers are hostile input: they enter the document as yaml.Node values with a quoted // style, never as text. // -// The panel touches three keys of the root: `proxies` (the person's servers go first), `proxy-groups` (an `Auto` group is added at -// the end while the switch of automatic selection is on and the template has no name `Auto`) and `dns` (added only when the template -// has none). The rest is encoded back as it was read, comments and anchors included. +// The panel touches three keys of the root: `proxies` (the person's servers go first), `proxy-groups` (groups may opt in to +// ordered local members, and an `Auto` group may be added) and `dns` (added only when the template has none). +// The rest is encoded back as it was read, comments and anchors included. // Limits enforced by Validate. const ( @@ -53,7 +53,6 @@ const ( const ( maxRuleTargetWarnings = 10 autoURL = "https://www.gstatic.com/generate_204" - trialServerCount = 2 ) // MihomoWarning is one finding of a template that does not stop a save: the profile works, and the owner should look. @@ -202,10 +201,19 @@ func parseDocument(text string) (doc, root *yaml.Node, err error) { return doc, doc.Content[0], nil } +// yaml.v3 resolves aliases when decoding mapping keys. Use the same key +// when editing the node tree, without replacing the alias in the document. +func mappingKey(n *yaml.Node) *yaml.Node { + if n.Kind == yaml.AliasNode { + return n.Alias + } + return n +} + // rootValue is the value of a key of the root mapping and the index of that value in root.Content; nil, -1 when the key is absent. func rootValue(root *yaml.Node, key string) (*yaml.Node, int) { for i := 0; i+1 < len(root.Content); i += 2 { - if k := root.Content[i]; k.Kind == yaml.ScalarNode && k.Value == key { + if k := mappingKey(root.Content[i]); k.Kind == yaml.ScalarNode && k.Value == key { return root.Content[i+1], i + 1 } } @@ -221,9 +229,9 @@ func checkRootShape(root *yaml.Node) error { return fmt.Errorf("line %d: the root must be a mapping (key: value lines)", root.Line) } for i := 0; i+1 < len(root.Content); i += 2 { - k, v := root.Content[i], root.Content[i+1] + k, v := mappingKey(root.Content[i]), root.Content[i+1] if k.Kind == yaml.ScalarNode && (k.ShortTag() == "!!merge" || k.Value == "<<") && k.Style == 0 { - return fmt.Errorf("line %d: a merge key `<<` at the root is not supported", k.Line) + return fmt.Errorf("line %d: a merge key `<<` at the root is not supported", root.Content[i].Line) } if k.Kind != yaml.ScalarNode || (k.Value != "proxies" && k.Value != "proxy-groups") { continue @@ -245,20 +253,24 @@ type tplNamed struct { } type tplGroup struct { - Name string `yaml:"name"` - Type string `yaml:"type"` - Proxies []string `yaml:"proxies"` - Use []string `yaml:"use"` - IncludeAllProxies bool `yaml:"include-all-proxies"` - IncludeAll bool `yaml:"include-all"` + Name string `yaml:"name"` + Type string `yaml:"type"` + Proxies []string `yaml:"proxies"` + Use []string `yaml:"use"` + IncludeAllProxies bool `yaml:"include-all-proxies"` + IncludeAll bool `yaml:"include-all"` + OrderedProxies yaml.Node `yaml:"mistgate-ordered-proxies"` + order *mihomoOrderedOptions } // tplInfo is a template read for the keys the panel works on. type tplInfo struct { - doc, root *yaml.Node - proxies []tplNamed - groups []tplGroup - names map[string]bool // the names of the template's proxies and groups + doc, root *yaml.Node + proxies []tplNamed + groups []tplGroup + names map[string]bool // the names of the template's proxies and groups + providers map[string]yaml.Node + providersRead bool } // loadTemplate reads text as the panel changes it: one document, a mapping, the shape of checkRootShape, the entries of `proxies` and @@ -296,23 +308,64 @@ func loadTemplate(text string) (*tplInfo, error) { return nil, err } } - for i, g := range t.groups { + groupNodes, _ := rootValue(root, "proxy-groups") + for i := range t.groups { + g := &t.groups[i] if err := add("proxy-groups", i, g.Name); err != nil { return nil, err } if g.Type == "" { return nil, fmt.Errorf("proxy-groups[%d] %q: a type is required", i, g.Name) } + // Decode the node so an explicit YAML null is not treated like an omitted flag. + flag := &g.OrderedProxies + if flag.Kind == 0 { + continue + } + if flag.ShortTag() != "!!bool" { + return nil, mihomoYAMLDiagnostic{err: fmt.Errorf("line %d: %s must be a YAML boolean", flag.Line, mihomoOrderedProxiesKey)} + } + var ordered bool + if err := flag.Decode(&ordered); err != nil { + return nil, mihomoYAMLDiagnostic{err: err} + } + if !ordered { + continue + } + opt, err := readMihomoOrderedOptions(groupNodes.Content[i], i) + if err != nil { + return nil, err + } + if opt.IncludeAllProxies || opt.IncludeAll { + return nil, fmt.Errorf("proxy-groups[%d]: %s cannot be enabled with include-all-proxies or include-all; use include-all-providers to add all external providers", i, mihomoOrderedProxiesKey) + } + if err := t.readProxyProviders(); err != nil { + return nil, err + } + if _, exists := t.providers[g.Name]; exists { + return nil, fmt.Errorf("proxy-groups[%d] %q: rename the group or the proxy provider before enabling %s; Mihomo requires distinct names", i, g.Name, mihomoOrderedProxiesKey) + } + g.Proxies, g.Use, g.order = opt.Proxies, opt.Use, opt } return t, nil } +func (t *tplInfo) readProxyProviders() error { + if !t.providersRead { + if v, _ := rootValue(t.root, "proxy-providers"); v != nil { + if err := v.Decode(&t.providers); err != nil { + return mihomoYAMLDiagnostic{err: err, prefix: "proxy-providers: "} + } + } + t.providersRead = true + } + return nil +} + // checkRefs checks what the groups name: every member is a name of the template, of the core, or Auto (when the panel adds it), and // every `use` is a key of proxy-providers. A name that is not there is why a Mihomo core refuses the whole file, and a name of a server // is the usual one: only some people have it. func (t *tplInfo) checkRefs(autoOn bool) error { - var providers map[string]any - loaded := false for i, g := range t.groups { for _, m := range g.Proxies { if t.names[m] || slices.Contains(CoreNames, m) || (autoOn && m == AutoName) { @@ -321,18 +374,16 @@ func (t *tplInfo) checkRefs(autoOn bool) error { if m == AutoName { return fmt.Errorf("proxy-groups[%d] %q: refers to Auto, which the panel adds only while automatic server selection is on (or define a group named Auto)", i, g.Name) } - return fmt.Errorf("proxy-groups[%d] %q: proxies: %q is not a proxy or group of this template (take servers with include-all-proxies or filter)", i, g.Name, m) + return fmt.Errorf("proxy-groups[%d] %q: proxies: %q is not a proxy or group of this template (take servers with %s or include-all-proxies)", i, g.Name, m, mihomoOrderedProxiesKey) + } + if g.order != nil && bool(g.order.IncludeAllProviders) { + continue // Mihomo replaces use with the declared provider keys. } for _, u := range g.Use { - if !loaded { - loaded = true - if v, _ := rootValue(t.root, "proxy-providers"); v != nil { - if err := v.Decode(&providers); err != nil && !isNull(v) { - return mihomoYAMLDiagnostic{err: err, prefix: "proxy-providers: "} - } - } + if err := t.readProxyProviders(); err != nil { + return err } - if _, ok := providers[u]; !ok { + if _, ok := t.providers[u]; !ok { return fmt.Errorf("proxy-groups[%d] %q: use: %q is not in proxy-providers", i, g.Name, u) } } @@ -401,10 +452,10 @@ func checkMihomoTemplate(ctx context.Context, text string, autoOn bool, sourceEr if err := ctx.Err(); err != nil { return err } - // A trial build with two servers, as a person would get it: an error of the encoder is found here, not in the apps. - out, err := ApplyMihomoTemplate(text, trialServers(), MihomoOptions{AutoSelect: autoOn}) + // Build with sample servers, including a long name to catch filters that are only slow on longer input. + out, err := applyLoadedMihomoTemplate(t, trialServers(), MihomoOptions{AutoSelect: autoOn}) if err != nil { - return fmt.Errorf("trial build: %w", err) + return fmt.Errorf("trial build: %w", mapError(err)) } if err := ctx.Err(); err != nil { return err @@ -435,9 +486,10 @@ func commentedMihomoMarker(doc *yaml.Node) (string, bool) { } func trialServers() []MihomoServer { - out := make([]MihomoServer, trialServerCount) - for i := range out { - name := "server " + strconv.Itoa(i+1) + const longName = "server 3 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!" + names := [...]string{"server 1", "server 2", longName} + out := make([]MihomoServer, len(names)) + for i, name := range names { out[i] = MihomoServer{Name: name, Node: mapOf( strNode("name"), quotedNode(name), strNode("type"), strNode("hysteria2"), strNode("server"), quotedNode("example.com"), strNode("port"), intNode(443), strNode("password"), quotedNode("x"))} @@ -467,8 +519,8 @@ type MihomoOptions struct { var ErrNoServers = errors.New("mihomo template: no servers") // ApplyMihomoTemplate puts the servers of a person into a template: they go first in `proxies` (a name the template or the core has -// gets " ·" added, the template's names are never changed), then `Auto` and `dns` as described at the top of this file. The template -// is read anew each call (the stored document is shared: its nodes are not modified). The result is the document to send. +// gets " ·" added, the template's names are never changed), then expands automatic local group members and adds `Auto` and `dns` +// as described at the top of this file. The template is read anew each call. The result is the document to send. // // ponytail: a read, a decode of the names and an encode on every request (about 6 ms of wasm CPU for a 14 KB template, 27 ms for // 64 KiB). If that ever costs too much: remember the nodes per template text and copy them deeply. @@ -480,6 +532,10 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) if err != nil { return nil, err } + return applyLoadedMihomoTemplate(t, servers, opt) +} + +func applyLoadedMihomoTemplate(t *tplInfo, servers []MihomoServer, opt MihomoOptions) ([]byte, error) { taken := map[string]bool{} for n := range t.names { taken[n] = true @@ -496,6 +552,9 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) names = append(names, name) nodes = append(nodes, s.Node) } + if err := expandOrderedMihomoGroups(t, names); err != nil { + return nil, err + } // The key is added at the end of the root when the template lacks it (or has it null). list := func(key string) *yaml.Node { @@ -527,6 +586,7 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) t.root.Content[i] = opt.DNS } } + stripMihomoOrderFlags(t) prepareMihomoYAML(t.doc) var buf bytes.Buffer enc := yaml.NewEncoder(&buf) @@ -570,7 +630,7 @@ func MihomoTemplateWarnings(text string, autoOn bool) []MihomoWarning { ownAuto := t.names[AutoName] takes := false for _, g := range t.groups { - takes = takes || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) + takes = takes || g.order != nil || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) } if !takes { out = append(out, MihomoWarning{Code: WarnNoServerGroup}) diff --git a/internal/panel/subsettings/mihomo_ordered_groups.go b/internal/panel/subsettings/mihomo_ordered_groups.go new file mode 100644 index 000000000..7dd77196c --- /dev/null +++ b/internal/panel/subsettings/mihomo_ordered_groups.go @@ -0,0 +1,355 @@ +package subsettings + +import ( + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/dlclark/regexp2" + "gopkg.in/yaml.v3" +) + +const mihomoOrderedProxiesKey = "mistgate-ordered-proxies" + +const ( + mihomoFilterBudget = 250 * time.Millisecond + mihomoFilterClockPeriod = 5 * time.Millisecond + // regexp2 adds a period to the deadline and polls an approximate clock. + mihomoFilterClockSlack = 2*mihomoFilterClockPeriod + time.Millisecond +) + +func init() { + regexp2.SetTimeoutCheckPeriod(mihomoFilterClockPeriod) +} + +// ErrMihomoFilterBudget does not contain the pattern or server names and is safe to return to the editor and log. +var ErrMihomoFilterBudget = errors.New("filter exceeded the matching time limit") + +// A filter cache belongs to one render. Regexp.MatchTimeout is mutable, so +// these expressions cannot be shared across renders. +// The budget uses wall time. On Cloudflare Workers the clock does not advance +// during synchronous matching, so the Worker's CPU limit is the backstop. +type mihomoGroupFilters struct { + compiled map[string]*regexp2.Regexp + deadline time.Time +} + +func (f *mihomoGroupFilters) match(pattern, name string) (bool, error) { + remaining := time.Until(f.deadline) + if remaining <= mihomoFilterClockSlack { + return false, ErrMihomoFilterBudget + } + re := f.compiled[pattern] + re.MatchTimeout = remaining - mihomoFilterClockSlack + matched, err := re.MatchString(name) + if err != nil || time.Until(f.deadline) <= 0 { + return false, ErrMihomoFilterBudget + } + return matched, nil +} + +func (f *mihomoGroupFilters) orderedMembers(authored, names []string, static []tplNamed, filter string) ([]string, error) { + members := make([]string, 0, len(authored)+len(names)+len(static)) + members = append(members, authored...) + seen := make(map[string]bool, cap(members)) + for _, name := range members { + seen[name] = true + } + if filter != "" && f.compiled == nil { + f.compiled = make(map[string]*regexp2.Regexp) + f.deadline = time.Now().Add(mihomoFilterBudget) + } + // For an empty filter the single empty expression means no matching is needed. + // In a nonempty filter, an empty component is a real regexp, just as in Mihomo. + for pattern := range strings.SplitSeq(filter, "`") { + if filter != "" && f.compiled[pattern] == nil { + if time.Until(f.deadline) <= 0 { + return nil, ErrMihomoFilterBudget + } + re, err := regexp2.Compile(pattern, regexp2.None) + if err != nil { + return nil, errors.New("invalid filter regular expression") + } + f.compiled[pattern] = re + } + add := func(name string) error { + if seen[name] { + return nil + } + if filter != "" { + matched, err := f.match(pattern, name) + if err != nil || !matched { + return err + } + } + seen[name] = true + members = append(members, name) + return nil + } + for _, name := range names { + if err := add(name); err != nil { + return nil, err + } + } + for _, p := range static { + if err := add(p.Name); err != nil { + return nil, err + } + } + if filter != "" && time.Until(f.deadline) <= 0 { + return nil, ErrMihomoFilterBudget + } + } + return members, nil +} + +// These options use the core's effective native keys, only for opted-in groups. +type mihomoOrderedOptions struct { + Proxies []string `yaml:"proxies"` + Use []string `yaml:"use"` + Filter mihomoNativeText `yaml:"filter"` + EmptyFallback mihomoNativeText `yaml:"empty-fallback"` + IncludeAllProxies mihomoNativeBool `yaml:"include-all-proxies"` + IncludeAllProviders mihomoNativeBool `yaml:"include-all-providers"` + IncludeAll mihomoNativeBool `yaml:"include-all"` + proxiesKey string +} + +func readMihomoOrderedOptions(group *yaml.Node, index int) (*mihomoOrderedOptions, error) { + prefix := fmt.Sprintf("proxy-groups[%d]: ", index) + var raw map[string]yaml.Node + if err := group.Decode(&raw); err != nil { + return nil, mihomoYAMLDiagnostic{err: err, prefix: prefix} + } + opt := new(mihomoOrderedOptions) + projected := mapOf() + for _, key := range [...]string{"proxies", "use", "filter", "empty-fallback", "include-all-proxies", "include-all-providers", "include-all"} { + actual := key + value, ok := raw[key] + if !ok { + for alias, candidate := range raw { + if !strings.EqualFold(alias, key) { + continue + } + if ok { + return nil, fmt.Errorf("%sambiguous option %s; use the exact spelling", prefix, key) + } + actual, value, ok = alias, candidate, true + } + } + if ok { + if key == "proxies" { + opt.proxiesKey = actual + } + projected.Content = append(projected.Content, strNode(key), &value) + } + } + if err := projected.Decode(opt); err != nil { + return nil, mihomoYAMLDiagnostic{err: err, prefix: prefix} + } + return opt, nil +} + +type mihomoNativeText string + +func (text *mihomoNativeText) UnmarshalYAML(n *yaml.Node) error { + var value any + if err := n.Decode(&value); err != nil { + return err + } + switch v := value.(type) { + case string: + *text = mihomoNativeText(v) + case int: + *text = mihomoNativeText(strconv.Itoa(v)) + case int64: + *text = mihomoNativeText(strconv.FormatInt(v, 10)) + case uint64: + *text = mihomoNativeText(strconv.FormatUint(v, 10)) + case float64: + *text = mihomoNativeText(strconv.FormatFloat(v, 'E', -1, 64)) + default: + return fmt.Errorf("line %d: expected a string or number", n.Line) + } + return nil +} + +type mihomoNativeBool bool + +func (enabled *mihomoNativeBool) UnmarshalYAML(n *yaml.Node) error { + // Mihomo's weak bool decoder accepts a YAML boolean or any integer. + var value any + if err := n.Decode(&value); err != nil { + return err + } + switch v := value.(type) { + case bool: + *enabled = mihomoNativeBool(v) + case int: + *enabled = v != 0 + case int64: + *enabled = v != 0 + case uint64: + *enabled = v != 0 + default: + return fmt.Errorf("line %d: expected a boolean or integer", n.Line) + } + return nil +} + +func expandOrderedMihomoGroups(t *tplInfo, names []string) error { + groups, _ := rootValue(t.root, "proxy-groups") + var filters mihomoGroupFilters + // Provider keys were read when the opted-in groups were validated. + for i, g := range t.groups { + if g.order == nil { + continue + } + group := groups.Content[i] + opt := g.order + members, err := filters.orderedMembers(g.Proxies, names, t.proxies, string(opt.Filter)) + if err != nil { + return fmt.Errorf("proxy-groups[%d]: %w", i, err) + } + if len(members) == 0 { + count := len(g.Use) + if opt.IncludeAllProviders { + count = len(t.providers) + } + if count == 0 { + fallback := string(opt.EmptyFallback) + if fallback == "" { + fallback = "COMPATIBLE" + } + members = append(members, fallback) + } + } + + old, index := rootValue(group, opt.proxiesKey) + if group.Kind == yaml.AliasNode || group.Anchor != "" || old != nil && hasYAMLAnchor(old) { + // Keep original anchor definitions inline and before their readers. A + // local merge overlay changes this group without changing what any alias sees. + group = mapOf(&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!merge", Value: "<<"}, group) + groups.Content[i] = group + old = nil + } + if old == nil { + group.Content = append(group.Content, strNode("proxies"), quotedSeqOf(members)) + } else if old.Kind == yaml.SequenceNode { + // This list has no anchors of its own; keep the authored items, + // including nulls and comments that the decoded list omits. + old.Content = append(old.Content, quotedSeqOf(members[len(g.Proxies):]).Content...) + } else { + seq := quotedSeqOf(members) + copyYAMLComments(seq, old) + group.Content[index] = seq + } + } + return nil +} + +// Strip the directive only from group mappings and the defaults they merge. +// An identically named provider or other YAML entry is not a directive. +func stripMihomoOrderFlags(t *tplInfo) { + if len(t.groups) == 0 { + return + } + groups, _ := rootValue(t.root, "proxy-groups") + var seen map[*yaml.Node]bool + var removed map[*yaml.Node]bool + var strip func(*yaml.Node) + strip = func(n *yaml.Node) { + if n.Kind == yaml.AliasNode { + n = n.Alias + } + if n.Anchor != "" { + if seen[n] { + return + } + if seen == nil { + seen = make(map[*yaml.Node]bool) + } + seen[n] = true + } + if n.Kind == yaml.SequenceNode { + for _, child := range n.Content { + strip(child) + } + return + } + if n.Kind != yaml.MappingNode { + return + } + kept := n.Content[:0] + for i := 0; i < len(n.Content); i += 2 { + k, v := n.Content[i], n.Content[i+1] + if key := mappingKey(k); key.Kind == yaml.ScalarNode && key.Value == mihomoOrderedProxiesKey { + markRemovedMihomoAnchors(k, &removed) + markRemovedMihomoAnchors(v, &removed) + continue + } + if k.Kind == yaml.ScalarNode && k.ShortTag() == "!!merge" { + strip(v) + } + kept = append(kept, k, v) + } + clear(n.Content[len(kept):]) + n.Content = kept + } + strip(groups) + if len(removed) != 0 { + restoreMihomoYAMLAnchors(t.doc, removed) + } +} + +func hasYAMLAnchor(node *yaml.Node) bool { + if node.Anchor != "" { + return true + } + for _, child := range node.Content { + if hasYAMLAnchor(child) { + return true + } + } + return false +} + +func copyYAMLComments(dst, src *yaml.Node) { + dst.HeadComment, dst.LineComment, dst.FootComment = src.HeadComment, src.LineComment, src.FootComment +} + +func markRemovedMihomoAnchors(n *yaml.Node, removed *map[*yaml.Node]bool) { + if n.Anchor != "" { + if *removed == nil { + *removed = make(map[*yaml.Node]bool) + } + (*removed)[n] = false + } + for _, c := range n.Content { + markRemovedMihomoAnchors(c, removed) + } +} + +// Move an anchor from the dropped directive to its first remaining use. +// Later references still use the original anchor name. +func restoreMihomoYAMLAnchors(n *yaml.Node, removed map[*yaml.Node]bool) *yaml.Node { + if n.Kind == yaml.AliasNode { + emitted, missing := removed[n.Alias] + if !missing || emitted { + return n + } + n = n.Alias + } + if emitted, missing := removed[n]; missing { + if emitted { + return &yaml.Node{Kind: yaml.AliasNode, Value: n.Anchor, Alias: n} + } + removed[n] = true + } + for i, child := range n.Content { + n.Content[i] = restoreMihomoYAMLAnchors(child, removed) + } + return n +} diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go new file mode 100644 index 000000000..9091bb409 --- /dev/null +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -0,0 +1,310 @@ +package subsettings + +import ( + "context" + "errors" + "runtime" + "slices" + "strings" + "testing" + "time" + + "github.com/dlclark/regexp2" + "gopkg.in/yaml.v3" +) + +func TestMihomoOrderedGroups(t *testing.T) { + const head = `proxies: + - {name: Static, type: direct} + - {name: Another, type: direct} +proxy-providers: + Example: {type: file, path: example.yaml} +proxy-groups: + - name: Pick + type: fallback +` + for _, tc := range []struct { + name, fields string + want []string + providers bool + use []string + }{ + {"explicit and unique final names", " proxies: [Static, DIRECT]\n mistgate-ordered-proxies: true\n", []string{"Static", "DIRECT", "Zulu", "Static ·", "Alpha", "Zulu ·", "Another"}, false, nil}, + {"ordered overlapping expressions with lookahead", " proxies: [DIRECT]\n mistgate-ordered-proxies: true\n filter: '^Z(?=ulu ·$)`^[AZ]`.*'\n", []string{"DIRECT", "Zulu ·", "Zulu", "Alpha", "Another", "Static ·", "Static"}, false, nil}, + {"empty with reject", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n empty-fallback: REJECT\n", []string{"REJECT"}, false, nil}, + {"empty by default", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", []string{"COMPATIBLE"}, false, nil}, + {"empty locals with explicit provider", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n use: [Example]\n", nil, false, []string{"Example"}}, + {"include all providers without locals", " mistgate-ordered-proxies: true\n include-all-providers: true\n filter: '^Nothing$'\n", nil, true, nil}, + {"provider only", " use: [Example]\n", nil, false, []string{"Example"}}, + } { + t.Run(tc.name, func(t *testing.T) { + out, _ := apply(t, head+tc.fields, MihomoOptions{}, "Zulu", "Static", "Alpha", "Zulu") + if strings.Contains(out, mihomoOrderedProxiesKey) { + t.Fatalf("Mistgate group flag reached the subscription:\n%s", out) + } + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + g := info.groups[0] + if !slices.Equal(g.Proxies, tc.want) || g.IncludeAll || g.IncludeAllProxies || + strings.Contains(out, "include-all-providers: true") != tc.providers || !slices.Equal(g.Use, tc.use) { + t.Fatalf("group = %+v; want members %q, include-all-providers %t, use %q", g, tc.want, tc.providers, tc.use) + } + }) + } + t.Run("native flags are not expanded", func(t *testing.T) { + for _, native := range []string{"include-all-proxies", "include-all"} { + base := head + " proxies: [DIRECT]\n " + native + ": true\n" + for _, suffix := range []string{"", " mistgate-ordered-proxies: false\n"} { + out, _ := apply(t, base+suffix, MihomoOptions{}, "Zulu", "Alpha") + if !strings.Contains(out, native+": true") || strings.Contains(out, mihomoOrderedProxiesKey) { + t.Fatalf("native group flags changed:\n%s", out) + } + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0].Proxies; !slices.Equal(got, []string{"DIRECT"}) { + t.Fatalf("native group gained members: %q", got) + } + } + } + }) + t.Run("Mihomo integer provider flags", func(t *testing.T) { + for _, tc := range []struct { + name, fields, providers string + members []string + }{ + {"native", " proxies: [DIRECT]\n", "1", []string{"DIRECT"}}, + {"opted in", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "1", nil}, + {"disabled", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "0", []string{"COMPATIBLE"}}, + } { + t.Run(tc.name, func(t *testing.T) { + providerFlag := " include-all-providers: " + tc.providers + "\n" + text := head + tc.fields + providerFlag + if err := CheckMihomoTemplate(text, false); err != nil { + t.Fatal(err) + } + out, _ := apply(t, text, MihomoOptions{}, "Zulu") + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0].Proxies; !slices.Equal(got, tc.members) { + t.Fatalf("members = %q, want %q", got, tc.members) + } + if !strings.Contains(out, providerFlag) { + t.Fatalf("provider flag changed:\n%s", out) + } + }) + } + }) + t.Run("conflicting native flags are rejected", func(t *testing.T) { + for _, flag := range []string{"include-all-proxies", "include-all", "INCLUDE-ALL-PROXIES", "INCLUDE-ALL"} { + text := head + " mistgate-ordered-proxies: true\n " + flag + ": true\n" + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "cannot be enabled with") { + t.Fatalf("%s: save validation error = %v", flag, err) + } + } + }) + t.Run("the opt-in must be a YAML boolean", func(t *testing.T) { + for _, value := range []string{`"on"`, `"yes"`, "on", "1", "null", "", "[true]"} { + text := head + " mistgate-ordered-proxies: " + value + "\n" + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "mistgate-ordered-proxies must be a YAML boolean") { + t.Fatalf("%s: save validation error = %v", value, err) + } + } + }) + t.Run("provider names cannot collide with opted-in groups", func(t *testing.T) { + base := strings.Replace(head, "name: Pick", "name: Example", 1) + " use: [Example]\n" + if err := CheckMihomoTemplate(base, false); err != nil { + t.Fatalf("native provider-only group: %v", err) + } + text := base + " mistgate-ordered-proxies: true\n filter: '^not a trial server$'\n" + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "requires distinct names") { + t.Fatalf("save validation error = %v", err) + } + }) + t.Run("ordered option errors point to the source", func(t *testing.T) { + const text = `# @mistgate-if ["grp_demo"] +mixed-port: 7890 +# @mistgate-end +proxy-groups: + - name: Pick + type: select + mistgate-ordered-proxies: true + filter: [] +` + err := CheckMihomoGroups(context.Background(), text, []string{"grp_demo"}, false) + if err == nil || !strings.Contains(err.Error(), "line 8:") { + t.Fatalf("save validation error = %v, want authored line 8", err) + } + }) + t.Run("ordered proxies suppress the no-servers warning", func(t *testing.T) { + if got := MihomoTemplateWarnings(head+" mistgate-ordered-proxies: true\n", false); len(got) != 0 { + t.Fatalf("warnings = %+v", got) + } + }) + t.Run("include all providers ignores use when provider map is empty", func(t *testing.T) { + out, _ := apply(t, `proxy-groups: + - name: Pick + type: select + mistgate-ordered-proxies: true + include-all-providers: true + use: [Ignored] + filter: '^Nothing$' +`, MihomoOptions{}, "Zulu") + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0].Proxies; !slices.Equal(got, []string{"COMPATIBLE"}) { + t.Fatalf("members = %q", got) + } + }) + t.Run("aliases and inherited flags stay local", func(t *testing.T) { + const text = `x-default: &default + type: select + mistgate-ordered-proxies: true + proxies: &shared [DIRECT] # shared list +x-group: &aliased + <<: *default + name: Aliased +proxy-groups: + - *aliased + - &original + <<: *default + name: Changed + mistgate-ordered-proxies: &flag true + proxies: &list + - &member REJECT # anchored member + - name: Outside + type: select + proxies: *list + - name: Inherited + <<: *default + mistgate-ordered-proxies: false +x-copy: *original +x-flag: *flag +x-flag-copy: *flag +x-member: *member +` + out, _ := apply(t, text, MihomoOptions{}, "Zulu", "Alpha") + if strings.Contains(out, mihomoOrderedProxiesKey) { + t.Fatalf("Mistgate group flag reached the subscription:\n%s", out) + } + if err := CheckMihomoTemplate(out, false); err != nil { + t.Fatalf("changed output does not pass validation: %v\n%s", err, out) + } + var d struct { + Groups []tplGroup `yaml:"proxy-groups"` + Alias tplGroup `yaml:"x-group"` + Copy tplGroup `yaml:"x-copy"` + Flag bool `yaml:"x-flag"` + FlagCopy bool `yaml:"x-flag-copy"` + Member string `yaml:"x-member"` + } + if err := yaml.Unmarshal([]byte(out), &d); err != nil { + t.Fatal(err) + } + want := [][]string{{"DIRECT", "Zulu", "Alpha"}, {"REJECT", "Zulu", "Alpha"}, {"REJECT"}, {"DIRECT"}} + for i, g := range d.Groups { + if g.IncludeAll || g.IncludeAllProxies || !slices.Equal(g.Proxies, want[i]) { + t.Fatalf("group %s = %+v; want %q without local auto-inclusion", g.Name, g, want[i]) + } + } + if !slices.Equal(d.Alias.Proxies, []string{"DIRECT"}) || !slices.Equal(d.Copy.Proxies, []string{"REJECT"}) || !d.Flag || !d.FlagCopy || d.Member != "REJECT" { + t.Fatalf("source values changed: %+v\n%s", d, out) + } + for _, comment := range []string{"# shared list", "# anchored member"} { + if !strings.Contains(out, comment) { + t.Fatalf("lost %q:\n%s", comment, out) + } + } + }) + t.Run("alias keys at the root and inside a group", func(t *testing.T) { + const text = `x-groups-key: &groups-key proxy-groups +x-proxies-key: &proxies-key proxies +x-include-key: &include-key mistgate-ordered-proxies +*groups-key: + - name: Pick + type: select + *include-key: true + *proxies-key: [DIRECT] +` + out, _ := apply(t, text, MihomoOptions{}, "Zulu", "Alpha") + if strings.Contains(out, "*include-key:") { + t.Fatalf("Mistgate group flag reached the subscription:\n%s", out) + } + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0]; got.OrderedProxies.Kind != 0 || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { + t.Fatalf("group = %+v", got) + } + if err := CheckMihomoTemplate(out, false); err != nil { + t.Fatal(err) + } + }) + t.Run("an alias key does not bypass the root shape check", func(t *testing.T) { + const text = `x-key: &key proxy-groups +x-list: &list [{name: Pick, type: select, include-all-proxies: true}] +*key: *list +` + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "must be a list written out") { + t.Fatalf("save validation error = %v", err) + } + }) + t.Run("invalid expression is rejected without its text", func(t *testing.T) { + const text = head + " mistgate-ordered-proxies: true\n filter: '.*`(private-pattern'\n" + out, err := ApplyMihomoTemplate(text, []MihomoServer{serverNode(t, "private-node")}, MihomoOptions{}) + if len(out) != 0 || err == nil || !strings.Contains(err.Error(), "invalid filter") || strings.Contains(err.Error(), "private-") { + t.Fatalf("output = %q, error = %v", out, err) + } + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "invalid filter") { + t.Fatalf("save validation error = %v", err) + } + }) + t.Run("filter budget reserves clock polling time", func(t *testing.T) { + for _, remaining := range []time.Duration{-time.Second, mihomoFilterClockSlack / 2} { + f := mihomoGroupFilters{ + compiled: map[string]*regexp2.Regexp{".*": regexp2.MustCompile(".*", regexp2.None)}, + deadline: time.Now().Add(remaining), + } + got, err := f.orderedMembers([]string{"DIRECT"}, []string{"Zulu"}, nil, ".*") + if got != nil || !errors.Is(err, ErrMihomoFilterBudget) { + t.Fatalf("members = %q, error = %v", got, err) + } + } + }) +} + +func TestMihomoFilterBudgetNative(t *testing.T) { + if runtime.GOOS == "js" { + t.Skip("regexp2 cannot enforce a deadline during synchronous WebAssembly matching") + } + const text = `proxy-groups: + - name: Pick + type: select + mistgate-ordered-proxies: true + filter: '^(\w+\s?)*$' +` + t.Run("render", func(t *testing.T) { + servers := []MihomoServer{serverNode(t, strings.Repeat("a", 64)+"!")} + start := time.Now() + got, err := ApplyMihomoTemplate(text, servers, MihomoOptions{}) + if got != nil || !errors.Is(err, ErrMihomoFilterBudget) { + t.Fatalf("render returned %q, %v; want filter budget error and no profile", got, err) + } + if elapsed := time.Since(start); elapsed >= 800*time.Millisecond { + t.Errorf("render exceeded 800 ms: %s", elapsed) + } + }) + t.Run("save with sample names", func(t *testing.T) { + if err := CheckMihomoTemplate(text, false); !errors.Is(err, ErrMihomoFilterBudget) { + t.Fatalf("save validation returned %v; want filter budget error", err) + } + }) +} diff --git a/proto/mistgate/admin/v1/subscription.proto b/proto/mistgate/admin/v1/subscription.proto index 8b071f2f8..4b8859264 100644 --- a/proto/mistgate/admin/v1/subscription.proto +++ b/proto/mistgate/admin/v1/subscription.proto @@ -137,9 +137,9 @@ message RoutingInfo { // One Mihomo YAML profile of the owner. The panel puts the servers of the person at the start of its `proxies` and, while // link_auto_select is on and the template has no group of that name, adds a url-test group `Auto` over them at the end of its -// `proxy-groups`; groups take the servers with `include-all-proxies` or `filter`. `dns` is added (resolvers of the person's preset, -// respect-rules on) only when the template has none. Everything else is left as written, comments included. The panel never -// fetches a URL of a template. +// `proxy-groups`. Groups can opt in to panel order with `mistgate-ordered-proxies: true`, or let Mihomo include and sort +// servers with `include-all-proxies` or `include-all`. `dns` is added (preset resolvers, respect-rules on) only when the +// template has none. The panel never fetches a URL of a template. // // A save is refused (INVALID_ARGUMENT, the text names the line) unless the text is one valid YAML document that parses in full (no // alias bomb, no repeated key), has a mapping at its root, `proxies` and `proxy-groups` that are lists (or absent) with named @@ -390,9 +390,9 @@ message PreviewMihomoTemplateRequest { } // One finding that does not stop a save (SubscriptionService words them by code). code is one of: no_server_group (no group takes the -// servers of the person: include-all-proxies, or Auto), own_dns (the person's DNS preset is not applied to this template), -// preset_rules_skipped (the preset has ad, split or country rules that a template does not get), own_auto (the template has its own -// Auto, so the panel adds none), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). +// servers of the person: `mistgate-ordered-proxies`, `include-all-proxies`, `include-all`, or `Auto`), own_dns (the person's +// DNS preset is not applied), preset_rules_skipped (the preset's ad, split or country rules are not applied), own_auto (the +// template has its own Auto), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). message MihomoWarning { string code = 1; string arg = 2; diff --git a/scripts/check-edge-sizes.sh b/scripts/check-edge-sizes.sh index e82407d9e..e9fed3601 100755 --- a/scripts/check-edge-sizes.sh +++ b/scripts/check-edge-sizes.sh @@ -45,6 +45,8 @@ entries=( # 30 MiB in November 2026 (29.01 MiB measured with group blocks in a Mihomo template also in, 13 KiB over 29): the relay # leg's address family (Relay.leg, NodeAddrs.LegHost, the check's family) is subscription code — the relay twin's usability # and its target are built in this Worker, so it cannot move to another role. + # Ordered Mihomo template groups bring the public Worker to 29.8 MiB (228 KiB left): it matches filters against each + # person's proxy names while serving their subscription. "mistgate-edge-public:30" # The agent link: wireCore plus the link driver. Measured 26.4 MiB. # 31 MiB in November 2026 (30.003 MiB measured, 2.9 KiB over 30): nothing of own probes runs here (the service, its @@ -80,7 +82,10 @@ entries=( # 49 MiB with the probe of a relay leg over the other address family (48.02 MiB measured, 18 KiB over 48): CheckRelay # with other_leg, the leg hints of ListRelayCandidates and the other-leg fields of a relay are admin calls, and the # fleet code that runs the probe is what they call. - "mistgate-edge-admin:49" + # 50 MiB with ordered Mihomo template groups (49.4 MiB measured): the admin Worker needs the same regexp2 + # matching as the public Worker to validate and preview unsaved templates. The public Worker serves saved profiles; + # sending drafts there would add a new cross-Worker RPC for an owner-only operation. + "mistgate-edge-admin:50" # The Provisioner: wireCore plus the SSH client. Measured 29.4 MiB; 31.9 MiB in November 2026 with the panel's SSH key, the # authorized_keys management and the login by an own private key, which need that SSH client and so cannot live elsewhere. "mistgate-edge-provision:35" diff --git a/web/src/gen/mistgate/admin/v1/subscription_pb.ts b/web/src/gen/mistgate/admin/v1/subscription_pb.ts index 76b7b2cb5..2c0959ef8 100644 --- a/web/src/gen/mistgate/admin/v1/subscription_pb.ts +++ b/web/src/gen/mistgate/admin/v1/subscription_pb.ts @@ -371,9 +371,9 @@ export const RoutingInfoSchema: GenMessage = /*@__PURE__*/ /** * One Mihomo YAML profile of the owner. The panel puts the servers of the person at the start of its `proxies` and, while * link_auto_select is on and the template has no group of that name, adds a url-test group `Auto` over them at the end of its - * `proxy-groups`; groups take the servers with `include-all-proxies` or `filter`. `dns` is added (resolvers of the person's preset, - * respect-rules on) only when the template has none. Everything else is left as written, comments included. The panel never - * fetches a URL of a template. + * `proxy-groups`. Groups can opt in to panel order with `mistgate-ordered-proxies: true`, or let Mihomo include and sort + * servers with `include-all-proxies` or `include-all`. `dns` is added (preset resolvers, respect-rules on) only when the + * template has none. The panel never fetches a URL of a template. * * A save is refused (INVALID_ARGUMENT, the text names the line) unless the text is one valid YAML document that parses in full (no * alias bomb, no repeated key), has a mapping at its root, `proxies` and `proxy-groups` that are lists (or absent) with named @@ -1095,9 +1095,9 @@ export const PreviewMihomoTemplateRequestSchema: GenMessage = { "subs.mt.err.nameTaken": "Такое название уже есть (регистр не важен).", "subs.mt.err.empty": "Текст пуст.", "subs.mt.err.big": "Текст занимает {n} КиБ. Один шаблон — до {max} КиБ.", - "subs.mt.warn.no_server_group": "Ни одна группа не берёт серверы человека. Добавь в группу include-all-proxies: true или сошлись на Auto, иначе подключаться будет не к чему.", + "subs.mt.warn.no_server_group": "Ни одна группа не берёт серверы человека. Добавь в группу mistgate-ordered-proxies: true или сошлись на Auto, иначе подключаться будет не к чему.", "subs.mt.warn.own_dns": "В шаблоне есть свой раздел dns, поэтому DNS-пресет человека к нему не применяется.", "subs.mt.warn.preset_rules_skipped": "В DNS-пресете этого человека есть правила рекламы, разделения или стран, а шаблон их не получает. Если они нужны, впиши их в шаблон.", "subs.mt.warn.own_auto": "В шаблоне есть своя группа Auto, поэтому панель свою не добавляет.", @@ -835,7 +835,7 @@ export const zh: typeof en = { "subs.mt.err.nameTaken": "已有同名模板(不区分大小写)。", "subs.mt.err.empty": "文本为空。", "subs.mt.err.big": "文本为 {n} KiB。单个模板最多 {max} KiB。", - "subs.mt.warn.no_server_group": "没有任何组使用用户的服务器。请在某个组里加上 include-all-proxies: true,或引用 Auto,否则无处可连。", + "subs.mt.warn.no_server_group": "没有任何组使用用户的服务器。请在某个组里加上 mistgate-ordered-proxies: true,或引用 Auto,否则无处可连。", "subs.mt.warn.own_dns": "模板有自己的 dns 部分,因此不会应用用户的 DNS 预设。", "subs.mt.warn.preset_rules_skipped": "此用户的 DNS 预设包含广告、分流或国家规则,而模板不会得到这些规则。需要的话请写进模板。", "subs.mt.warn.own_auto": "模板有自己的 Auto 组,因此面板不再添加。", @@ -1230,7 +1230,7 @@ export const fa: Record = { "subs.mt.err.nameTaken": "قالب دیگری همین نام را دارد (حروف بزرگ و کوچک فرقی ندارند).", "subs.mt.err.empty": "متن خالی است.", "subs.mt.err.big": "این متن {n} کیبی‌بایت است. هر قالب حداکثر {max} کیبی‌بایت می‌تواند باشد.", - "subs.mt.warn.no_server_group": "هیچ گروهی سرورهای فرد را نمی‌گیرد. در یک گروه include-all-proxies: true بگذارید یا به Auto ارجاع دهید، وگرنه چیزی برای اتصال نیست.", + "subs.mt.warn.no_server_group": "هیچ گروهی سرورهای فرد را نمی‌گیرد. در یک گروه mistgate-ordered-proxies: true بگذارید یا به Auto ارجاع دهید، وگرنه چیزی برای اتصال نیست.", "subs.mt.warn.own_dns": "قالب بخش dns خودش را دارد، پس پیش‌تنظیم DNS فرد روی آن اعمال نمی‌شود.", "subs.mt.warn.preset_rules_skipped": "پیش‌تنظیم DNS این فرد قواعد تبلیغ، تفکیک یا کشور دارد و قالب آن‌ها را نمی‌گیرد. اگر لازم‌اند، در قالب بنویسید.", "subs.mt.warn.own_auto": "قالب گروه Auto خودش را دارد، پس پنل گروهی اضافه نمی‌کند.", @@ -1617,7 +1617,7 @@ export const tr: Record = { "subs.mt.err.nameTaken": "Başka bir şablonda aynı ad var (büyük küçük harf fark etmez).", "subs.mt.err.empty": "Metin boş.", "subs.mt.err.big": "Bu metin {n} KiB. Bir şablon en çok {max} KiB olabilir.", - "subs.mt.warn.no_server_group": "Hiçbir grup kişinin sunucularını almıyor. Bir gruba include-all-proxies: true ekle ya da Auto'ya başvur, yoksa bağlanacak bir şey kalmaz.", + "subs.mt.warn.no_server_group": "Hiçbir grup kişinin sunucularını almıyor. Bir gruba mistgate-ordered-proxies: true ekle ya da Auto'ya başvur, yoksa bağlanacak bir şey kalmaz.", "subs.mt.warn.own_dns": "Şablonun kendi dns bölümü var, bu yüzden kişinin DNS ön ayarı ona uygulanmaz.", "subs.mt.warn.preset_rules_skipped": "Bu kişinin DNS ön ayarında reklam, ayırma ya da ülke kuralları var ve şablon bunları almaz. Gerekiyorsa şablona kendin yaz.", "subs.mt.warn.own_auto": "Şablonun kendi Auto grubu var, bu yüzden panel eklemez.", diff --git a/web/src/screens/subscriptions/mihomo.test.tsx b/web/src/screens/subscriptions/mihomo.test.tsx index 1b4e6f698..dfe595d08 100644 --- a/web/src/screens/subscriptions/mihomo.test.tsx +++ b/web/src/screens/subscriptions/mihomo.test.tsx @@ -680,10 +680,10 @@ describe("the pieces the form says early", () => { expect(templateRefusal("invalid subscription settings: mihomo_templates[2].group_ids: the group \"g\" is already in the template \"A\"")).toMatchObject({ index: 2 }); expect(templateRefusal("invalid subscription settings: mihomo_templates: 300000 bytes of text in all")).toEqual({ text: "mihomo_templates: 300000 bytes of text in all" }); }); - it("starts a new template with a group over every server, and Auto only while the panel adds it", () => { + it("starts a new template with a group in panel order, and Auto only while the panel adds it", () => { expect(starterTemplate(true)).toContain("proxies: [Auto, DIRECT]"); expect(starterTemplate(false)).toContain("proxies: [DIRECT]"); - expect(starterTemplate(false)).toContain("include-all-proxies: true"); + expect(starterTemplate(false)).toMatch(/^ mistgate-ordered-proxies: true$/m); }); it("ships an inert group example that can be enabled for an assigned group", () => { const starter = starterTemplate(true); diff --git a/web/src/screens/subscriptions/model.ts b/web/src/screens/subscriptions/model.ts index 1a6dd1766..75e996e79 100644 --- a/web/src/screens/subscriptions/model.ts +++ b/web/src/screens/subscriptions/model.ts @@ -747,8 +747,9 @@ export function textKey(s: string): string { /** The text a new template starts with: one select group over every server of the person (and Auto while the panel adds it). */ export const starterTemplate = (auto: boolean): string => [ - "# The panel puts the person's servers at the start of `proxies` (the key may be missing).", - "# Groups take them with include-all-proxies or filter.", + "# Use mistgate-ordered-proxies: true to include each person's servers in panel order.", + "# Mistgate puts explicit group members first, then the person's servers, then template proxies.", + "# This flag is only for templates; don't combine it with include-all-proxies or include-all.", "mixed-port: 7890", "mode: rule", "", @@ -761,7 +762,7 @@ export const starterTemplate = (auto: boolean): string => "proxy-groups:", " - name: Proxy", " type: select", - " include-all-proxies: true", + " mistgate-ordered-proxies: true", ` proxies: [${auto ? "Auto, " : ""}DIRECT]`, "rules:", " - MATCH,Proxy",