Compare commits

..

5 Commits

Author SHA1 Message Date
wangjia 9aafb63461 chore(todo): 同步最新看板到 main(#24-#27 + #23→done)
Deploy Server / deploy-server (push) Successful in 4m7s
主 checkout 停在陈旧 feat/private-dest-acl,其工作区 todo 看板反而领先 main
4 条(#24 UI连接态脱钩 / #25 私有服务在家直连 / #26 MySQL Promo 并发防线 /
#27 分支审核 Minor 硬化)且 #23 已推进到 done。工作区是 main 的干净超集
(main 无任何独有条目),取工作区版覆盖回 main,零丢失。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-08-01 02:12:34 +08:00
wangjia 6f232d4043 fix(routing): 堵住 ip_cidr direct 旁路系统层 + 客户端保存失败可见提示
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 25s
ci-pangolin / Cleartext Scan — Android 禁明文 (push) Successful in 19s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 18s
ci-pangolin / Golden — 视觉回归 (全量:components/auth/desktop/tablet) (push) Failing after 13m6s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 13m16s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Failing after 13m25s
ci-pangolin / Go — build + test (push) Failing after 13m35s
ci-pangolin / DS-flow — 原型/跨端同源/代码色单源闸 (push) Failing after 13m45s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Failing after 13m54s
ci-pangolin / Flutter — analyze + test (push) Failing after 14m5s
ci-pangolin / OpenAPI Sync Check (push) Failing after 14m16s
ci-pangolin / Lint — shellcheck (push) Failing after 14m27s
分支审核发现两处 Important,合并前修复。

① [安全] direct 的 ip_cidr 用户规则可自伤式旁路整条隧道:
   Validate 原先只校 CIDR 语法。用户提交 ip_cidr=0.0.0.0/0 action=direct
   (或 172.16.0.0/12,含隧道 DNS 172.19.0.2)会并入 TUN 入站
   route_exclude_address(OS/auto_route 层,位于系统强制层之下),被排除的
   流量根本不进 sing-box → hijack-dns 与整条隧道被静默旁路,违反「系统层
   用户不可越」铁律。
   - Validate: direct 的 ip_cidr 拒绝 catch-all(/0)及与保留段 172.16.0.0/12
     重叠(写入闸)。
   - clientconfig 渲染层:新增 routing.SafeToExclude 守卫,只有安全的 direct
     ip_cidr 才并入 route_exclude_address(纵深防护,兜底写入闸之前的历史坏行)。
   - 测试 TestValidateDirectIPCIDRReservedGuard 钉死:拒 catch-all/隧道段重叠、
     放行 proxy catch-all 与不重叠 direct。

② [健壮性] 客户端保存失败静默回滚 + 抛未捕获异步异常 + 对话框无字段校验:
   _persist 失败会 rethrow(约定调用方 catch),但屏幕层所有回调
   (setMode/setBuiltin/addRule/removeRule/reorder/resetToDefault)均未 catch,
   规则闪现即消失、无提示,且 rethrow 变 zone 未处理异常。
   - 新增 _guardSave 守卫:await + 失败弹 SnackBar(AuthApiException 显服务端
     双语文案含校验错,其余回退通用「保存失败」),包裹全部变更类回调。
   - 添加规则对话框:_valueError 字段级预校验(ip_cidr 用 InternetAddress
     校验、geo 白名单仅 cn),非法即禁用保存并内联红字提示;语义级(保留段)
     仍由服务端权威判定经 SnackBar 呈现。
   - l10n 单源新增 routingSaveFailed / routingRuleValueInvalid(6 语),regen。

go test ./... 全绿;flutter analyze 无 error;flutter test 265 全过无 golden 回归;
codegen 幂等、原型 i18n 无漂移。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-08-01 00:32:52 +08:00
wangjia e157b16c11 fix(server): 走隧道/拒绝的域名规则也开 reverse_mapping
用户规则(可配置分流)里 action==proxy/reject 的域名规则,此前不触发
dns.reverse_mapping(只有 direct 域名规则触发)。而应用自行解析域名后按 IP
发起连接,路由层只剩 IP,无反向映射则 domain 规则永不命中——走隧道/拒绝的
域名规则会静默失效。

translateUserRules 把 hasDomainDirect 扩成 hasDomainRule:任意 action 的
域名类规则(domain/domain_suffix/domain_keyword)都置真、都开 reverse_mapping。
direct 专属的 ip_cidr→route_exclude_address(extraExclude)那条线不变。

这也是把私有服务分流(PANGOLIN_PRIVATE_SPLIT_DOMAINS)改用用户规则表达的
前置修复——否则一条"走隧道"用户规则替代 private-split 会连不上。

回归测试 TestBuildConfigProxyDomainEnablesReverseMapping:唯一一条走隧道/拒绝
域名规则(privateSplit 关、无 direct 域名规则)必须开 reverse_mapping。go test ./... 全绿。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-07-31 01:15:34 +08:00
wangjia ce485a1b62 fix(ui): SegSwitch 用 FittedBox(scaleDown) 防窄容器截断文字
添加规则弹层的动作段选(Direct/Tunnel/Reject)在窄弹层里被 icon+文字挤到 ellipsis 截断
成「Dire…/Tun…/Reje…」。改:段内容包 FittedBox(scaleDown)——放得下原样(宽段选/goldens
不变),放不下整体等比缩放而非截断;padding 16→12 留余量。flutter test 265/265 无 golden 回归。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-07-29 08:42:27 +08:00
wangjia 49d0c5d2df docs(claude): 记 iOS 真机装机(local_test.sh ipad,老忘)+ CI 发版(tag触发+私有依赖鉴权)+ 可配置分流功能
- 移动端段加真机装机:API_URL=... local_test.sh ipad <设备>(公司分发证书/签名核验/xcurl 装机);
  iOS libbox gitignore 产物从主仓拷免重建;新设备 -allowProvisioningDeviceRegistration。
- CI/CD 段更新:tag 触发发版(server-v*/client-v*/site-v* → compile→test→release→deploy pangolin1
  备份+migrate+回滚+healthz),取代过时的「仅校验无部署」;私有依赖 github.com/wangjia/codes→gitea
  鉴权(GOPRIVATE+insteadOf,冷缓存 runner 必踩);发版排障(gitea actions API + rbw gitea 读写key)。
- server/ 加可配置分流小节:routing_profiles/GET-POST me/routing/BuildClientConfig 翻译(层级/三模式/
  IP直连 route_exclude 在 tunIn/域名直连 reverse_mapping/nil 逐字节不变)/system_locked_domains。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-07-29 08:23:42 +08:00
17 changed files with 496 additions and 76 deletions
+36 -3
View File
@@ -66,11 +66,39 @@ server 已与具体 DB 解绑(裸 SQL + 薄方言层,`internal/db/dialect.go`):
`dialect.LockForUpdate()`;时间等一律 Go 端算好传 `?`,**不要**用 `UTC_TIMESTAMP()`/
`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
`.gitea/workflows/ci.yml`(runner label `nas`):shellcheck(bootstrap/single-node 脚本)、
OpenAPI 结构校验、UI 文案脱敏扫描、Flutter analyze+test。**仅校验,无部署动作。**
- 节点部署是手动/按需的(scp+ssh 跑 bootstrap / single-node),不走 CI 自动推送。
`.gitea/workflows/`(runner = 家里 NAS 上的 act_runner;job `runs-on: ubuntu-latest` 由它在
`catthehacker/ubuntu:act-latest` 容器承接):
- **`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 单源模型
@@ -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 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(经 REALITY 真实出站测 RTT);**坑很深,改前必读**
+2
View File
@@ -663,6 +663,8 @@ abstract class AppText {
String get routingRuleValueHint; // 目标输入框占位 / Target input placeholder
String get routingNoRules; // 暂无自定义规则 / No custom rules yet
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 routingReset; // 重置默认 / Reset defaults
String get routingResetConfirmTitle; // 重置为默认规则? / Reset to defaults?
+4
View File
@@ -571,6 +571,10 @@ class StringsEn extends AppText {
@override
String get routingAddRule => 'Add rule';
@override
String get routingSaveFailed => 'Save failed, please try again';
@override
String get routingRuleValueInvalid => 'Invalid format';
@override
String get routingImport => 'Import from text';
@override
String get routingReset => 'Reset defaults';
+4
View File
@@ -571,6 +571,10 @@ class StringsEs extends AppText {
@override
String get routingAddRule => 'Añadir regla';
@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';
@override
String get routingReset => 'Restablecer';
+4
View File
@@ -571,6 +571,10 @@ class StringsJa extends AppText {
@override
String get routingAddRule => 'ルールを追加';
@override
String get routingSaveFailed => '保存に失敗しました。もう一度お試しください';
@override
String get routingRuleValueInvalid => '形式が正しくありません';
@override
String get routingImport => 'テキストから読み込み';
@override
String get routingReset => 'デフォルトに戻す';
+4
View File
@@ -571,6 +571,10 @@ class StringsKo extends AppText {
@override
String get routingAddRule => '규칙 추가';
@override
String get routingSaveFailed => '저장에 실패했습니다. 다시 시도하세요';
@override
String get routingRuleValueInvalid => '형식이 올바르지 않습니다';
@override
String get routingImport => '텍스트에서 가져오기';
@override
String get routingReset => '기본값 재설정';
+4
View File
@@ -571,6 +571,10 @@ class StringsRu extends AppText {
@override
String get routingAddRule => 'Добавить правило';
@override
String get routingSaveFailed => 'Не удалось сохранить, попробуйте ещё раз';
@override
String get routingRuleValueInvalid => 'Неверный формат';
@override
String get routingImport => 'Импорт из текста';
@override
String get routingReset => 'Сбросить настройки';
+4
View File
@@ -571,6 +571,10 @@ class StringsZh extends AppText {
@override
String get routingAddRule => '添加规则';
@override
String get routingSaveFailed => '保存失败,请重试';
@override
String get routingRuleValueInvalid => '格式不正确';
@override
String get routingImport => '从文本导入';
@override
String get routingReset => '重置默认';
+63 -7
View File
@@ -13,12 +13,15 @@
// - 域名类规则(domain/domain_suffix/domain_keyword)命中 RoutingProfile.
// systemLockedDomains(FT-A 起 GET /v1/me/routing 下发的私有服务域名清单,
// PANGOLIN_PRIVATE_SPLIT_DOMAINS)——服务端渲染时恒强制走隧道,与用户规则动作冲突。
import 'dart:io' show InternetAddress, InternetAddressType;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../l10n/app_text.dart';
import '../models/routing_profile.dart';
import '../pangolin_theme.dart';
import '../services/auth_api.dart' show AuthApiException;
import '../state/app_providers.dart';
import '../state/routing_provider.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 {
const _RoutingBody({required this.t, required this.profile});
final AppText t;
@@ -86,7 +108,7 @@ class _RoutingBody extends ConsumerWidget {
(icon: PangolinIcons.arrowRight, label: t.routingModeDirect),
],
selectedIndex: selectedIdx,
onChanged: (i) => notifier.setMode(_kModeValues[i]),
onChanged: (i) => _guardSave(context, t, () => notifier.setMode(_kModeValues[i])),
),
const SizedBox(height: 8),
Text(t.routingModeNote, style: PangolinText.caption.copyWith(color: c.fg3, height: 1.5)),
@@ -101,7 +123,7 @@ class _RoutingBody extends ConsumerWidget {
title: t.routingCnDirect,
sub: 'GeoIP / GeoSite CN',
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,
),
_forcedRow(c, icon: PangolinIcons.home, title: t.routingLanDirect, sub: t.routingLanForced, pill: t.routingForcedPill),
@@ -135,14 +157,14 @@ class _RoutingBody extends ConsumerWidget {
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
buildDefaultDragHandles: false,
onReorder: (oldIndex, newIndex) => notifier.reorder(oldIndex, newIndex),
onReorder: (oldIndex, newIndex) => _guardSave(context, t, () => notifier.reorder(oldIndex, newIndex)),
children: [
for (var i = 0; i < profile.rules.length; i++)
_ruleRow(
context, c, t, i, profile.rules[i],
_conflictFor(profile.rules, i, profile.systemLockedDomains),
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;
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 {
final rule = await showDialog<RoutingRule>(context: context, builder: (_) => _AddRuleDialog(t: t));
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(
@@ -446,11 +470,38 @@ class _AddRuleDialogState extends State<_AddRuleDialog> {
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
Widget build(BuildContext context) {
final c = context.pangolin;
final t = widget.t;
final canSave = _value.text.trim().isNotEmpty;
final valueError = _valueError(t);
final canSave = _value.text.trim().isNotEmpty && valueError == null;
return AlertDialog(
backgroundColor: c.surface,
@@ -479,6 +530,11 @@ class _AddRuleDialogState extends State<_AddRuleDialog> {
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),
SegSwitch(
options: [
+13 -11
View File
@@ -49,30 +49,32 @@ class SegSwitch extends StatelessWidget {
child: AnimatedContainer(
duration: const Duration(milliseconds: 140),
curve: Curves.easeOut,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
// .segswitch-opt.is-active:surface 底 + shadow-sm;未选透明
color: active ? c.surface : Colors.transparent,
borderRadius: BorderRadius.circular(PangolinRadius.full),
boxShadow: active ? PangolinShadow.sm : null,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(o.icon, size: 16, color: active ? c.fg1 : c.fg2),
const SizedBox(width: 8),
Flexible(
child: Text(
// FittedBox(scaleDown):放得下则原样(宽段选不变),放不下则图标+文字整体
// 等比缩放而非把文字 ellipsis 截断(窄弹层里 Direct/Tunnel/Reject 曾被截成 Dire…)。
child: FittedBox(
fit: BoxFit.scaleDown,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(o.icon, size: 16, color: active ? c.fg1 : c.fg2),
const SizedBox(width: 8),
Text(
o.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: PangolinText.sm.copyWith(
color: active ? c.fg1 : c.fg2,
fontWeight: FontWeight.w600,
),
),
),
],
],
),
),
),
);
+16
View File
@@ -2241,6 +2241,22 @@
"ru": "Добавить правило",
"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": {
"zh": "从文本导入",
"en": "Import from text",
+17 -12
View File
@@ -43,11 +43,14 @@ type ClientConfigOpts struct {
// - extraExclude: type==ip_cidr && action==direct 的 value,供调用方并入
// TUN 入站的 route_exclude_address(auto_route 层直连才真正生效,
// 见 tunIn 构造处注释)。
// - hasDomainDirect: 是否存在 action==direct 的域名类规则(domain/
// - hasDomainRule: 是否存在**任意** action 的域名类规则(domain/
// domain_suffix/domain_keyword),供调用方决定是否开 dns.reverse_mapping。
// 不限 direct:走隧道/拒绝的域名规则同样需要反向映射——应用自行解析域名后
// 按 IP 发起连接,路由层只剩 IP,没有 reverse_mapping 则 domain 规则永不命中、
// 该规则(不论直连/隧道/拒绝)静默失效。
// - geoSets: 规则引用到的 geoip-<v>/geosite-<v> rule_set tag(去重),供
// 调用方在国内分流(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" {
return nil, nil, false, nil
}
@@ -71,12 +74,13 @@ func translateUserRules(p *routing.Profile) (rules []any, extraExclude []string,
switch r.Type {
case "domain", "domain_suffix", "domain_keyword":
rules = append(rules, map[string]any{r.Type: []string{r.Value}, "outbound": outbound})
if outbound == "direct" {
hasDomainDirect = true
}
// 任意 action 的域名规则都要 reverse_mapping(见返回值注释),不止 direct。
hasDomainRule = true
case "ip_cidr":
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)
}
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
@@ -243,10 +247,10 @@ func BuildClientConfig(node *nodes.NodeRow, dpUUID, deriveKey string, opts Clien
// 直接返回全零值,以下每一步都随之短路,保证 nil-profile 渲染逐字节不变。
var userRules []any
var extraExclude []string
var hasDomainDirect bool
var hasDomainRule bool
var geoSets []string
if opts.Profile != nil {
userRules, extraExclude, hasDomainDirect, geoSets = translateUserRules(opts.Profile)
userRules, extraExclude, hasDomainRule, geoSets = translateUserRules(opts.Profile)
if opts.RulesBaseURL == "" && len(geoSets) > 0 {
// 没有 base 就没法渲染 remote rule_set 的下载 URL,引用它的用户规则
// 会指向未定义的 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",
})
}
if privateSplit || hasDomainDirect {
if privateSplit || hasDomainRule {
// 回映射:记住"哪个 IP 是哪个域名解析出来的",给后续按 IP 发起的连接补回
// 域名元数据——路由层的 domain 规则(私有域名→隧道 / 用户域名直连)靠它
// 才会命中。hasDomainDirect:用户规则含 action==direct 的域名类规则时同样需要。
// 域名元数据——路由层的 domain 规则(私有域名→隧道 / 用户域名规则)靠它
// 才会命中。hasDomainRule:用户规则含**任意** action 的域名类规则(直连/
// 走隧道/拒绝)时都需要——否则该域名规则永不命中、静默失效。
dns["reverse_mapping"] = true
}
// 国内分流的 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) {
p := routing.Default()
p.Mode = "global"
+45 -1
View File
@@ -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 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
// 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 `[]`
@@ -99,8 +133,18 @@ func (p *Profile) Validate() []FieldError {
}
switch r.Type {
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"})
} 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":
if !geoWhitelist[strings.ToLower(r.Value)] {
+31
View File
@@ -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) {
p := Default()
for i := 0; i < 201; i++ {
+164 -39
View File
@@ -327,12 +327,12 @@ header .header-meta{color:var(--fg-soft)}
<header>
<div class="wrap">
<h1>feature+windows — 项目 TODO</h1>
<div class="header-meta">生成于 2026-07-23 · 真相源 todo/todo.json</div>
<div class="header-meta">生成于 2026-08-01 · 真相源 todo/todo.json</div>
<div class="stats">
<div class="stat-pill"><strong>22</strong>全部</div>
<div class="stat-pill"><strong>9</strong>待开始</div>
<div class="stat-pill"><strong>1</strong>开发中</div>
<div class="stat-pill"><strong>4</strong>待验收</div>
<div class="stat-pill"><strong>26</strong>全部</div>
<div class="stat-pill"><strong>13</strong>待开始</div>
<div class="stat-pill"><strong>0</strong>开发中</div>
<div class="stat-pill"><strong>5</strong>待验收</div>
<div class="stat-pill"><strong>8</strong>已验收</div>
</div>
@@ -376,7 +376,7 @@ header .header-meta{color:var(--fg-soft)}
<div class="section-block" id="section-open">
<div class="section-title st-open" data-toggle="open">
📋 待开始 <span class="s-count">9</span>
📋 待开始 <span class="s-count">13</span>
<span class="s-arrow">▴ 收起</span>
</div>
<div class="section-list-wrap " id="list-wrap-open">
@@ -630,6 +630,130 @@ header .header-meta{color:var(--fg-soft)}
</div>
</li>
<li class="todo-card s-open"
data-id="24"
data-level="mid"
data-status="open"
data-tier=""
data-tags="">
<div class="card-header">
<span class="item-id">#24</span>
<span class="item-title">客户端长时间运行后重开显示未连接(Offline)但隧道实际仍在连——UI连接态与真实VPN态脱钩。iOS实测:系统VPN设置里『已连接』(Pangolin加速/穿山甲激活),但app连接页显示Offline/Tap to connect。排查方向:app冷启/回前台时未从NETunnelProviderManager/系统VPN真实态同步隧道状态,statusStream初始态错判为off。四端可能共性(Dart侧状态流)。</span>
<div class="card-badges">
<span class="tag status-badge s-open">待开始</span>
<span class="tag t-high">重要</span>
</div>
</div>
<div class="card-footer">
<div class="tag-row"></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-07-26</span>
</div>
</div>
</li>
<li class="todo-card s-open"
data-id="25"
data-level="mid"
data-status="open"
data-tier=""
data-tags="">
<div class="card-header">
<span class="item-id">#25</span>
<span class="item-title">私有服务在家直连(不绕 Ali frps):nas/git/win/brain.51yanmei.com。方案=局域网分离解析 DNS(dnsmasq 或 AdGuard Home 挂 NAS,per-host 覆盖到 192.168.3.x + DHCP option6 下发)解决 VPN 关闭情形;VPN 开启情形走 B2 两旋钮(保留极小 dns-system 服务端清单,路由决策下沉用户规则)。需在家局域网环境操作。前置修复 reverse_mapping 已完成(commit e157b16)</span>
<div class="card-badges">
<span class="tag status-badge s-open">待开始</span>
<span class="tag t-high">重要</span>
</div>
</div>
<div class="card-footer">
<div class="tag-row"></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-07-31</span>
</div>
</div>
</li>
<li class="todo-card s-open"
data-id="26"
data-level="mid"
data-status="open"
data-tier=""
data-tags="">
<div class="card-header">
<span class="item-id">#26</span>
<span class="item-title">切 MySQL 前必补 Promo 限购并发防线:pay/webhook.go settle 对 pro_month_promo 靠应用层 HasPaidPurchaseExcludingTx 复查,MySQL READ COMMITTED 下并发两笔独立订单会双发一个月 Pro。当前 SQLite _txlock 串行化 + 部分唯一索引 ux_pay_promo_paid 双兜底,不触发;切 MySQL 需改 SELECT..FOR UPDATE 锁 user 维度或全表唯一索引</span>
<div class="card-badges">
<span class="tag status-badge s-open">待开始</span>
<span class="tag t-high">重要</span>
</div>
</div>
<div class="card-footer">
<div class="tag-row"></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-08-01</span>
</div>
</div>
</li>
<li class="todo-card s-open"
data-id="27"
data-level="mid"
data-status="open"
data-tier=""
data-tags="">
<div class="card-header">
<span class="item-id">#27</span>
<span class="item-title">分支审核 Minor 硬化(routing/pay):①TG webhook secret 改 subtle.ConstantTimeCompare(reward/handler.go:113 现用 !=);②routing 保存成功后回填服务端 Normalize 结果(现保留本地乐观值,重复/带空格规则短暂 UI 漂移);③nodes.go splitCN 冗余赋值清理</span>
<div class="card-badges">
<span class="tag status-badge s-open">待开始</span>
<span class="tag t-high">重要</span>
</div>
</div>
<div class="card-footer">
<div class="tag-row"></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-08-01</span>
</div>
</div>
</li>
<li class="todo-card s-open"
data-id="3"
data-level="low"
@@ -665,48 +789,18 @@ header .header-meta{color:var(--fg-soft)}
</div>
<div class="section-block" id="section-doing">
<div class="section-title st-doing" data-toggle="doing">
🔨 开发中 <span class="s-count">1</span>
🔨 开发中 <span class="s-count">0</span>
<span class="s-arrow">▴ 收起</span>
</div>
<div class="section-list-wrap " id="list-wrap-doing">
<ul class="todo-list" id="list-doing">
<li class="todo-card s-doing"
data-id="23"
data-level="mid"
data-status="doing"
data-tier=""
data-tags="">
<div class="card-header">
<span class="item-id">#23</span>
<span class="item-title">私有目的地 ACL(节点侧):只有白名单 dp_uuid 能经 pangolin 出口访问 brain/nas/git/win.51yanmei.com。节点本地 acl.json + agent 渲染放行/拒绝规则对,fail-closedSIGHUP 热生效。设计 docs/private-dest-acl-design.html,计划 docs/superpowers/plans/2026-07-23-private-dest-acl.md</span>
<div class="card-badges">
<span class="tag status-badge s-doing">开发中</span>
<span class="tag t-high">重要</span>
</div>
</div>
<div class="card-footer">
<div class="tag-row"></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-07-23</span>
</div>
</div>
</li>
<p class="empty-tip">暂无条目</p>
</ul>
</div>
</div>
<div class="section-block" id="section-done">
<div class="section-title st-done" data-toggle="done">
🔍 待验收 <span class="s-count">4</span>
🔍 待验收 <span class="s-count">5</span>
<span class="s-arrow">▴ 收起</span>
</div>
<div class="section-list-wrap " id="list-wrap-done">
@@ -837,6 +931,37 @@ header .header-meta{color:var(--fg-soft)}
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-07-16</span>
</div>
</div>
</li>
<li class="todo-card s-done"
data-id="23"
data-level="mid"
data-status="done"
data-tier=""
data-tags="">
<div class="card-header">
<span class="item-id">#23</span>
<span class="item-title">私有目的地 ACL(节点侧):只有白名单 dp_uuid 能经 pangolin 出口访问 brain/nas/git/win.51yanmei.com。节点本地 acl.json + agent 渲染放行/拒绝规则对,fail-closedSIGHUP 热生效。设计 docs/private-dest-acl-design.html,计划 docs/superpowers/plans/2026-07-23-private-dest-acl.md</span>
<div class="card-badges">
<span class="tag status-badge s-done">待验收</span>
<span class="tag t-high">重要</span>
<button class="reject-btn" data-id="23" data-title="私有目的地 ACL(节点侧):只有白名单 dp_uuid 能经 pangolin 出口访问 brain/nas/git/win.51yanmei.com。节点本地 acl.json + agent 渲染放行/拒绝规则对,fail-closedSIGHUP 热生效。设计 docs/private-dest-acl-design.html,计划 docs/superpowers/plans/2026-07-23-private-dest-acl.md">拒绝验收</button>
</div>
</div>
<div class="card-footer">
<div class="tag-row"></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-07-23</span>
</div>
</div>
</li>
+59 -3
View File
@@ -1,9 +1,9 @@
{
"meta": {
"title": "feature+windows — 项目 TODO",
"updated_at": "2026-07-22T16:59:57.735Z"
"updated_at": "2026-07-31T16:34:06.427Z"
},
"seq": 23,
"seq": 27,
"items": [
{
"id": 1,
@@ -368,11 +368,67 @@
"tier": null,
"tags": [],
"owner": "agent",
"status": "doing",
"status": "done",
"created_at": "2026-07-22T16:59:41.945Z",
"done": false,
"completed_at": null,
"version": null
},
{
"id": 24,
"title": "客户端长时间运行后重开显示未连接(Offline)但隧道实际仍在连——UI连接态与真实VPN态脱钩。iOS实测:系统VPN设置里『已连接』(Pangolin加速/穿山甲激活),但app连接页显示Offline/Tap to connect。排查方向:app冷启/回前台时未从NETunnelProviderManager/系统VPN真实态同步隧道状态,statusStream初始态错判为off。四端可能共性(Dart侧状态流)。",
"desc": null,
"level": "mid",
"tier": null,
"tags": [],
"owner": "agent",
"status": "open",
"created_at": "2026-07-26T07:33:36.766Z",
"done": false,
"completed_at": null,
"version": null
},
{
"id": 25,
"title": "私有服务在家直连(不绕 Ali frps):nas/git/win/brain.51yanmei.com。方案=局域网分离解析 DNS(dnsmasq 或 AdGuard Home 挂 NAS,per-host 覆盖到 192.168.3.x + DHCP option6 下发)解决 VPN 关闭情形;VPN 开启情形走 B2 两旋钮(保留极小 dns-system 服务端清单,路由决策下沉用户规则)。需在家局域网环境操作。前置修复 reverse_mapping 已完成(commit e157b16)",
"desc": null,
"level": "mid",
"tier": null,
"tags": [],
"owner": "agent",
"status": "open",
"created_at": "2026-07-31T02:10:58.408Z",
"done": false,
"completed_at": null,
"version": null
},
{
"id": 26,
"title": "切 MySQL 前必补 Promo 限购并发防线:pay/webhook.go settle 对 pro_month_promo 靠应用层 HasPaidPurchaseExcludingTx 复查,MySQL READ COMMITTED 下并发两笔独立订单会双发一个月 Pro。当前 SQLite _txlock 串行化 + 部分唯一索引 ux_pay_promo_paid 双兜底,不触发;切 MySQL 需改 SELECT..FOR UPDATE 锁 user 维度或全表唯一索引",
"desc": null,
"level": "mid",
"tier": null,
"tags": [],
"owner": "agent",
"status": "open",
"created_at": "2026-07-31T16:34:06.353Z",
"done": false,
"completed_at": null,
"version": null
},
{
"id": 27,
"title": "分支审核 Minor 硬化(routing/pay):①TG webhook secret 改 subtle.ConstantTimeCompare(reward/handler.go:113 现用 !=);②routing 保存成功后回填服务端 Normalize 结果(现保留本地乐观值,重复/带空格规则短暂 UI 漂移);③nodes.go splitCN 冗余赋值清理",
"desc": null,
"level": "mid",
"tier": null,
"tags": [],
"owner": "agent",
"status": "open",
"created_at": "2026-07-31T16:34:06.426Z",
"done": false,
"completed_at": null,
"version": null
}
]
}