Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6f232d4043 | |||
| e157b16c11 | |||
| ce485a1b62 | |||
| 49d0c5d2df |
@@ -66,11 +66,39 @@ server 已与具体 DB 解绑(裸 SQL + 薄方言层,`internal/db/dialect.go`):
|
|||||||
`dialect.LockForUpdate()`;时间等一律 Go 端算好传 `?`,**不要**用 `UTC_TIMESTAMP()`/
|
`dialect.LockForUpdate()`;时间等一律 Go 端算好传 `?`,**不要**用 `UTC_TIMESTAMP()`/
|
||||||
`NOW()`/`FIELD()` 等 MySQL 专属构造(已全部清除,加回会破坏可移植性)。
|
`NOW()`/`FIELD()` 等 MySQL 专属构造(已全部清除,加回会破坏可移植性)。
|
||||||
|
|
||||||
|
### 可配置分流(routing profile,类 Shadowrocket)
|
||||||
|
|
||||||
|
用户自定义路由规则(域名/IP/GeoIP/GeoSite × 直连/走隧道/拒绝),有序首命中,存服务端 per-user 档案:
|
||||||
|
- 表 `routing_profiles`(迁移 000028)· `internal/routing`(Profile/校验/Store)· `GET/POST /v1/me/routing`
|
||||||
|
(`httpapi/routing.go`)。写操作走 **POST**(仓库无 PUT 先例);校验非法整体 400 逐条错误、不半保存。
|
||||||
|
- **客户端不拼配置(铁律 ARCHITECTURE.md §3.1)**:客户端只编辑/存取档案,`BuildClientConfig`
|
||||||
|
(`httpapi/clientconfig.go`)在 connect 时读档案翻译进 `route.rules`——层级 **系统强制层**(hijack-dns/
|
||||||
|
LAN 直连/私有服务走隧道,恒在、用户不可越)→ **用户规则** → geoip-cn 国内分流 → FINAL;三模式
|
||||||
|
rule/global/direct(global/direct 忽略用户规则只改 FINAL)。
|
||||||
|
- **直连真生效**:IP 直连 value 并入 `route_exclude_address`(在 **TUN inbound** `tunIn` 非顶层 `route`)、
|
||||||
|
域名直连开 `dns.reverse_mapping`。**fail-safe**:档案空/坏/取失败 → 回退默认,`Profile==nil` 逐字节
|
||||||
|
等价旧行为(有测试钉)。GET 附只读 `system_locked_domains`(私有域名清单,PUT 不持久化)供 UI 标「系统强制不生效」。
|
||||||
|
- 客户端:设置页「分流规则」下钻(`routing_screen.dart` + `routing_provider`,Riverpod);改档案后连接态
|
||||||
|
自动重连使新规则生效。设计/计划见 `docs/configurable-proxy-{spec,plan}.html`。
|
||||||
|
|
||||||
## CI/CD
|
## CI/CD
|
||||||
|
|
||||||
`.gitea/workflows/ci.yml`(runner label `nas`):shellcheck(bootstrap/single-node 脚本)、
|
`.gitea/workflows/`(runner = 家里 NAS 上的 act_runner;job `runs-on: ubuntu-latest` 由它在
|
||||||
OpenAPI 结构校验、UI 文案脱敏扫描、Flutter analyze+test。**仅校验,无部署动作。**
|
`catthehacker/ubuntu:act-latest` 容器承接):
|
||||||
- 节点部署是手动/按需的(scp+ssh 跑 bootstrap / single-node),不走 CI 自动推送。
|
- **`ci.yml`**(push/PR,**仅校验**):shellcheck、OpenAPI 结构校验、UI 文案脱敏扫描、Flutter
|
||||||
|
analyze+test、codegen 漂移闸(`ci/check-codegen-drift.sh`:token/l10n/原型 i18n)。
|
||||||
|
- **发版走 tag 触发**(cicd-design 已落地,取代旧「无部署」):`server-vX.Y.Z` → `deploy-server.yml`
|
||||||
|
= compile-backend → `test.sh server`(**`go test ./...`**,全绿才继续)→ Forgejo release →
|
||||||
|
`deploy-server.sh` 到 pangolin1(**备份DB→migrate up→换二进制→重启→本地 `/healthz` 权威闸**,
|
||||||
|
migrate 失败自动回滚DB+重启旧二进制)。同理 `client-v*`(deploy-client.yml)、`site-v*`。
|
||||||
|
- **⚠️ 发版必踩的私有依赖坑**:go.mod 依赖 **私有** `github.com/wangjia/codes`(真源在自建 gitea
|
||||||
|
`git.51yanmei.com/wangjia/codes`)。冷缓存 runner 上 `go build` 会走 direct git 到 github → 无凭证
|
||||||
|
挂(`could not read Username, terminal prompts disabled`)。`deploy-server.yml` 已加「私有依赖鉴权」步:
|
||||||
|
`GOPRIVATE=github.com/wangjia/codes` + `git config url."<FORGEJO_URL 带 oauth2:FORGEJO_TOKEN>/wangjia/codes.git".insteadOf https://github.com/wangjia/codes`。**新增任何私有 Go 依赖,编译前照此配鉴权。**
|
||||||
|
- **发版排障**:gitea `https://git.51yanmei.com/wangjia/pangolin/actions`;日志用 rbw「gitea 读写key」查
|
||||||
|
`/api/v1/repos/wangjia/pangolin/actions/runs/<url_id>/jobs`(step 结论)+
|
||||||
|
`/wangjia/pangolin/actions/runs/<url_id>/jobs/<job_db_id>/logs`(原始日志)。
|
||||||
|
- 节点**新机初始化**仍手动(scp+ssh 跑 bootstrap / single-node),不走 CI。
|
||||||
|
|
||||||
## 设计 Token 单源模型
|
## 设计 Token 单源模型
|
||||||
|
|
||||||
@@ -179,6 +207,11 @@ cd web/website && npm run gen:tokens
|
|||||||
- Android:`bash scripts/build-libbox.sh android` → `Libbox.aar`,**重命名小写** `libbox.aar` 放 `app/kernel/dist/android/`。⚠️ gomobile 编 Android **强制 JDK 17**(JDK 21 直接拒);`export JAVA_HOME=/opt/homebrew/opt/openjdk@17/...` 再编。
|
- Android:`bash scripts/build-libbox.sh android` → `Libbox.aar`,**重命名小写** `libbox.aar` 放 `app/kernel/dist/android/`。⚠️ gomobile 编 Android **强制 JDK 17**(JDK 21 直接拒);`export JAVA_HOME=/opt/homebrew/opt/openjdk@17/...` 再编。
|
||||||
- ⚠️ **Android libbox Java 包名是 `io.nekohasekai.libbox`**(不是 `libbox`),Kotlin import 用前者。
|
- ⚠️ **Android libbox Java 包名是 `io.nekohasekai.libbox`**(不是 `libbox`),Kotlin import 用前者。
|
||||||
|
|
||||||
|
**真机装机(老忘——有现成脚本,别手搓 xcodebuild/签名)**:
|
||||||
|
- **iOS**:`API_URL=https://api.yanmeiai.com bash scripts/local_test.sh ipad "<设备名/id>"`(`local_test.sh ios-devices` 列已连设备)。脚本自动:flutter build ipa(**公司分发证书** Apple Distribution: Yanmei / Team `BYL4KQHMTN`,ad-hoc)→ 核验签名主体(防无声退回个人证书)→ `xcrun devicectl` 装机。`API_URL` 决定客户端连哪个控制面(prod = `https://api.yanmeiai.com`)。
|
||||||
|
- iOS libbox 是 **gitignore 产物**,新 worktree 常缺 → 从主仓拷免重建:`cp -R /Users/wangjia/code/pangolin/client/ios/Frameworks/Libbox.xcframework client/ios/Frameworks/`(routing 等功能不碰 libbox 接口,主仓那份兼容)。
|
||||||
|
- 新设备首次装报 `0xe8008012`(描述文件不含 UDID)→ 需 xcodebuild `-allowProvisioningUpdates -allowProvisioningDeviceRegistration`(脚本 die 里给了兜底命令);chen 的设备(chen-macbook/chen-iphone)已注册。装机走**公司**分发证书,禁个人开发证书(记忆 `ios-install-team-cert`)。
|
||||||
|
|
||||||
## 跨端实时统计 + urltest 延迟(连接页"延迟"的唯一正解)
|
## 跨端实时统计 + urltest 延迟(连接页"延迟"的唯一正解)
|
||||||
|
|
||||||
连接页"延迟"= 内核 urltest(经 REALITY 真实出站测 RTT);**坑很深,改前必读**
|
连接页"延迟"= 内核 urltest(经 REALITY 真实出站测 RTT);**坑很深,改前必读**
|
||||||
|
|||||||
@@ -663,6 +663,8 @@ abstract class AppText {
|
|||||||
String get routingRuleValueHint; // 目标输入框占位 / Target input placeholder
|
String get routingRuleValueHint; // 目标输入框占位 / Target input placeholder
|
||||||
String get routingNoRules; // 暂无自定义规则 / No custom rules yet
|
String get routingNoRules; // 暂无自定义规则 / No custom rules yet
|
||||||
String get routingAddRule; // 添加规则 / Add rule
|
String get routingAddRule; // 添加规则 / Add rule
|
||||||
|
String get routingSaveFailed; // 保存失败,请重试 / Save failed, please try again
|
||||||
|
String get routingRuleValueInvalid; // 格式不正确 / Invalid format
|
||||||
String get routingImport; // 从文本导入 / Import from text
|
String get routingImport; // 从文本导入 / Import from text
|
||||||
String get routingReset; // 重置默认 / Reset defaults
|
String get routingReset; // 重置默认 / Reset defaults
|
||||||
String get routingResetConfirmTitle; // 重置为默认规则? / Reset to defaults?
|
String get routingResetConfirmTitle; // 重置为默认规则? / Reset to defaults?
|
||||||
|
|||||||
@@ -571,6 +571,10 @@ class StringsEn extends AppText {
|
|||||||
@override
|
@override
|
||||||
String get routingAddRule => 'Add rule';
|
String get routingAddRule => 'Add rule';
|
||||||
@override
|
@override
|
||||||
|
String get routingSaveFailed => 'Save failed, please try again';
|
||||||
|
@override
|
||||||
|
String get routingRuleValueInvalid => 'Invalid format';
|
||||||
|
@override
|
||||||
String get routingImport => 'Import from text';
|
String get routingImport => 'Import from text';
|
||||||
@override
|
@override
|
||||||
String get routingReset => 'Reset defaults';
|
String get routingReset => 'Reset defaults';
|
||||||
|
|||||||
@@ -571,6 +571,10 @@ class StringsEs extends AppText {
|
|||||||
@override
|
@override
|
||||||
String get routingAddRule => 'Añadir regla';
|
String get routingAddRule => 'Añadir regla';
|
||||||
@override
|
@override
|
||||||
|
String get routingSaveFailed => 'Error al guardar, inténtalo de nuevo';
|
||||||
|
@override
|
||||||
|
String get routingRuleValueInvalid => 'Formato no válido';
|
||||||
|
@override
|
||||||
String get routingImport => 'Importar desde texto';
|
String get routingImport => 'Importar desde texto';
|
||||||
@override
|
@override
|
||||||
String get routingReset => 'Restablecer';
|
String get routingReset => 'Restablecer';
|
||||||
|
|||||||
@@ -571,6 +571,10 @@ class StringsJa extends AppText {
|
|||||||
@override
|
@override
|
||||||
String get routingAddRule => 'ルールを追加';
|
String get routingAddRule => 'ルールを追加';
|
||||||
@override
|
@override
|
||||||
|
String get routingSaveFailed => '保存に失敗しました。もう一度お試しください';
|
||||||
|
@override
|
||||||
|
String get routingRuleValueInvalid => '形式が正しくありません';
|
||||||
|
@override
|
||||||
String get routingImport => 'テキストから読み込み';
|
String get routingImport => 'テキストから読み込み';
|
||||||
@override
|
@override
|
||||||
String get routingReset => 'デフォルトに戻す';
|
String get routingReset => 'デフォルトに戻す';
|
||||||
|
|||||||
@@ -571,6 +571,10 @@ class StringsKo extends AppText {
|
|||||||
@override
|
@override
|
||||||
String get routingAddRule => '규칙 추가';
|
String get routingAddRule => '규칙 추가';
|
||||||
@override
|
@override
|
||||||
|
String get routingSaveFailed => '저장에 실패했습니다. 다시 시도하세요';
|
||||||
|
@override
|
||||||
|
String get routingRuleValueInvalid => '형식이 올바르지 않습니다';
|
||||||
|
@override
|
||||||
String get routingImport => '텍스트에서 가져오기';
|
String get routingImport => '텍스트에서 가져오기';
|
||||||
@override
|
@override
|
||||||
String get routingReset => '기본값 재설정';
|
String get routingReset => '기본값 재설정';
|
||||||
|
|||||||
@@ -571,6 +571,10 @@ class StringsRu extends AppText {
|
|||||||
@override
|
@override
|
||||||
String get routingAddRule => 'Добавить правило';
|
String get routingAddRule => 'Добавить правило';
|
||||||
@override
|
@override
|
||||||
|
String get routingSaveFailed => 'Не удалось сохранить, попробуйте ещё раз';
|
||||||
|
@override
|
||||||
|
String get routingRuleValueInvalid => 'Неверный формат';
|
||||||
|
@override
|
||||||
String get routingImport => 'Импорт из текста';
|
String get routingImport => 'Импорт из текста';
|
||||||
@override
|
@override
|
||||||
String get routingReset => 'Сбросить настройки';
|
String get routingReset => 'Сбросить настройки';
|
||||||
|
|||||||
@@ -571,6 +571,10 @@ class StringsZh extends AppText {
|
|||||||
@override
|
@override
|
||||||
String get routingAddRule => '添加规则';
|
String get routingAddRule => '添加规则';
|
||||||
@override
|
@override
|
||||||
|
String get routingSaveFailed => '保存失败,请重试';
|
||||||
|
@override
|
||||||
|
String get routingRuleValueInvalid => '格式不正确';
|
||||||
|
@override
|
||||||
String get routingImport => '从文本导入';
|
String get routingImport => '从文本导入';
|
||||||
@override
|
@override
|
||||||
String get routingReset => '重置默认';
|
String get routingReset => '重置默认';
|
||||||
|
|||||||
@@ -13,12 +13,15 @@
|
|||||||
// - 域名类规则(domain/domain_suffix/domain_keyword)命中 RoutingProfile.
|
// - 域名类规则(domain/domain_suffix/domain_keyword)命中 RoutingProfile.
|
||||||
// systemLockedDomains(FT-A 起 GET /v1/me/routing 下发的私有服务域名清单,
|
// systemLockedDomains(FT-A 起 GET /v1/me/routing 下发的私有服务域名清单,
|
||||||
// PANGOLIN_PRIVATE_SPLIT_DOMAINS)——服务端渲染时恒强制走隧道,与用户规则动作冲突。
|
// PANGOLIN_PRIVATE_SPLIT_DOMAINS)——服务端渲染时恒强制走隧道,与用户规则动作冲突。
|
||||||
|
import 'dart:io' show InternetAddress, InternetAddressType;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||||
|
|
||||||
import '../l10n/app_text.dart';
|
import '../l10n/app_text.dart';
|
||||||
import '../models/routing_profile.dart';
|
import '../models/routing_profile.dart';
|
||||||
import '../pangolin_theme.dart';
|
import '../pangolin_theme.dart';
|
||||||
|
import '../services/auth_api.dart' show AuthApiException;
|
||||||
import '../state/app_providers.dart';
|
import '../state/app_providers.dart';
|
||||||
import '../state/routing_provider.dart';
|
import '../state/routing_provider.dart';
|
||||||
import 'pangolin_button.dart';
|
import 'pangolin_button.dart';
|
||||||
@@ -61,6 +64,25 @@ class RoutingScreen extends ConsumerWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 变更类操作统一守卫:await + 失败弹 SnackBar(不再静默回滚 / 抛未捕获异步异常)。
|
||||||
|
/// _persist 失败已回滚 state 并 rethrow,这里兜住并把原因告知用户;AuthApiException
|
||||||
|
/// 带服务端双语文案(含 routing_invalid 校验错误),其余异常回退通用「保存失败」。
|
||||||
|
Future<void> _guardSave(BuildContext context, AppText t, Future<void> Function() op) async {
|
||||||
|
try {
|
||||||
|
await op();
|
||||||
|
} on AuthApiException catch (e) {
|
||||||
|
if (!context.mounted) return;
|
||||||
|
_showRoutingError(context, t.lang == AppLang.zh ? e.messageZh : e.messageEn);
|
||||||
|
} catch (_) {
|
||||||
|
if (!context.mounted) return;
|
||||||
|
_showRoutingError(context, t.routingSaveFailed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showRoutingError(BuildContext context, String msg) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
|
||||||
|
}
|
||||||
|
|
||||||
class _RoutingBody extends ConsumerWidget {
|
class _RoutingBody extends ConsumerWidget {
|
||||||
const _RoutingBody({required this.t, required this.profile});
|
const _RoutingBody({required this.t, required this.profile});
|
||||||
final AppText t;
|
final AppText t;
|
||||||
@@ -86,7 +108,7 @@ class _RoutingBody extends ConsumerWidget {
|
|||||||
(icon: PangolinIcons.arrowRight, label: t.routingModeDirect),
|
(icon: PangolinIcons.arrowRight, label: t.routingModeDirect),
|
||||||
],
|
],
|
||||||
selectedIndex: selectedIdx,
|
selectedIndex: selectedIdx,
|
||||||
onChanged: (i) => notifier.setMode(_kModeValues[i]),
|
onChanged: (i) => _guardSave(context, t, () => notifier.setMode(_kModeValues[i])),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(t.routingModeNote, style: PangolinText.caption.copyWith(color: c.fg3, height: 1.5)),
|
Text(t.routingModeNote, style: PangolinText.caption.copyWith(color: c.fg3, height: 1.5)),
|
||||||
@@ -101,7 +123,7 @@ class _RoutingBody extends ConsumerWidget {
|
|||||||
title: t.routingCnDirect,
|
title: t.routingCnDirect,
|
||||||
sub: 'GeoIP / GeoSite CN',
|
sub: 'GeoIP / GeoSite CN',
|
||||||
value: profile.builtin.chinaDirect,
|
value: profile.builtin.chinaDirect,
|
||||||
onChanged: (v) => notifier.setBuiltin(profile.builtin.copyWith(chinaDirect: v)),
|
onChanged: (v) => _guardSave(context, t, () => notifier.setBuiltin(profile.builtin.copyWith(chinaDirect: v))),
|
||||||
last: false,
|
last: false,
|
||||||
),
|
),
|
||||||
_forcedRow(c, icon: PangolinIcons.home, title: t.routingLanDirect, sub: t.routingLanForced, pill: t.routingForcedPill),
|
_forcedRow(c, icon: PangolinIcons.home, title: t.routingLanDirect, sub: t.routingLanForced, pill: t.routingForcedPill),
|
||||||
@@ -135,14 +157,14 @@ class _RoutingBody extends ConsumerWidget {
|
|||||||
shrinkWrap: true,
|
shrinkWrap: true,
|
||||||
physics: const NeverScrollableScrollPhysics(),
|
physics: const NeverScrollableScrollPhysics(),
|
||||||
buildDefaultDragHandles: false,
|
buildDefaultDragHandles: false,
|
||||||
onReorder: (oldIndex, newIndex) => notifier.reorder(oldIndex, newIndex),
|
onReorder: (oldIndex, newIndex) => _guardSave(context, t, () => notifier.reorder(oldIndex, newIndex)),
|
||||||
children: [
|
children: [
|
||||||
for (var i = 0; i < profile.rules.length; i++)
|
for (var i = 0; i < profile.rules.length; i++)
|
||||||
_ruleRow(
|
_ruleRow(
|
||||||
context, c, t, i, profile.rules[i],
|
context, c, t, i, profile.rules[i],
|
||||||
_conflictFor(profile.rules, i, profile.systemLockedDomains),
|
_conflictFor(profile.rules, i, profile.systemLockedDomains),
|
||||||
i < profile.rules.length - 1,
|
i < profile.rules.length - 1,
|
||||||
onDelete: () => notifier.removeRule(i)),
|
onDelete: () => _guardSave(context, t, () => notifier.removeRule(i))),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -220,13 +242,15 @@ class _RoutingBody extends ConsumerWidget {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (ok != true) return;
|
if (ok != true) return;
|
||||||
await ref.read(routingProfileProvider.notifier).resetToDefault();
|
if (!context.mounted) return;
|
||||||
|
await _guardSave(context, t, () => ref.read(routingProfileProvider.notifier).resetToDefault());
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openAddDialog(BuildContext context, WidgetRef ref, AppText t) async {
|
Future<void> _openAddDialog(BuildContext context, WidgetRef ref, AppText t) async {
|
||||||
final rule = await showDialog<RoutingRule>(context: context, builder: (_) => _AddRuleDialog(t: t));
|
final rule = await showDialog<RoutingRule>(context: context, builder: (_) => _AddRuleDialog(t: t));
|
||||||
if (rule == null) return;
|
if (rule == null) return;
|
||||||
await ref.read(routingProfileProvider.notifier).addRule(rule);
|
if (!context.mounted) return;
|
||||||
|
await _guardSave(context, t, () => ref.read(routingProfileProvider.notifier).addRule(rule));
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _builtinToggleRow(
|
Widget _builtinToggleRow(
|
||||||
@@ -446,11 +470,38 @@ class _AddRuleDialogState extends State<_AddRuleDialog> {
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 字段级预校验:只拦明显格式错(空由按钮禁用兜底),避免"乐观显示→服务端 400→静默消失"。
|
||||||
|
/// 语义级(保留段/catch-all direct)仍由服务端权威判定,经 SnackBar 呈现。返回 null=通过。
|
||||||
|
String? _valueError(AppText t) {
|
||||||
|
final v = _value.text.trim();
|
||||||
|
if (v.isEmpty) return null;
|
||||||
|
switch (_type) {
|
||||||
|
case 'ip_cidr':
|
||||||
|
if (!_isValidCidr(v)) return t.routingRuleValueInvalid;
|
||||||
|
case 'geoip':
|
||||||
|
case 'geosite':
|
||||||
|
if (v.toLowerCase() != 'cn') return t.routingRuleValueInvalid; // geo 白名单仅 cn
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _isValidCidr(String s) {
|
||||||
|
final parts = s.split('/');
|
||||||
|
if (parts.length != 2) return false;
|
||||||
|
final prefix = int.tryParse(parts[1]);
|
||||||
|
if (prefix == null) return false;
|
||||||
|
final addr = InternetAddress.tryParse(parts[0]);
|
||||||
|
if (addr == null) return false;
|
||||||
|
final max = addr.type == InternetAddressType.IPv6 ? 128 : 32;
|
||||||
|
return prefix >= 0 && prefix <= max;
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final c = context.pangolin;
|
final c = context.pangolin;
|
||||||
final t = widget.t;
|
final t = widget.t;
|
||||||
final canSave = _value.text.trim().isNotEmpty;
|
final valueError = _valueError(t);
|
||||||
|
final canSave = _value.text.trim().isNotEmpty && valueError == null;
|
||||||
|
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
backgroundColor: c.surface,
|
backgroundColor: c.surface,
|
||||||
@@ -479,6 +530,11 @@ class _AddRuleDialogState extends State<_AddRuleDialog> {
|
|||||||
onChanged: (_) => setState(() {}),
|
onChanged: (_) => setState(() {}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
if (valueError != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 6, left: 4),
|
||||||
|
child: Text(valueError, style: PangolinText.caption.copyWith(color: c.danger)),
|
||||||
|
),
|
||||||
const SizedBox(height: 14),
|
const SizedBox(height: 14),
|
||||||
SegSwitch(
|
SegSwitch(
|
||||||
options: [
|
options: [
|
||||||
|
|||||||
@@ -49,30 +49,32 @@ class SegSwitch extends StatelessWidget {
|
|||||||
child: AnimatedContainer(
|
child: AnimatedContainer(
|
||||||
duration: const Duration(milliseconds: 140),
|
duration: const Duration(milliseconds: 140),
|
||||||
curve: Curves.easeOut,
|
curve: Curves.easeOut,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
// .segswitch-opt.is-active:surface 底 + shadow-sm;未选透明
|
// .segswitch-opt.is-active:surface 底 + shadow-sm;未选透明
|
||||||
color: active ? c.surface : Colors.transparent,
|
color: active ? c.surface : Colors.transparent,
|
||||||
borderRadius: BorderRadius.circular(PangolinRadius.full),
|
borderRadius: BorderRadius.circular(PangolinRadius.full),
|
||||||
boxShadow: active ? PangolinShadow.sm : null,
|
boxShadow: active ? PangolinShadow.sm : null,
|
||||||
),
|
),
|
||||||
child: Row(
|
// FittedBox(scaleDown):放得下则原样(宽段选不变),放不下则图标+文字整体
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
// 等比缩放而非把文字 ellipsis 截断(窄弹层里 Direct/Tunnel/Reject 曾被截成 Dire…)。
|
||||||
children: [
|
child: FittedBox(
|
||||||
Icon(o.icon, size: 16, color: active ? c.fg1 : c.fg2),
|
fit: BoxFit.scaleDown,
|
||||||
const SizedBox(width: 8),
|
child: Row(
|
||||||
Flexible(
|
mainAxisSize: MainAxisSize.min,
|
||||||
child: Text(
|
children: [
|
||||||
|
Icon(o.icon, size: 16, color: active ? c.fg1 : c.fg2),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
o.label,
|
o.label,
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: PangolinText.sm.copyWith(
|
style: PangolinText.sm.copyWith(
|
||||||
color: active ? c.fg1 : c.fg2,
|
color: active ? c.fg1 : c.fg2,
|
||||||
fontWeight: FontWeight.w600,
|
fontWeight: FontWeight.w600,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
],
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2241,6 +2241,22 @@
|
|||||||
"ru": "Добавить правило",
|
"ru": "Добавить правило",
|
||||||
"es": "Añadir regla"
|
"es": "Añadir regla"
|
||||||
},
|
},
|
||||||
|
"routingSaveFailed": {
|
||||||
|
"zh": "保存失败,请重试",
|
||||||
|
"en": "Save failed, please try again",
|
||||||
|
"ja": "保存に失敗しました。もう一度お試しください",
|
||||||
|
"ko": "저장에 실패했습니다. 다시 시도하세요",
|
||||||
|
"ru": "Не удалось сохранить, попробуйте ещё раз",
|
||||||
|
"es": "Error al guardar, inténtalo de nuevo"
|
||||||
|
},
|
||||||
|
"routingRuleValueInvalid": {
|
||||||
|
"zh": "格式不正确",
|
||||||
|
"en": "Invalid format",
|
||||||
|
"ja": "形式が正しくありません",
|
||||||
|
"ko": "형식이 올바르지 않습니다",
|
||||||
|
"ru": "Неверный формат",
|
||||||
|
"es": "Formato no válido"
|
||||||
|
},
|
||||||
"routingImport": {
|
"routingImport": {
|
||||||
"zh": "从文本导入",
|
"zh": "从文本导入",
|
||||||
"en": "Import from text",
|
"en": "Import from text",
|
||||||
|
|||||||
@@ -43,11 +43,14 @@ type ClientConfigOpts struct {
|
|||||||
// - extraExclude: type==ip_cidr && action==direct 的 value,供调用方并入
|
// - extraExclude: type==ip_cidr && action==direct 的 value,供调用方并入
|
||||||
// TUN 入站的 route_exclude_address(auto_route 层直连才真正生效,
|
// TUN 入站的 route_exclude_address(auto_route 层直连才真正生效,
|
||||||
// 见 tunIn 构造处注释)。
|
// 见 tunIn 构造处注释)。
|
||||||
// - hasDomainDirect: 是否存在 action==direct 的域名类规则(domain/
|
// - hasDomainRule: 是否存在**任意** action 的域名类规则(domain/
|
||||||
// domain_suffix/domain_keyword),供调用方决定是否开 dns.reverse_mapping。
|
// domain_suffix/domain_keyword),供调用方决定是否开 dns.reverse_mapping。
|
||||||
|
// 不限 direct:走隧道/拒绝的域名规则同样需要反向映射——应用自行解析域名后
|
||||||
|
// 按 IP 发起连接,路由层只剩 IP,没有 reverse_mapping 则 domain 规则永不命中、
|
||||||
|
// 该规则(不论直连/隧道/拒绝)静默失效。
|
||||||
// - geoSets: 规则引用到的 geoip-<v>/geosite-<v> rule_set tag(去重),供
|
// - geoSets: 规则引用到的 geoip-<v>/geosite-<v> rule_set tag(去重),供
|
||||||
// 调用方在国内分流(splitActive)之外也补上 rule_set 定义。
|
// 调用方在国内分流(splitActive)之外也补上 rule_set 定义。
|
||||||
func translateUserRules(p *routing.Profile) (rules []any, extraExclude []string, hasDomainDirect bool, geoSets []string) {
|
func translateUserRules(p *routing.Profile) (rules []any, extraExclude []string, hasDomainRule bool, geoSets []string) {
|
||||||
if p == nil || p.Mode != "rule" {
|
if p == nil || p.Mode != "rule" {
|
||||||
return nil, nil, false, nil
|
return nil, nil, false, nil
|
||||||
}
|
}
|
||||||
@@ -71,12 +74,13 @@ func translateUserRules(p *routing.Profile) (rules []any, extraExclude []string,
|
|||||||
switch r.Type {
|
switch r.Type {
|
||||||
case "domain", "domain_suffix", "domain_keyword":
|
case "domain", "domain_suffix", "domain_keyword":
|
||||||
rules = append(rules, map[string]any{r.Type: []string{r.Value}, "outbound": outbound})
|
rules = append(rules, map[string]any{r.Type: []string{r.Value}, "outbound": outbound})
|
||||||
if outbound == "direct" {
|
// 任意 action 的域名规则都要 reverse_mapping(见返回值注释),不止 direct。
|
||||||
hasDomainDirect = true
|
hasDomainRule = true
|
||||||
}
|
|
||||||
case "ip_cidr":
|
case "ip_cidr":
|
||||||
rules = append(rules, map[string]any{"ip_cidr": []string{r.Value}, "outbound": outbound})
|
rules = append(rules, map[string]any{"ip_cidr": []string{r.Value}, "outbound": outbound})
|
||||||
if outbound == "direct" {
|
// 纵深防护:只有安全的 direct ip_cidr 才并入 route_exclude_address。
|
||||||
|
// catch-all/隧道保留段会静默旁路系统层(Validate 已在写入路径拦,这里兜底历史坏行)。
|
||||||
|
if outbound == "direct" && routing.SafeToExclude(r.Value) {
|
||||||
extraExclude = append(extraExclude, r.Value)
|
extraExclude = append(extraExclude, r.Value)
|
||||||
}
|
}
|
||||||
case "geoip", "geosite":
|
case "geoip", "geosite":
|
||||||
@@ -88,7 +92,7 @@ func translateUserRules(p *routing.Profile) (rules []any, extraExclude []string,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return rules, extraExclude, hasDomainDirect, geoSets
|
return rules, extraExclude, hasDomainRule, geoSets
|
||||||
}
|
}
|
||||||
|
|
||||||
// ruleSetDef 渲染一个自托管 remote rule_set 定义(与既有 geoip-cn/geosite-cn
|
// ruleSetDef 渲染一个自托管 remote rule_set 定义(与既有 geoip-cn/geosite-cn
|
||||||
@@ -243,10 +247,10 @@ func BuildClientConfig(node *nodes.NodeRow, dpUUID, deriveKey string, opts Clien
|
|||||||
// 直接返回全零值,以下每一步都随之短路,保证 nil-profile 渲染逐字节不变。
|
// 直接返回全零值,以下每一步都随之短路,保证 nil-profile 渲染逐字节不变。
|
||||||
var userRules []any
|
var userRules []any
|
||||||
var extraExclude []string
|
var extraExclude []string
|
||||||
var hasDomainDirect bool
|
var hasDomainRule bool
|
||||||
var geoSets []string
|
var geoSets []string
|
||||||
if opts.Profile != nil {
|
if opts.Profile != nil {
|
||||||
userRules, extraExclude, hasDomainDirect, geoSets = translateUserRules(opts.Profile)
|
userRules, extraExclude, hasDomainRule, geoSets = translateUserRules(opts.Profile)
|
||||||
if opts.RulesBaseURL == "" && len(geoSets) > 0 {
|
if opts.RulesBaseURL == "" && len(geoSets) > 0 {
|
||||||
// 没有 base 就没法渲染 remote rule_set 的下载 URL,引用它的用户规则
|
// 没有 base 就没法渲染 remote rule_set 的下载 URL,引用它的用户规则
|
||||||
// 会指向未定义的 tag(sing-box FATAL)。与 splitActive 缺 base 时静默
|
// 会指向未定义的 tag(sing-box FATAL)。与 splitActive 缺 base 时静默
|
||||||
@@ -380,10 +384,11 @@ func BuildClientConfig(node *nodes.NodeRow, dpUUID, deriveKey string, opts Clien
|
|||||||
"domain": opts.PrivateSplitDomains, "server": "dns-system",
|
"domain": opts.PrivateSplitDomains, "server": "dns-system",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if privateSplit || hasDomainDirect {
|
if privateSplit || hasDomainRule {
|
||||||
// 回映射:记住"哪个 IP 是哪个域名解析出来的",给后续按 IP 发起的连接补回
|
// 回映射:记住"哪个 IP 是哪个域名解析出来的",给后续按 IP 发起的连接补回
|
||||||
// 域名元数据——路由层的 domain 规则(私有域名→隧道 / 用户域名直连)靠它
|
// 域名元数据——路由层的 domain 规则(私有域名→隧道 / 用户域名规则)靠它
|
||||||
// 才会命中。hasDomainDirect:用户规则含 action==direct 的域名类规则时同样需要。
|
// 才会命中。hasDomainRule:用户规则含**任意** action 的域名类规则(直连/
|
||||||
|
// 走隧道/拒绝)时都需要——否则该域名规则永不命中、静默失效。
|
||||||
dns["reverse_mapping"] = true
|
dns["reverse_mapping"] = true
|
||||||
}
|
}
|
||||||
// 国内分流的 DNS 面(补 #5 数据面之外的 DNS 面):开分流时,命中 geosite-cn 的
|
// 国内分流的 DNS 面(补 #5 数据面之外的 DNS 面):开分流时,命中 geosite-cn 的
|
||||||
|
|||||||
@@ -358,6 +358,32 @@ func TestBuildConfigUserRules(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 回归钉:走隧道/拒绝的域名规则也必须开 reverse_mapping。应用自行解析域名后按 IP
|
||||||
|
// 发起连接,路由层只剩 IP,无反向映射则 domain 规则永不命中、该规则静默失效。
|
||||||
|
// 旧实现只为 action==direct 的域名规则开 reverse_mapping,走隧道/拒绝会漏 → 本测试
|
||||||
|
// 用**唯一一条走隧道域名规则**(无任何 direct 域名规则、privateSplit 关)钉死修复。
|
||||||
|
func TestBuildConfigProxyDomainEnablesReverseMapping(t *testing.T) {
|
||||||
|
for _, action := range []string{"proxy", "reject"} {
|
||||||
|
node := testNode()
|
||||||
|
p := routing.Default()
|
||||||
|
p.Rules = []routing.Rule{
|
||||||
|
{Type: "domain_suffix", Value: "example.com", Action: action, Enabled: true},
|
||||||
|
}
|
||||||
|
// SplitCN 关 + 不给 PrivateSplitDomains → reverse_mapping 只可能由该域名规则触发。
|
||||||
|
raw, err := BuildClientConfig(node, "dp", "k", ClientConfigOpts{Profile: p})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var cfg map[string]any
|
||||||
|
if err := json.Unmarshal(raw, &cfg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cfg["dns"].(map[string]any)["reverse_mapping"] != true {
|
||||||
|
t.Fatalf("action=%s domain rule must enable reverse_mapping", action)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestBuildConfigGlobalMode(t *testing.T) {
|
func TestBuildConfigGlobalMode(t *testing.T) {
|
||||||
p := routing.Default()
|
p := routing.Default()
|
||||||
p.Mode = "global"
|
p.Mode = "global"
|
||||||
|
|||||||
@@ -71,6 +71,40 @@ var validType = map[string]bool{"domain": true, "domain_suffix": true, "domain_k
|
|||||||
var validAction = map[string]bool{"direct": true, "proxy": true, "reject": true}
|
var validAction = map[string]bool{"direct": true, "proxy": true, "reject": true}
|
||||||
var geoWhitelist = map[string]bool{"cn": true} // geoip/geosite 仅自托管 cn
|
var geoWhitelist = map[string]bool{"cn": true} // geoip/geosite 仅自托管 cn
|
||||||
|
|
||||||
|
// reservedTunnelNet 是隧道/内部 DNS 保留段(含隧道 DNS 172.19.0.2)。direct 的
|
||||||
|
// ip_cidr 规则会并入 TUN 入站 route_exclude_address(OS/auto_route 层,位于系统
|
||||||
|
// 强制层之下),若排除此段会静默旁路 hijack-dns 与整条隧道 —— 见 Validate 里的守卫。
|
||||||
|
var reservedTunnelNet = mustCIDR("172.16.0.0/12")
|
||||||
|
|
||||||
|
func mustCIDR(s string) *net.IPNet {
|
||||||
|
_, n, err := net.ParseCIDR(s)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// cidrsOverlap 判断两个对齐的 CIDR 块是否相交(其一的网络地址落在另一之内)。
|
||||||
|
// 家族不匹配(v4 vs v6)时 net.IPNet.Contains 返回 false,故混用安全。
|
||||||
|
func cidrsOverlap(a, b *net.IPNet) bool {
|
||||||
|
return a.Contains(b.IP) || b.Contains(a.IP)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SafeToExclude 报告一条 direct 的 ip_cidr 值是否可安全并入 TUN route_exclude_address。
|
||||||
|
// 与 Validate 的守卫同源:catch-all 或与隧道/DNS 保留段重叠一律拒绝。渲染层(clientconfig)
|
||||||
|
// 在合并 extraExclude 前调用它,作纵深防护——即便有写入闸之前存下的历史坏行,也不会
|
||||||
|
// 让它静默旁路系统强制层。
|
||||||
|
func SafeToExclude(cidr string) bool {
|
||||||
|
_, ipnet, err := net.ParseCIDR(cidr)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if ones, _ := ipnet.Mask.Size(); ones == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return !cidrsOverlap(ipnet, reservedTunnelNet)
|
||||||
|
}
|
||||||
|
|
||||||
// Validate checks the profile against the type/action whitelist, CIDR
|
// Validate checks the profile against the type/action whitelist, CIDR
|
||||||
// syntax, the geo set whitelist, and the rule count cap. It returns an empty
|
// syntax, the geo set whitelist, and the rule count cap. It returns an empty
|
||||||
// (non-nil) slice when the profile is valid — so JSON encoding produces `[]`
|
// (non-nil) slice when the profile is valid — so JSON encoding produces `[]`
|
||||||
@@ -99,8 +133,18 @@ func (p *Profile) Validate() []FieldError {
|
|||||||
}
|
}
|
||||||
switch r.Type {
|
switch r.Type {
|
||||||
case "ip_cidr":
|
case "ip_cidr":
|
||||||
if _, _, err := net.ParseCIDR(r.Value); err != nil {
|
_, ipnet, err := net.ParseCIDR(r.Value)
|
||||||
|
if err != nil {
|
||||||
errs = append(errs, FieldError{i, "value", "invalid CIDR"})
|
errs = append(errs, FieldError{i, "value", "invalid CIDR"})
|
||||||
|
} else if r.Action == "direct" {
|
||||||
|
// direct 的 ip_cidr 并入 TUN route_exclude_address(系统层之下)。
|
||||||
|
// catch-all(/0)会整条旁路隧道;与隧道/DNS 保留段重叠会破坏隧道 DNS。
|
||||||
|
// 二者都能静默越过系统强制层,拒绝之(proxy/reject 不入排除表,不受限)。
|
||||||
|
if ones, _ := ipnet.Mask.Size(); ones == 0 {
|
||||||
|
errs = append(errs, FieldError{i, "value", "direct ip_cidr must not be catch-all (0.0.0.0/0 or ::/0)"})
|
||||||
|
} else if cidrsOverlap(ipnet, reservedTunnelNet) {
|
||||||
|
errs = append(errs, FieldError{i, "value", "direct ip_cidr must not overlap reserved tunnel range 172.16.0.0/12"})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case "geoip", "geosite":
|
case "geoip", "geosite":
|
||||||
if !geoWhitelist[strings.ToLower(r.Value)] {
|
if !geoWhitelist[strings.ToLower(r.Value)] {
|
||||||
|
|||||||
@@ -42,6 +42,37 @@ func TestValidate(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestValidateDirectIPCIDRReservedGuard(t *testing.T) {
|
||||||
|
// direct 的 ip_cidr 会并入 TUN route_exclude_address(系统层之下),catch-all 或
|
||||||
|
// 与隧道/DNS 保留段(172.16.0.0/12)重叠会静默旁路 hijack-dns/隧道 → 必须拒绝。
|
||||||
|
rejected := []Rule{
|
||||||
|
{Type: "ip_cidr", Value: "0.0.0.0/0", Action: "direct", Enabled: true},
|
||||||
|
{Type: "ip_cidr", Value: "::/0", Action: "direct", Enabled: true},
|
||||||
|
{Type: "ip_cidr", Value: "172.16.0.0/12", Action: "direct", Enabled: true},
|
||||||
|
{Type: "ip_cidr", Value: "172.19.0.0/16", Action: "direct", Enabled: true}, // 含隧道 DNS 172.19.0.2
|
||||||
|
}
|
||||||
|
for _, r := range rejected {
|
||||||
|
p := Default()
|
||||||
|
p.Rules = []Rule{r}
|
||||||
|
if errs := p.Validate(); len(errs) == 0 {
|
||||||
|
t.Errorf("direct ip_cidr %q 应被拒,却无报错", r.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// proxy/reject 不入排除表故不受限;不与保留段重叠的 direct 允许。
|
||||||
|
allowed := []Rule{
|
||||||
|
{Type: "ip_cidr", Value: "0.0.0.0/0", Action: "proxy", Enabled: true},
|
||||||
|
{Type: "ip_cidr", Value: "10.0.0.0/8", Action: "direct", Enabled: true},
|
||||||
|
{Type: "ip_cidr", Value: "8.8.8.8/32", Action: "direct", Enabled: true},
|
||||||
|
}
|
||||||
|
for _, r := range allowed {
|
||||||
|
p := Default()
|
||||||
|
p.Rules = []Rule{r}
|
||||||
|
if errs := p.Validate(); len(errs) != 0 {
|
||||||
|
t.Errorf("ip_cidr %q action=%s 应允许,却报错 %v", r.Value, r.Action, errs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestValidateCountLimit(t *testing.T) {
|
func TestValidateCountLimit(t *testing.T) {
|
||||||
p := Default()
|
p := Default()
|
||||||
for i := 0; i < 201; i++ {
|
for i := 0; i < 201; i++ {
|
||||||
|
|||||||
Reference in New Issue
Block a user