Compare commits

...

21 Commits

Author SHA1 Message Date
wangjia def3bb34b8 fix(server): 控制面 8080 收口——默认绑 loopback + 部署时幂等纠偏 ADDR/ufw
Deploy Server / deploy-server (push) Successful in 4m33s
Deploy Site / deploy-site (push) Successful in 2m19s
Deploy Client / build-windows (push) Successful in 1m39s
Deploy Client / build-android (push) Successful in 3m49s
Deploy Client / build-macos (push) Failing after 1m47s
Deploy Client / build-ios (push) Failing after 16m18s
Deploy Client / release-deploy (push) Successful in 1m39s
现网 server.env 漂移成 ADDR=:8080(全网卡),ufw 又放行 8080 → 控制面 API 明文
裸奔公网(http://<IP>:8080),绕过 cloudflared/CF 的 TLS 层。两处硬化:
- main.go:ADDR 未设时默认由 :8080 改 127.0.0.1:8080(防御纵深;跨主机监听须显式设 ADDR)
- deploy-server.sh:部署重启前幂等把 ADDR=:8080 纠回 127.0.0.1:8080(备份原文件)+
  撤 ufw allow 8080/tcp。收口随 server-v* 发版自动落地,不再手改线上。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-09 10:02:10 +08:00
wangjia bb031a04c1 fix(client/web): 语言跟随系统 + SSO 落地补 basePath + 移除账户页续费按钮
- 语言(#1):LocaleNotifier 首启无用户选择时读设备 locale(zh/ja/ko/ru/es 命中
  对应语种,余回退英文),原来恒为固定默认 en、从不看系统语言。用户显式切换仍持久
  化优先。
- 用户中心 SSO(#3):usercenter 运行在 basePath=/user,但 /sso 落地页用原生
  window.location.replace('/') 跳转(Next 不补 basePath)→ 落到站点根=官网主页,
  且换票已建立的会话看起来像未登录。改为 withBase() 统一补 /user 前缀,兑票成功
  直达 /user/ 且保持登录态。(服务端 issue/exchange 流程实测均 200,非后端问题)
- 账户页(#4):移除"续费/升级"按钮(免费卡片 + PRO 横幅两处)及其未用组件;购买入口
  仍由"购买套餐"行保留,不影响下单路径。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-09 09:42:25 +08:00
wangjia e7e59a786d fix(client): 默认 UI 品牌文案统一英文 Pangolin(窗口标题/托盘/安装包名/macOS 菜单栏)
默认 UI 语言是英文,但窗口标题(windowManager.setTitle)、MaterialApp title、
托盘 tooltip 与右键菜单、Windows 安装包显示名、macOS CFBundleName 硬编码中文,
中英混排。统一改英文品牌名;iOS 桌面图标名(CFBundleDisplayName=穿山甲)按
市场定位保留。托盘菜单文案后续可接 l10n(现契约无 tray 键)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-09 01:43:39 +08:00
wangjia b59101abf1 chore(scripts): local_test 默认 API 改指生产域名(8080 公网收口后旧默认失效)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-09 00:54:03 +08:00
wangjia 0ddcc5e935 fix(client/macos): CI 重签 sysext entitlements 补 network.client/server + 闸断言
Deploy Client / build-windows (push) Successful in 1m43s
Deploy Client / build-android (push) Successful in 5m13s
Deploy Client / build-macos (push) Successful in 6m53s
Deploy Client / build-ios (push) Failing after 12m28s
Deploy Client / release-deploy (push) Successful in 2m6s
v1.1.2 事故第二弹:inside-out 重签的 sysext heredoc 漏了
com.apple.security.network.client/server —— 沙箱扩展无权对外建连,
隧道起了也连不上节点(本地 Xcode 直签用仓库 PacketTunnel.entitlements
带这两键,故 local_test 流程正常,唯 CI 包不通)。

- compile-macos.sh / local_test.sh cmd_sign:sysext heredoc 补两键(与仓库源文件对齐)
- 公证前一致性闸扩展:断言 sysext 最终签名 network.client/server=true,重签丢键即 fail
- 已本地验证:对 v1.1.2 发布包用新 entitlements 重签,读回签名两键在位

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-09 00:49:05 +08:00
wangjia 0c6957fcb5 chore(todo): #28 App Group 修复已发版 client-v1.1.2,标 done 待验收
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-09 00:07:14 +08:00
wangjia 6a4da3e164 chore(todo): 记 #28 App Group 事故复盘 + #29 chenxin 凭据过期 + #30 四语支付文案缺口
Deploy Client / build-windows (push) Successful in 1m43s
Deploy Client / build-android (push) Successful in 6m57s
Deploy Client / build-macos (push) Successful in 8m43s
Deploy Client / build-ios (push) Successful in 4m53s
Deploy Client / release-deploy (push) Successful in 2m6s
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-08 23:41:36 +08:00
wangjia 77302cfa7a fix(client/macos): CI 重签 App Group 修回 macOS 原生格式 + 公证前一致性闸
compile-macos.sh 的 sysext entitlements 曾硬编码 iOS 风格 group. 前缀,且主 app
entitlements 缺 application-groups —— 与 NEMachServiceName 前缀对不上,
nesessionmanager 报 Code=6,sysextd 当场卸载新扩展,线上包永远建不出 VPN 配置
(本地 Xcode 直签流程正常,故长期未察觉;详见 todo #28)。

- compile-macos.sh: 两处 entitlements 改用 ${APP_GROUP};公证前加一致性闸
  (读最终签名核对 app/sysext App Group 与 NEMachServiceName 前缀,不一致即 fail)
- local_test.sh: 同款修复 + verify_app_group 闸 + cmd_bump_build 自动递增
  sysext 构建号 + macos 一条龙子命令(bump→build→闸→公证→装→跑)
- pbxproj: CURRENT_PROJECT_VERSION 53→55(本地已构建两次,保持单调)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEVUXAbFT6bF1Qw27RHWoD
2026-08-08 23:41:36 +08:00
wangjia 79830cb43f fix(ci): client release-deploy 加 if 守卫,mac/ios 抖失败不阻发布
Deploy Client / build-windows (push) Successful in 1m42s
Deploy Client / build-android (push) Successful in 5m8s
Deploy Client / build-macos (push) Successful in 8m3s
Deploy Client / build-ios (push) Successful in 4m59s
Deploy Client / release-deploy (push) Successful in 2m2s
run 239:android/windows/macos 全绿、ios 在 Checkout 阶段 git fetch
git.51yanmei.com 走 frps 超时挂掉(非 iOS 构建问题;run 238 同代码 fetch 碰巧
成功)。因上一版把 build-ios 加进 release-deploy 的 needs,而 gitea 里
continue-on-error 的 job 失败**仍会 skip 下游 needs** → release-deploy 被跳过。

修:needs 保留四平台(等全部完成、不抢跑 → 收齐已上传产物),但加
`if: always() && needs.build-android.result == 'success'` —— 只要 android
(稳定 floor)成功即发布,mac/ios/windows 的瞬断失败不再 skip release-deploy,
download-artifact 收当时存在的产物照发。

yaml 校验通过。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-08-03 00:17:53 +08:00
wangjia fdc13ea06c fix(ci): client release-deploy 挪到 nas runner + 等全平台构建
Deploy Client / build-windows (push) Successful in 1m41s
Deploy Client / build-android (push) Successful in 4m40s
Deploy Client / build-macos (push) Successful in 7m30s
Deploy Client / build-ios (push) Failing after 11m51s
Deploy Client / release-deploy (push) Has been skipped
client-v1.1.1 首跑:4 平台 build 全绿,但 release-deploy 卡在「Release →
Forgejo」curl exit 28(超时,3m3s=release_ensure 60s×3 重试耗尽)。根因:
release-deploy `runs-on: mac`(mac-pangolin-2)访问 git.51yanmei.com 走 frps
隧道 → 抖断。deploy-server/deploy-site 同类 Forgejo release 步跑在
ubuntu-latest(nas act_runner,与 gitea 同机/同网)稳定通过(server 仅 13s)。

- runs-on: mac → ubuntu-latest:release-deploy 全为网络/SSH 步骤(下载产物/
  传 Forgejo/SSH pangolin1/通知),无 mac 专属需求,挪到 nas runner 走本地。
- needs: [build-android] → [build-android, build-windows, build-macos, build-ios]:
  等全部平台 build 完再发布,修旧竞态(只等 android → macos/ios 产物没传就发布
  漏平台)。macos/ios 保留 continue-on-error,失败不阻断已成功平台。
- 更新过时注释(原称 Apple secret 未配 / needs 仅 android+windows)。

yaml 校验通过。build 四平台本身已在 run 639 全绿,本次只修发布环节。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-08-01 23:47:29 +08:00
wangjia f0f845c6e5 fix(ci): site 流水线加 npm 国内镜像(GFW)+ npm ci 重试
Deploy Site / deploy-site (push) Successful in 2m6s
Deploy Client / build-windows (push) Successful in 1m43s
Deploy Client / build-android (push) Successful in 20m37s
Deploy Client / build-macos (push) Successful in 8m19s
Deploy Client / build-ios (push) Successful in 5m29s
Deploy Client / release-deploy (push) Failing after 24m14s
site pipeline(deploy-site.yml:Astro 官网 + Next.js 用户中心 + npx wrangler)
在墙内 nas runner 上 npm ci / npx wrangler@4 直连 registry.npmjs.org → 慢/抖断。
_env.sh 早有 Go(goproxy.cn)/Flutter(flutter-io.cn)镜像,唯独漏了 npm,且 3 个
site 脚本根本没 source _env.sh。上次「修外网发版 GFW 坑」只覆盖 android(gradle)/
windows(maven),site 这块遗漏。

- _env.sh:加 NPM_CONFIG_REGISTRY=registry.npmmirror.com(可 env 覆盖)+ npm_ci_retry
  助手(照 flutter_pub_get_retry,5 次重试)。
- compile-site.sh / compile-usercenter.sh:source _env.sh,npm ci → npm_ci_retry。
- deploy-site.sh:source _env.sh,让 npx wrangler@4 也走镜像拉包。

本地实跑 compile-site.sh:镜像生效、Astro 构建成功、dist/ 产物齐全(index.html 48K
+ 多语言目录)。shellcheck -x 全 clean。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-08-01 20:32:37 +08:00
wangjia b255fdfb4e chore(ci): CI 校验迁本地(ci/check-local.sh),删 pipeline ci.yml
ci.yml 跑在自建 gitea 的 mac-pangolin-2 runner 上,该 runner 不稳:重 job
(go/flutter/golden/integration/e2e)频繁整体超时/失败(run 233、236 复现:所有
runs-on=mac 的 job 全挂、runs-on=ubuntu 的 nas 快扫描全过,证明是 mac runner
掉线而非代码)。既然开发就在 mac 上、原生工具齐全,把校验迁回本地。

- 新增 ci/check-local.sh:与 ci.yml 各 job 一一对应,dev mac 原生跑(仅 golden
  因 Linux 权威基线走 docker)。分档:默认=静态闸+go build/test+flutter analyze/test
  (各带覆盖率闸 Go30%/Flutter28%);--full 加 golden/go-integration/e2e;
  --only <名> 单跑;--list 列项。缺工具标 SKIP 不算失败。shellcheck-clean。
- 删 .gitea/workflows/ci.yml(部署流水线 deploy-server/client/site 保留,发版
  仍过 go test)。
- .githooks/pre-commit:秒级快闸不变,指引改指 ci/check-local.sh(原指 CI)。
- CLAUDE.md CI/CD 段重写 + ds-flow 闸表「CI」触发点改「check-local」。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-08-01 10:20:18 +08:00
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
wangjia cd0ba919d1 fix(ci): deploy-server 编译前给私有依赖 github.com/wangjia/codes 配 gitea 鉴权
Deploy Server / deploy-server (push) Successful in 4m17s
冷缓存 runner 上 go build 拉私有 codes 依赖时,GOPROXY=goproxy.cn 对私有仓 404 →
回退 direct git 到 github.com → 无凭证失败(server-v1.1.0 首发在此挂,44s Compile 步红)。
加一步:GOPRIVATE + git insteadOf 把 github.com/wangjia/codes 重写到自建 gitea 并注入
FORGEJO_TOKEN(已验证 oauth2:<token> basic-auth 可 ls-remote 到 pin 的 commit)。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-07-29 07:50:35 +08:00
wangjia a307c6ca2c fix(test): codes-lib 迁移往返测试改用 m.Migrate(21) 显式定位版本
Deploy Server / deploy-server (push) Failing after 41s
TestCodesLibMigrateRoundTrip 硬编码 6 次 Steps(-1),假设 000027 是迁移栈顶;本功能
加了 000028_routing_profiles 后 6 步落在版本 22、跳过了 000022 down,导致断言失败。
根因不是迁移 SQL(000022 up/down 正确、codes-lib 表无 FK——推翻了 FK 假设),而是
测试的脆弱步数计数被新增迁移打乱。改用 m.Migrate(21) 显式降到 000022 down 之后的
边界,不受栈顶新增迁移影响。全仓 go test ./... 恢复 0 FAIL。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A79VtQA1BwTuQN1ThpvYpo
2026-07-29 07:08:56 +08:00
wangjia 2930d76cf3 feat(routing): 域名级系统锁冲突提示 + 重置默认按钮 + 客户端 follow-up 清理
承接 FT-A(GET /v1/me/routing 含只读 system_locked_domains)。

- RoutingProfile 加只读 systemLockedDomains(fromJson 读/toJson 不输出);
  routing_screen 冲突检测扩展到域名类规则(domain/domain_suffix/domain_keyword
  命中锁定域名 → systemLocked),ip_cidr 私网启发式保留。
- RoutingProfile.defaults() + RoutingProfileNotifier.resetToDefault()(复用
  _persist:乐观更新/失败回滚/存成功后自动重连,保留只读 systemLockedDomains
  不丢)+ routing_screen 加「重置默认」按钮与二次确认弹层(新增 3 个 l10n 键)。
- RoutingRule.copyWith 用哨兵支持 note 显式清空为 null;RoutingRule/Builtin/
  RoutingProfile 加值相等 operator==/hashCode。
- T8 smartRouteSub 清理:grep 全仓发现 design/prototype/i18n/alias.json →
  gen_proto_i18n.mjs(CI 漂移闸)仍有活引用,按计划口径不删,详见
  .superpowers/sdd/task-FTB-report.md。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-29 06:57:58 +08:00
wangjia 3159dd75c1 refactor(routing): 暴露 system_locked_domains + 服务端 follow-up 清理(FK/Validate/dedup/exclude单源/共用Store/Builtin保留) 2026-07-29 06:38:52 +08:00
51 changed files with 1782 additions and 533 deletions
-271
View File
@@ -1,271 +0,0 @@
name: ci-pangolin
# 触发条件:deploy/ 或 design/ 或 client/ 或 server/ 或 ci/ 变更时,以及所有向 main 的 PR
on:
push:
branches: [main]
paths:
- 'deploy/**'
- 'design/**'
- 'client/**'
- 'server/**'
- 'ci/**'
- 'scripts/ci/**'
- '.gitea/workflows/ci.yml'
pull_request:
branches: [main]
workflow_dispatch:
# runner 分配:
# · runs-on: ubuntu-latest —— 在 catthehacker 容器里跑,仅用于纯 bash 扫描
# (redline/cleartext/portable-sql);容器内**不能**嵌套 `docker run`(DinD 挂载
# 失败,$PWD 在宿主不存在),故套 docker 的 job 不能用它。
# · runs-on: mac —— host 模式(mac-pangolin-2 直接在宿主跑),`docker run` 是宿主
# 真 docker(非嵌套),可正常拉/跑 node/golang/flutter/python/shellcheck 镜像。
# golden 保留 ghcr.io/cirruslabs/flutter Linux 容器 → 与入库基线渲染一致。
jobs:
# ── Job 1: Lint (shellcheck) ─────────────────────────────────────────────
lint:
name: Lint — shellcheck
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: shellcheck 节点脚本(bootstrap + single-node)
# 注:koalaman/shellcheck 镜像 ENTRYPOINT 已是 shellcheck,命令里别再写一遍
# (否则变 `shellcheck shellcheck …`,把 "shellcheck" 当文件→openBinaryFile 报错)。
run: |
docker run --rm \
-v "$PWD/deploy:/mnt/deploy:ro" \
koalaman/shellcheck:stable \
-S warning \
/mnt/deploy/bootstrap/init.sh \
/mnt/deploy/bootstrap/monitor/pangolin-monitor.sh \
/mnt/deploy/bootstrap/monitor/deadman-watch.sh \
/mnt/deploy/single-node/deploy.sh
- name: shellcheck CI 脚本(scripts/ci)
run: |
docker run --rm \
-v "$PWD/scripts/ci:/mnt/scripts/ci:ro" \
koalaman/shellcheck:stable \
-S warning \
/mnt/scripts/ci/_env.sh \
/mnt/scripts/ci/lib-forgejo.sh \
/mnt/scripts/ci/notify.sh \
/mnt/scripts/ci/lib-ssh.sh \
/mnt/scripts/ci/compile-site.sh \
/mnt/scripts/ci/deploy-site.sh \
/mnt/scripts/ci/compile-backend.sh \
/mnt/scripts/ci/release-server.sh \
/mnt/scripts/ci/deploy-server.sh \
/mnt/scripts/ci/test.sh \
/mnt/scripts/ci/backup-db.sh \
/mnt/scripts/ci/compile-android.sh \
/mnt/scripts/ci/compile-windows.sh \
/mnt/scripts/ci/compile-macos.sh \
/mnt/scripts/ci/compile-ios.sh \
/mnt/scripts/ci/release-client.sh \
/mnt/scripts/ci/deploy-client.sh
- name: shellcheck CI 脚本(ci/)
run: |
docker run --rm \
-v "$PWD/ci:/mnt/ci:ro" \
koalaman/shellcheck:stable \
-S warning \
/mnt/ci/scan-cleartext.sh
# ── Job 2: OpenAPI Sync Check ────────────────────────────────────────────
openapi-check:
name: OpenAPI Sync Check
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
# openapi-spec-validator 是纯 Python、无外部依赖,校验 OAS 3.0 结构合法性。
- name: lint design/server/openapi.yaml
run: |
docker run --rm \
-v "$PWD/design/server:/spec:ro" \
python:3.12-alpine \
sh -c "pip install openapi-spec-validator --quiet && \
python -m openapi_spec_validator /spec/openapi.yaml"
# ── Job 3: Redline Word Scan (脱敏) ──────────────────────────────────────
redline-scan:
name: Redline Scan — 脱敏 (UI 文案)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: scan UI text resources for prohibited words
run: bash ci/scan-redline.sh
# ── Job 3b: Cleartext Scan (Android 禁全局明文,#25 控制面已 https) ──────
cleartext-scan:
name: Cleartext Scan — Android 禁明文
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: scan Android manifest for global cleartext
run: bash ci/scan-cleartext.sh
# ── Job 4: Flutter 客户端(分析 + 单测/组件测试)────────────────────────
flutter-client:
name: Flutter — analyze + test
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: flutter analyze + test + coverage
run: |
mkdir -p "$HOME/.cache/pangolin-ci/pubcache"
docker run --rm \
-v "$PWD/client:/app" -w /app \
-v "$HOME/.cache/pangolin-ci/pubcache:/root/.pub-cache" \
ghcr.io/cirruslabs/flutter:stable \
bash -c "flutter pub get && flutter analyze --no-fatal-infos && flutter test --coverage test/unit test/widget test/contract"
# 覆盖率闸(host 侧解析 lcov):防断崖,低于阈值即失败。
COV=$(awk -F: '/^LF:/{f+=$2} /^LH:/{h+=$2} END{if(f>0)printf "%.1f",h/f*100}' client/coverage/lcov.info)
echo "flutter 行覆盖 ${COV}%"
awk -v c="$COV" 'BEGIN{ if(c+0 < 28){ print "❌ flutter 覆盖率 "c"% < 阈值 28%"; exit 1 } print "✅ flutter 覆盖率 "c"% ≥ 28%" }'
# ── Job 5: Portable SQL Scan (支柱 3:双库可移植)─────────────────────────
# server Go 运行时查询不得含 MySQL 专属构造(同一份 SQL 要跑 mysql 与 sqlite)。
# 规则与豁免见 ci/scan-portable-sql.sh 头注 + docs/dev-conventions.html 支柱 3。
portable-sql-scan:
name: Portable SQL — 可移植性 (mysql/sqlite)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: scan server Go runtime SQL for MySQL-specific constructs
run: bash ci/scan-portable-sql.sh
# ── Job 6: Codegen Drift (支柱 2:token 单源不漂移)──────────────────────
# 重新生成 client/lib/pangolin_tokens.gen.dart,与已提交版本不一致即失败
# (改了 design/colors_and_type.css 没重生成,或手改了生成物)。
codegen-drift:
name: Codegen Drift — token 生成物未漂移
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: regenerate flutter tokens & assert no drift
run: |
docker run --rm \
-v "$PWD:/repo" -w /repo \
node:20 \
bash ci/check-codegen-drift.sh
ds-flow:
name: DS-flow — 原型/跨端同源/代码色单源闸
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: 原型校验(check-ds)
run: docker run --rm -v "$PWD:/repo" -w /repo node:20 node design/prototype/tools/check-ds.mjs
- name: 跨端同源(check-l1-sync)
run: docker run --rm -v "$PWD:/repo" -w /repo node:20 node tools/check-l1-sync.mjs
- name: Flutter 颜色单源(check_ds_code --strict)
run: docker run --rm -v "$PWD/client:/app" -w /app node:20 node tool/check_ds_code.mjs --strict
# ── Job 7: Go 服务端(build + test:含契约快照 + sqlite 真库,跳过 integration)──
# 此前 server 测试未进 CI;契约快照(支柱 2)等需在此守门。integration 测试走
# -tags integration(需 docker 起 mysql/redis),见 go-integration job。
go-server:
name: Go — build + test
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: go build + vet + test + coverage
run: |
# 宿主持久缓存(host-mode runner):省掉每次 `go: downloading` 全量拉依赖。
mkdir -p "$HOME/.cache/pangolin-ci/gomod" "$HOME/.cache/pangolin-ci/gobuild"
docker run --rm \
-v "$PWD/server:/app" -w /app \
-v "$HOME/.cache/pangolin-ci/gomod:/go/pkg/mod" \
-v "$HOME/.cache/pangolin-ci/gobuild:/root/.cache/go-build" \
golang:1.25 \
bash -c "go build ./... && go vet ./... && go test -coverprofile=cover.out ./... && go tool cover -func=cover.out > coverage.txt"
tail -1 server/coverage.txt
# 覆盖率闸(host 侧解析,避开容器引号转义):防断崖,低于阈值即失败。
COV=$(grep '^total:' server/coverage.txt | grep -oE '[0-9]+\.[0-9]+')
awk -v c="$COV" 'BEGIN{ if(c+0 < 30){ print "❌ Go 覆盖率 "c"% < 阈值 30%"; exit 1 } print "✅ Go 覆盖率 "c"% ≥ 30%" }'
# ── Job 8: E2E Smoke (L4 进程级端到端,含 gRPC 全链路)───────────────────
# 真起打包的 server 二进制(sqlite 临时库 + 内嵌 miniredis,无需 docker-in-docker)
# → enroll(mTLS)→ ReportUsage 注入用量 → /v1/usage 断言统计真入库真读出。
# 详见 scripts/e2e-smoke.sh + server/test/e2e/。
e2e-smoke:
name: E2E Smoke — L4 进程级端到端
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: 进程级端到端冒烟 (server 二进制 + miniredis + gRPC 全链路)
run: |
mkdir -p "$HOME/.cache/pangolin-ci/gomod" "$HOME/.cache/pangolin-ci/gobuild"
docker run --rm \
-v "$PWD:/repo" -w /repo \
-v "$HOME/.cache/pangolin-ci/gomod:/go/pkg/mod" \
-v "$HOME/.cache/pangolin-ci/gobuild:/root/.cache/go-build" \
golang:1.25 \
bash -c "bash scripts/e2e-smoke.sh"
# 注:openssl/curl/python3 已在 golang:1.25 镜像内,无需 apt 安装
# (原 apt-get 会走 Docker Desktop 代理→本机 clash 死口,徒增网络脆性)。
# ── Job 10: Go 集成测试 (L2:真 mysql8/redis 经 testcontainers)──────────
# 跨库可移植(支柱 3)+ 按租户流量记账(usage)+ 配额(devices)+ 兑换(codes)+
# 节点生命周期(nodes)+ migrate/时区(store)的真库行为,sqlite 单测覆盖不到。
# 走 -tags integration,testcontainers 自起 mysql:8/redis 容器。
# · 在 host-mode runner 的宿主机直接跑 go(不套 golang 容器):testcontainers 要真
# docker,DooD 套在容器里在 Docker Desktop(mac)上网络不通。依赖宿主 go + docker。
# · -p 1 串行:一次只起一个 mysql 容器,避免并发把 Docker Desktop 压垮/端口资源争用。
go-integration:
name: Go — integration (mysql/redis testcontainers)
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: go test -tags integration (宿主 docker + testcontainers)
run: |
cd server
go test -tags integration -count=1 -p 1 ./...
# ── Job 9: Golden 视觉回归 (L3 子集:components + auth)──────────────────
# Linux 权威基线(scripts/update-goldens.sh 生成;mac 渲染不一致故钉死 Linux 容器)。
# tablet/desktop-stats golden 与 stats-overhaul 工作区耦合,待其合并后并入本 job。
golden:
name: Golden — 视觉回归 (全量:components/auth/desktop/tablet)
runs-on: mac
steps:
- name: Checkout
uses: actions/checkout@v4
- name: flutter test golden (Linux 权威基线)
run: |
mkdir -p "$HOME/.cache/pangolin-ci/pubcache"
docker run --rm \
-v "$PWD/client:/app" -w /app \
-v "$HOME/.cache/pangolin-ci/pubcache:/root/.pub-cache" \
ghcr.io/cirruslabs/flutter:stable \
bash -c "flutter pub get && flutter test test/golden"
+27 -25
View File
@@ -90,25 +90,16 @@ jobs:
name: windows
path: dist/
# Why build-macos/build-ios don't block the working android+windows pipeline
# when Apple secrets aren't configured yet (they aren't, as of this writing):
# 1. release-deploy's `needs:` below is [build-android, build-windows]
# ONLY — macOS/iOS are NOT dependencies, so release-deploy never waits
# on them and never fails because of them.
# 2. `continue-on-error: true` on both jobs keeps the overall workflow-run
# status green even while compile-macos.sh hard-fails (Apple Developer
# ID / notary secrets absent — see its fail-fast checks) — that failure
# is real signal ("go configure the secrets"), but it shouldn't read as
# "the release pipeline is broken" when android+windows shipped fine.
# 3. compile-macos.sh's own default behavior is to hard-fail (not skip)
# when its secrets are missing (macOS distribution must never ship
# unsigned/unnotarized — see its header comment); compile-ios.sh's
# default is to skip gracefully (exit 0) since an unconfigured iOS
# account is a normal "not set up yet" state, not a defect. Either way
# the job produces no dist/pangolin-macos-x64.zip, and
# release-deploy's "Download all artifacts" step (no `name:` filter)
# simply picks up whatever artifacts DO exist — an absent "macos"
# artifact is not an error there.
# build-macos/build-ios 用 `continue-on-error: true` → 即便 Apple 侧构建抖了
# (frps 拉 sing-box 源码 / 公证超时等),也不阻塞 android+windows 发布:
# 1. release-deploy 现在 `needs:` 全部四个平台(见下),所以它会**等**全部
# build 完成再发布 —— 避免旧 `needs: [build-android]` 只等 android、
# macos/ios 还没传产物就发布导致漏平台的竞态。
# 2. continue-on-error 让 macos/ios 失败仍算「completed」满足 needs,不使整个
# workflow 变红、不阻断已成功平台的发布;release-deploy 的「Download all
# artifacts」(无 name 过滤)只捡实际存在的产物,缺某平台不报错。
# 3. Apple 签名 secret 现已在 gitea 用户级配齐(DEVELOPER_ID_P12/IOS_DIST_P12/
# APPSTORE_API_* 等),macos/ios 正常应成功;continue-on-error 只是抖动兜底。
build-macos:
runs-on: mac
continue-on-error: true
@@ -172,13 +163,24 @@ jobs:
# No artifact upload — compile-ios.sh uploads straight to TestFlight via
# altool (matches jiu); nothing is produced under dist/ for this job.
# release-deploy needs build-android(唯一稳定可用的平台 floor)。windows/macos/ios
# best-effort:各自 runner+secret 就绪则上传 artifact,release-deploy flatten 收
# dist-raw/ 里"当时存在"的产物。windows 机离线 / Apple secret 未配 都不阻塞发版
# (对应平台下载保留 pangolin1 上一版,待可用时下个 client-v* 追上)。
# release-deploy 发布策略:needs 全部四平台(等它们**完成**,不抢跑),但用
# `if` 让 mac/ios/windows 的失败不 skip 本 job —— 只要 android(稳定 floor)成功即发。
# 背景:build-macos/ios 必须跑在 mac runner,其 Checkout(git fetch git.51yanmei.com)
# 走 frps 隧道偶发超时挂掉(run 239 的 ios 就是 fetch fdc13ea 超时,非 iOS 构建问题;
# run 238 同代码 fetch 碰巧成功)。这类瞬断不该阻断已成功平台的发布。
# · needs 四平台 → download-artifact 收到当时**全部已上传**的产物(修旧
# `needs:[build-android]` 只等 android、macos/ios 没传就发布漏平台的竞态)。
# · continue-on-error 在 gitea 里**不**让下游 needs 在失败时继续(会 skip),故必须
# 配 `if: always() && needs.build-android.result=='success'` 才能「等全部、失败不阻」。
release-deploy:
needs: [build-android]
runs-on: mac
needs: [build-android, build-windows, build-macos, build-ios]
if: ${{ always() && needs.build-android.result == 'success' }}
# ubuntu-latest = 家里 nas act_runner,与 gitea 同机/同网:Release → Forgejo 的
# API 调用走本地不过 frps 隧道(mac runner 走 git.51yanmei.com→frps→抖,curl 超时
# exit 28,3m3s=release_ensure 60s×3 重试耗尽)。deploy-server/deploy-site 同为
# ubuntu-latest,其 Forgejo release 步稳定通过(server 仅 13s)。此 job 全为网络/
# SSH 步骤(下载产物/传 Forgejo/SSH pangolin1/通知),无 mac 专属需求。
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
+15
View File
@@ -37,6 +37,21 @@ jobs:
export PATH=/usr/local/go/bin:$PATH
go version
# go.mod 依赖 github.com/wangjia/codes 的真源是自建私有 gitea(GOPROXY=goproxy.cn
# 对私有仓返 404 → 回退 direct git 到 github.com → 无凭证 terminal-prompts-disabled
# 失败)。这里把 go 对该路径的拉取重写到 gitea 并注入 token(oauth2:<token>
# basic-auth),GOPRIVATE 让 go 跳过公共 proxy/sumdb 直接走 git。runner 模块缓存
# 为热时不触发此路径,冷缓存(如换 runner/清缓存)必需。
- name: 私有依赖鉴权(github.com/wangjia/codes → 自建 gitea)
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_URL: ${{ secrets.FORGEJO_URL }}
run: |
proto="${FORGEJO_URL%%://*}"
host="${FORGEJO_URL#*://}"
git config --global url."${proto}://oauth2:${FORGEJO_TOKEN}@${host}/wangjia/codes.git".insteadOf "https://github.com/wangjia/codes"
echo "GOPRIVATE=github.com/wangjia/codes" >> "$GITHUB_ENV"
# 直接在 runner 跑(不嵌套 docker,避免 DinD 挂载失败;go 由上一步装好)。
- name: Compile (Go 控制面)
run: bash scripts/ci/compile-backend.sh
+3 -2
View File
@@ -2,7 +2,8 @@
# .githooks/pre-commit — 闸 3:提交前本地把关(复用 CI 同款检查的快子集)。
#
# 启用:bash ci/install-hooks.sh (设 git core.hooksPath=.githooks)
# 设计:成功静默、失败才打详情;只放秒级检查。flutter/go test 较慢,留给 CI(闸 4)。
# 设计:成功静默、失败才打详情;只放秒级检查。flutter/go test 较慢,不放这里 ——
# 提交/发版前手动跑 `bash ci/check-local.sh`(取代已删的 pipeline ci.yml)。
#
# 跑:红线词扫描 + 可移植 SQL 扫描 + codegen 漂移检查。
set -euo pipefail
@@ -48,4 +49,4 @@ if command -v node >/dev/null 2>&1; then
fi
fi
echo "[pre-commit] ✓ 本地闸通过(完整测试见 CI)"
echo "[pre-commit] ✓ 本地闸通过(完整校验跑 bash ci/check-local.sh)"
+49 -8
View File
@@ -66,11 +66,47 @@ 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 自动推送。
**校验(CI)已迁本地,不再上 pipeline**:原 `ci.yml`(push/PR)跑在 mac-pangolin-2 runner 上,
该 runner 不稳(重 job 频繁整体超时/失败),已**删除**。校验改为本地手动跑
**`bash ci/check-local.sh`**(dev mac 原生工具齐全):
- 默认档(快):shellcheck + 脱敏红线 + Android 明文 + 可移植SQL + OpenAPI + codegen漂移 +
ds-flow 三闸 + `go build/vet/test ./...` + `flutter analyze+test`(各带覆盖率闸)。
- `--full`:追加 golden(**docker Linux flutter**,mac 原生像素对不上基线)+ go integration
(testcontainers,docker)+ e2e-smoke。`--only <名>` 单跑,`--list` 列项。
- 秒级子集仍由 `.githooks/pre-commit` 提交时自动跑(`bash ci/install-hooks.sh` 启用一次);
完整校验靠 `ci/check-local.sh`。**改 CI 检查逻辑改 `ci/*.sh` 与本脚本,不要再加 workflow。**
`.gitea/workflows/` 现**只剩发版流水线**(deploy-server/client/site,tag 触发;runner 同为家里
NAS act_runner):
- **发版走 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 单源模型
@@ -97,7 +133,7 @@ cd web/website && npm run gen:tokens
> 标注「⏳」的部件正在建,未标注的已生效。参考样板 `~/code/jiu`。
**心智模型**:设计只有一个出生地(**原型单源**),代码永远是镜像;跨端副本是否走样由
**静态闸**在提交/CI 前拦截,像素是否还原由 **golden/fidelity 双级验收**兜底。主题:**light / dark 双主题**
**静态闸**在提交/本地校验(check-local)前拦截,像素是否还原由 **golden/fidelity 双级验收**兜底。主题:**light / dark 双主题**
**原型单源** `design/prototype/`(⏳ 建设中,Phase 1):
- `tokens.css` — 令牌真源:基础 `:root`(主题无关标量:间距/圆角/字号/字体/阴影/动效)+ `[data-theme=dark]` 颜色覆盖块。
@@ -121,10 +157,10 @@ cd web/website && npm run gen:tokens
| 闸 | 拦什么 | 何时 |
|---|---|---|
| 原型校验 `check-ds.mjs`(⏳ Phase 5 | 硬编码色/未定义 token/未登记组件/魔法数断点… 12 道 | pre-commit(动了原型)+ CI |
| 跨端同源 `check-l1-sync.mjs`(⏳ Phase 2 | tokens 逐值/icons 同集/Web hex 白名单 | CI |
| 代码色单源 `check_ds_code.mjs`(⏳ Phase 5 | Flutter 裸 `Color(0x)`/具名 `Colors.x``// ds-ignore: 理由` 豁免) | pre-commit`--changed`+ CI |
| codegen 零 diff `ci/check-codegen-drift.sh`**已生效** | 重生成 token 后 `git diff` 非空即 fail | pre-commit + CI |
| 原型校验 `check-ds.mjs`(⏳ Phase 5 | 硬编码色/未定义 token/未登记组件/魔法数断点… 12 道 | pre-commit(动了原型)+ check-local |
| 跨端同源 `check-l1-sync.mjs`(⏳ Phase 2 | tokens 逐值/icons 同集/Web hex 白名单 | check-local |
| 代码色单源 `check_ds_code.mjs`(⏳ Phase 5 | Flutter 裸 `Color(0x)`/具名 `Colors.x``// ds-ignore: 理由` 豁免) | pre-commit`--changed`+ check-local |
| codegen 零 diff `ci/check-codegen-drift.sh`**已生效** | 重生成 token 后 `git diff` 非空即 fail | pre-commit + check-local |
**双级像素验收**
- **golden****已有**`client/test/golden/`):多主题回归自比(同渲染器),抓串色/漏 token;真字体加载防豆腐块、钉死 viewport/dpr/动态值。重录 `flutter test --update-goldens`,随功能 commit 入库。
@@ -179,6 +215,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);**坑很深,改前必读**
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env bash
#
# ci/check-local.sh — 本地跑完整 CI 校验闸(取代已删的 .gitea/workflows/ci.yml)。
#
# 背景:CI 校验原先跑在自建 gitea 的 mac-pangolin-2 runner 上,该 runner 不稳定
# (重 job 频繁超时/整体失败)。既然开发就在 mac 上、原生工具齐全,把校验迁回本地:
# 提交前 / 发版前手动跑本脚本,取代 pipeline 上那套 ci.yml。
# 部署流水线(.gitea/workflows/deploy-*.yml,tag 触发)保留 —— 发版时仍过 go test。
#
# 用法:
# bash ci/check-local.sh # 默认档(快,原生):静态闸 + go build/test + flutter analyze/test
# bash ci/check-local.sh --full # 追加重档:golden(docker) + go integration(docker) + e2e
# bash ci/check-local.sh --only go # 只跑某一项(名字见下方 CHECK 列表,可用前缀)
# bash ci/check-local.sh --list # 列出所有检查项
#
# 各检查与 .gitea/workflows/ci.yml 的 job 一一对应;命令尽量原生(dev mac 有
# go/node/flutter/python/shellcheck),仅 golden 因 Linux 权威基线仍走 docker。
# 缺工具的检查标 SKIP(不算失败,但会在汇总里提示「未验证」)。
#
set -uo pipefail
SRC="${BASH_SOURCE[0]}"
DIR="${SRC%/*}"; [ "$DIR" = "$SRC" ] && DIR="."
cd "$DIR/.." || exit 1; REPO="$PWD"
# ── 颜色 / 汇总 ───────────────────────────────────────────────────────────
G=$'\033[0;32m'; R=$'\033[0;31m'; Y=$'\033[1;33m'; B=$'\033[1;34m'; Z=$'\033[0m'
PASS=(); FAIL=(); SKIP=()
have(){ command -v "$1" >/dev/null 2>&1; }
# run_check <名称> <命令...> —— 跑一项检查,记录结果,失败也继续(最后汇总)。
run_check(){
local name="$1"; shift
printf '%s▶ %s%s\n' "$B" "$name" "$Z"
if "$@"; then PASS+=("$name"); printf '%s ✓ %s%s\n\n' "$G" "$name" "$Z"
else FAIL+=("$name"); printf '%s ✗ %s%s\n\n' "$R" "$name" "$Z"; fi
}
skip(){ SKIP+=("$1"); printf '%s⏭ SKIP %s(%s)%s\n\n' "$Y" "$1" "$2" "$Z"; }
# ── 各检查(与 ci.yml job 对应)──────────────────────────────────────────
check_shellcheck(){
have shellcheck || { skip "shellcheck" "未装 shellcheck(brew install shellcheck)"; return 0; }
shellcheck -S warning \
deploy/bootstrap/init.sh \
deploy/bootstrap/monitor/pangolin-monitor.sh \
deploy/bootstrap/monitor/deadman-watch.sh \
deploy/single-node/deploy.sh \
scripts/ci/*.sh \
ci/*.sh
}
check_openapi(){
# 原生优先;缺模块就跳过并提示一次性安装(不走 docker+pip:每次拉镜像装包太慢)。
if have python3 && python3 -c "import openapi_spec_validator" 2>/dev/null; then
python3 -m openapi_spec_validator design/server/openapi.yaml
else
skip "openapi" "缺模块,一次性装:pip3 install openapi-spec-validator"; return 0
fi
}
check_redline(){ bash ci/scan-redline.sh; }
check_cleartext(){ bash ci/scan-cleartext.sh; }
check_portable_sql(){ bash ci/scan-portable-sql.sh; }
check_codegen_drift(){ have node || { skip "codegen-drift" "未装 node"; return 0; }; bash ci/check-codegen-drift.sh; }
check_ds_flow(){
have node || { skip "ds-flow" "未装 node"; return 0; }
node design/prototype/tools/check-ds.mjs \
&& node tools/check-l1-sync.mjs \
&& ( cd client && node tool/check_ds_code.mjs --strict )
}
check_go(){
have go || { skip "go build+test" "未装 go"; return 0; }
( cd server \
&& go build ./... \
&& go vet ./... \
&& go test -coverprofile=cover.out ./... \
&& go tool cover -func=cover.out > coverage.txt \
&& tail -1 coverage.txt \
&& awk '/^total:/{c=$3; sub(/%/,"",c); if(c+0<30){print "❌ Go 覆盖率 "c"% < 30%"; exit 1} print "✅ Go 覆盖率 "c"% ≥ 30%"}' coverage.txt )
}
check_flutter(){
have flutter || { skip "flutter analyze+test" "未装 flutter"; return 0; }
( cd client \
&& flutter pub get \
&& flutter analyze --no-fatal-infos \
&& flutter test --coverage test/unit test/widget test/contract \
&& awk -F: '/^LF:/{f+=$2} /^LH:/{h+=$2} END{c=(f>0)?h/f*100:0; if(c<28){printf "❌ flutter 覆盖率 %.1f%% < 28%%\n",c; exit 1} printf "✅ flutter 覆盖率 %.1f%% ≥ 28%%\n",c}' coverage/lcov.info )
}
# ── 重档(--full):需 docker / 更慢 ──────────────────────────────────────
check_golden(){
# Linux 权威基线(mac 原生渲染像素对不上),必须 docker Linux flutter。
have docker || { skip "golden" "未装 docker(golden 需 Linux 容器)"; return 0; }
mkdir -p "$HOME/.cache/pangolin-ci/pubcache"
docker run --rm -v "$REPO/client:/app" -w /app \
-v "$HOME/.cache/pangolin-ci/pubcache:/root/.pub-cache" \
ghcr.io/cirruslabs/flutter:stable \
bash -c "flutter pub get && flutter test test/golden"
}
check_go_integration(){
have go || { skip "go integration" "未装 go"; return 0; }
have docker || { skip "go integration" "未装 docker(testcontainers 需 docker)"; return 0; }
( cd server && go test -tags integration -count=1 -p 1 ./... )
}
check_e2e(){
have go || { skip "e2e-smoke" "未装 go"; return 0; }
bash scripts/e2e-smoke.sh
}
# 检查登记表:名字 → 档位(fast|full)。名字→函数用 case 分发(避开关联数组的
# bash4+ 依赖与 set -u subscript 求值坑)。
FAST=(shellcheck openapi redline cleartext portable-sql codegen-drift ds-flow go flutter)
FULL=(golden go-integration e2e)
dispatch(){
case "$1" in
shellcheck) check_shellcheck ;;
openapi) check_openapi ;;
redline) check_redline ;;
cleartext) check_cleartext ;;
portable-sql) check_portable_sql ;;
codegen-drift) check_codegen_drift ;;
ds-flow) check_ds_flow ;;
go) check_go ;;
flutter) check_flutter ;;
golden) check_golden ;;
go-integration) check_go_integration ;;
e2e) check_e2e ;;
*) echo "未知检查:$1"; return 2 ;;
esac
}
# ── 参数 ────────────────────────────────────────────────────────────────
MODE=fast; ONLY=""
for a in "$@"; do
case "$a" in
--full) MODE=full ;;
--fast) MODE=fast ;;
--list) printf 'fast: %s\nfull: %s\n' "${FAST[*]}" "${FULL[*]}"; exit 0 ;;
--only=*) ONLY="${a#--only=}" ;;
--only) MODE=only ;; # 兼容 `--only go`(下一个 token 当名字)
-h|--help) sed -n '2,26p' "$SRC"; exit 0 ;;
*) [ "$MODE" = only ] && ONLY="$a" ;;
esac
done
if [ -n "$ONLY" ]; then
ORDER=()
for k in "${FAST[@]}" "${FULL[@]}"; do [[ "$k" == "$ONLY"* ]] && ORDER+=("$k"); done
[ ${#ORDER[@]} -eq 0 ] && { echo "无匹配 '$ONLY';可选:${FAST[*]} ${FULL[*]}"; exit 2; }
elif [ "$MODE" = full ]; then ORDER=("${FAST[@]}" "${FULL[@]}")
else ORDER=("${FAST[@]}"); fi
printf '%s== 本地 CI 校验(%s档,%d 项)==%s\n\n' "$B" "$MODE" "${#ORDER[@]}" "$Z"
for k in "${ORDER[@]}"; do run_check "$k" dispatch "$k"; done
# ── 汇总 ────────────────────────────────────────────────────────────────
printf '%s══════ 汇总 ══════%s\n' "$B" "$Z"
printf '%s通过 %d%s | %s失败 %d%s | %s跳过 %d%s\n' "$G" "${#PASS[@]}" "$Z" "$R" "${#FAIL[@]}" "$Z" "$Y" "${#SKIP[@]}" "$Z"
[ ${#SKIP[@]} -gt 0 ] && printf '%s跳过(未验证):%s%s\n' "$Y" "${SKIP[*]}" "$Z"
if [ ${#FAIL[@]} -gt 0 ]; then printf '%s失败:%s%s\n' "$R" "${FAIL[*]}" "$Z"; exit 1; fi
printf '%s全部通过 ✓%s\n' "$G" "$Z"
+5
View File
@@ -663,7 +663,12 @@ 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?
String get routingResetConfirmBody; // 重置确认弹层正文 / Reset confirm dialog body
String get routingResetConfirmAction; // 重置(确认按钮) / Reset (confirm action)
String get routingBack; // 返回设置 / Back to settings
}
+10
View File
@@ -571,10 +571,20 @@ 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';
@override
String get routingResetConfirmTitle => 'Reset to defaults?';
@override
String get routingResetConfirmBody => 'This clears all your custom rules and restores the factory routing table.';
@override
String get routingResetConfirmAction => 'Reset';
@override
String get routingBack => 'Back to settings';
@override
List<String> get days7 => const ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
+10
View File
@@ -571,10 +571,20 @@ 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';
@override
String get routingResetConfirmTitle => '¿Restablecer las reglas predeterminadas?';
@override
String get routingResetConfirmBody => 'Esto borra todas tus reglas personalizadas y restaura la tabla de enrutamiento de fábrica.';
@override
String get routingResetConfirmAction => 'Restablecer';
@override
String get routingBack => 'Volver a ajustes';
@override
List<String> get days7 => const ['L', 'M', 'X', 'J', 'V', 'S', 'D'];
+10
View File
@@ -571,10 +571,20 @@ class StringsJa extends AppText {
@override
String get routingAddRule => 'ルールを追加';
@override
String get routingSaveFailed => '保存に失敗しました。もう一度お試しください';
@override
String get routingRuleValueInvalid => '形式が正しくありません';
@override
String get routingImport => 'テキストから読み込み';
@override
String get routingReset => 'デフォルトに戻す';
@override
String get routingResetConfirmTitle => 'デフォルトのルールに戻しますか?';
@override
String get routingResetConfirmBody => 'カスタムルールをすべて削除し、出荷時の分流テーブルに戻します。';
@override
String get routingResetConfirmAction => 'リセット';
@override
String get routingBack => '設定に戻る';
@override
List<String> get days7 => const ['', '', '', '', '', '', ''];
+10
View File
@@ -571,10 +571,20 @@ class StringsKo extends AppText {
@override
String get routingAddRule => '규칙 추가';
@override
String get routingSaveFailed => '저장에 실패했습니다. 다시 시도하세요';
@override
String get routingRuleValueInvalid => '형식이 올바르지 않습니다';
@override
String get routingImport => '텍스트에서 가져오기';
@override
String get routingReset => '기본값 재설정';
@override
String get routingResetConfirmTitle => '기본 규칙으로 재설정할까요?';
@override
String get routingResetConfirmBody => '사용자 지정 규칙을 모두 삭제하고 초기 분산 규칙으로 복원합니다.';
@override
String get routingResetConfirmAction => '재설정';
@override
String get routingBack => '설정으로 돌아가기';
@override
List<String> get days7 => const ['', '', '', '', '', '', ''];
+10
View File
@@ -571,10 +571,20 @@ class StringsRu extends AppText {
@override
String get routingAddRule => 'Добавить правило';
@override
String get routingSaveFailed => 'Не удалось сохранить, попробуйте ещё раз';
@override
String get routingRuleValueInvalid => 'Неверный формат';
@override
String get routingImport => 'Импорт из текста';
@override
String get routingReset => 'Сбросить настройки';
@override
String get routingResetConfirmTitle => 'Сбросить к правилам по умолчанию?';
@override
String get routingResetConfirmBody => 'Это удалит все ваши пользовательские правила и восстановит заводскую таблицу маршрутизации.';
@override
String get routingResetConfirmAction => 'Сбросить';
@override
String get routingBack => 'Назад к настройкам';
@override
List<String> get days7 => const ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
+10
View File
@@ -571,10 +571,20 @@ class StringsZh extends AppText {
@override
String get routingAddRule => '添加规则';
@override
String get routingSaveFailed => '保存失败,请重试';
@override
String get routingRuleValueInvalid => '格式不正确';
@override
String get routingImport => '从文本导入';
@override
String get routingReset => '重置默认';
@override
String get routingResetConfirmTitle => '重置为默认规则?';
@override
String get routingResetConfirmBody => '将清除你自定义的所有规则,恢复到出厂分流表。';
@override
String get routingResetConfirmAction => '重置';
@override
String get routingBack => '返回设置';
@override
List<String> get days7 => const ['', '', '', '', '', '', ''];
+3 -3
View File
@@ -43,8 +43,8 @@ Future<void> main(List<String> args) async {
await windowManager.setMinimumSize(const Size(720, 560));
await windowManager.setSize(const Size(920, 640));
await windowManager.center();
// 窗口标题用文品牌名(不带 "VPN" 字眼);英文环境下原生标题为 "Pangolin"
await windowManager.setTitle('穿山甲');
// 窗口标题用文品牌名(不带 "VPN" 字眼;默认 UI 语言为英文,标题保持一致)
await windowManager.setTitle('Pangolin');
// 自启:首帧前就隐藏窗口(避免闪现),托盘已就绪可随时唤回;自动连接逻辑照常跑。
if (bootAutostart) {
await windowManager.hide();
@@ -109,7 +109,7 @@ class _PangolinAppState extends ConsumerState<PangolinApp> {
Widget build(BuildContext context) {
final mode = ref.watch(themeModeProvider);
return MaterialApp(
title: '穿山甲',
title: 'Pangolin',
debugShowCheckedModeBanner: false,
theme: PangolinTheme.light,
darkTheme: PangolinTheme.dark,
+76 -3
View File
@@ -1,8 +1,10 @@
// routing_profile.dart — 可配置分流档案(GET/POST /v1/me/routing)。
//
// 对齐后端契约(server/internal/httpapi 分流端点):
// {mode, builtin:{china_direct,lan_direct,private_via_tunnel}, rules:[...], final}。
// {mode, builtin:{china_direct,lan_direct,private_via_tunnel}, rules:[...], final,
// system_locked_domains:[...]}(FT-A 起响应含只读私有服务域名清单)。
// 手写 fromJson/toJson(项目无 json_serializable,仿 lib/models/me.dart)。
import 'package:flutter/foundation.dart' show listEquals;
/// 分流模式。
/// 'rule' = 按规则(内置 + 自定义) | 'global' = 全局代理 | 'direct' = 全局直连。
@@ -55,8 +57,24 @@ class Builtin {
lanDirect: lanDirect ?? this.lanDirect,
privateViaTunnel: privateViaTunnel ?? this.privateViaTunnel,
);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Builtin &&
runtimeType == other.runtimeType &&
chinaDirect == other.chinaDirect &&
lanDirect == other.lanDirect &&
privateViaTunnel == other.privateViaTunnel;
@override
int get hashCode => Object.hash(chinaDirect, lanDirect, privateViaTunnel);
}
/// copyWith 的哨兵值:用于区分「未传参(保留原值)」与「显式传 null(清空该字段)」,
/// 仅 [RoutingRule.note] 需要(其它字段无「清空」语义,`??` 已够用)。
const _noteSentinel = Object();
/// 单条自定义分流规则。
///
/// **enabled 语义**(计划裁决):构造默认 `true`;[toJson] 恒输出 `enabled` 字段
@@ -95,20 +113,35 @@ class RoutingRule {
'enabled': enabled,
};
/// [note] 用哨兵:不传 → 保留原值;显式传 `null` → 清空为 null。
RoutingRule copyWith({
String? type,
String? value,
String? action,
String? note,
Object? note = _noteSentinel,
bool? enabled,
}) =>
RoutingRule(
type: type ?? this.type,
value: value ?? this.value,
action: action ?? this.action,
note: note ?? this.note,
note: identical(note, _noteSentinel) ? this.note : note as String?,
enabled: enabled ?? this.enabled,
);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is RoutingRule &&
runtimeType == other.runtimeType &&
type == other.type &&
value == other.value &&
action == other.action &&
note == other.note &&
enabled == other.enabled;
@override
int get hashCode => Object.hash(type, value, action, note, enabled);
}
/// 分流档案(账户级,单份)。
@@ -118,6 +151,7 @@ class RoutingProfile {
this.builtin = const Builtin(),
this.rules = const [],
this.finalAction = 'proxy',
this.systemLockedDomains = const [],
});
final RoutingMode mode;
@@ -127,6 +161,11 @@ class RoutingProfile {
/// 兜底动作(JSON key 为保留字 `final`,Dart 侧改名)。'proxy' | 'direct'。
final String finalAction;
/// **只读**:系统强制走隧道的私有服务域名清单(服务端 `PANGOLIN_PRIVATE_SPLIT_DOMAINS`,
/// FT-A 起随 GET /v1/me/routing 下发)。`toJson()` 不输出——服务端忽略,且此字段
/// 客户端不可写。
final List<String> systemLockedDomains;
factory RoutingProfile.fromJson(Map<String, dynamic> m) => RoutingProfile(
mode: m['mode'] as String? ?? 'rule',
builtin: m['builtin'] != null
@@ -136,6 +175,8 @@ class RoutingProfile {
.map((e) => RoutingRule.fromJson(e as Map<String, dynamic>))
.toList(),
finalAction: m['final'] as String? ?? 'proxy',
systemLockedDomains:
(m['system_locked_domains'] as List?)?.cast<String>() ?? const [],
);
Map<String, dynamic> toJson() => {
@@ -145,16 +186,48 @@ class RoutingProfile {
'final': finalAction,
};
/// 出厂默认档案(对齐服务端 `routing.Default()`):智能分流 + 内置全开 + 无自定义规则。
/// 不含 systemLockedDomains(那是账户相关的只读回显,由调用方按需保留;见
/// RoutingProfileNotifier.resetToDefault())。
factory RoutingProfile.defaults() => const RoutingProfile(
mode: 'rule',
builtin: Builtin(),
rules: [],
finalAction: 'proxy',
);
RoutingProfile copyWith({
RoutingMode? mode,
Builtin? builtin,
List<RoutingRule>? rules,
String? finalAction,
List<String>? systemLockedDomains,
}) =>
RoutingProfile(
mode: mode ?? this.mode,
builtin: builtin ?? this.builtin,
rules: rules ?? this.rules,
finalAction: finalAction ?? this.finalAction,
systemLockedDomains: systemLockedDomains ?? this.systemLockedDomains,
);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is RoutingProfile &&
runtimeType == other.runtimeType &&
mode == other.mode &&
builtin == other.builtin &&
listEquals(rules, other.rules) &&
finalAction == other.finalAction &&
listEquals(systemLockedDomains, other.systemLockedDomains);
@override
int get hashCode => Object.hash(
mode,
builtin,
Object.hashAll(rules),
finalAction,
Object.hashAll(systemLockedDomains),
);
}
-41
View File
@@ -60,15 +60,6 @@ class AccountPage extends ConsumerWidget {
isFree: isFree,
email: email,
expiresLabel: expiresLabel,
// Renew/Upgrade 直达购买页(套餐 + 渠道 switch),不再经 PlansScreen。
onUpgrade: () => open(
NavView.purchase,
PurchaseScreen(
t: t,
onOrderCreated: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => PaymentScreen(t: t, onDone: () => Navigator.of(context).pop()))),
),
),
),
const SizedBox(height: 18),
// 账户信息
@@ -156,13 +147,11 @@ class _PlanBanner extends StatelessWidget {
required this.isFree,
required this.email,
required this.expiresLabel,
required this.onUpgrade,
});
final AppText t;
final bool isFree;
final String email;
final String expiresLabel;
final VoidCallback onUpgrade;
@override
Widget build(BuildContext context) {
@@ -193,7 +182,6 @@ class _PlanBanner extends StatelessWidget {
child: Text(t.freePlanName, style: PangolinText.caption.copyWith(color: c.fg2, fontWeight: FontWeight.w600, fontSize: 11)),
),
])),
_UpgradeButton(label: t.upgradeBtn, onTap: onUpgrade),
]),
]),
);
@@ -222,40 +210,11 @@ class _PlanBanner extends StatelessWidget {
Text(expiresLabel.isEmpty ? t.proMember : '${t.proMember} · $expiresLabel',
style: TextStyle(color: PangolinColors.white.withValues(alpha: 0.85), fontSize: 12)),
])),
FilledButton(
onPressed: onUpgrade,
style: FilledButton.styleFrom(
backgroundColor: PangolinColors.white,
foregroundColor: PangolinColors.clay700,
shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
),
child: Text(t.upgradeBtn, style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 13)),
),
]),
);
}
}
class _UpgradeButton extends StatelessWidget {
const _UpgradeButton({required this.label, required this.onTap});
final String label;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final c = context.pangolin;
return FilledButton(
onPressed: onTap,
style: FilledButton.styleFrom(
backgroundColor: c.accent,
foregroundColor: c.fgOnAccent,
shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
),
child: Text(label, style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 13)),
);
}
}
class _SectionLabel extends StatelessWidget {
const _SectionLabel({required this.text});
+21 -5
View File
@@ -1,4 +1,6 @@
// app_providers.dart — 语言 / 主题 / 套餐视角等基础状态(Riverpod)
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -32,15 +34,29 @@ AppText appTextFor(AppLang lang) {
}
}
/// 当前语言(单显)。默认英文(国际化默认语种);用户选择持久化到
/// shared_preferences(key `pg_lang`,存枚举 name),重启保留 —— 原来无持久化,
/// 切了语言重启会丢。设置/账户页经 `.notifier).set(lang)` 切换
/// 当前语言。首启无用户选择时**跟随系统语言**(设备 locale → 支持的 AppLang,
/// 命不中回退英文);用户在设置/账户页显式切换后持久化到 shared_preferences
/// (key `pg_lang`,存枚举 name),此后一律以用户选择为准、不再看系统
class LocaleNotifier extends StateNotifier<AppLang> {
LocaleNotifier() : super(AppLang.en) {
LocaleNotifier() : super(_systemDefault()) {
_load();
}
static const _key = 'pg_lang';
/// 设备语言 → 支持的 AppLang。取平台首选 locale 的语言码(zh/ja/ko/ru/es 命中
/// 对应语种,其余一律英文)。构造期同步可用,无需 await。
static AppLang _systemDefault() {
try {
final code = ui.PlatformDispatcher.instance.locale.languageCode.toLowerCase();
for (final l in AppLang.values) {
if (l.name == code) return l;
}
} catch (_) {
/* 取系统 locale 失败 → 英文 */
}
return AppLang.en;
}
Future<void> _load() async {
try {
final saved = (await SharedPreferences.getInstance()).getString(_key);
@@ -53,7 +69,7 @@ class LocaleNotifier extends StateNotifier<AppLang> {
}
}
} catch (_) {
/* 读失败保持默认 en */
/* 读失败保持系统默认 */
}
}
+8
View File
@@ -69,6 +69,14 @@ class RoutingProfileNotifier extends AsyncNotifier<RoutingProfile> {
return p.copyWith(rules: rules);
});
/// 重置为出厂默认档案(模式/内置开关/自定义规则/final 全部还原),但保留当前只读的
/// [RoutingProfile.systemLockedDomains] 回显不丢——它不是用户可改的档案内容,只是
/// 服务端下发的账户相关信息,与「重置」无关。复用 [_mutateAndSave]/[_persist]:
/// 乐观更新 + 失败回滚 rethrow + 存成功后连接态 on 则自动重连,同 addRule。
Future<void> resetToDefault() => _mutateAndSave(
(p) => RoutingProfile.defaults().copyWith(systemLockedDomains: p.systemLockedDomains),
);
Future<void> _mutateAndSave(RoutingProfile Function(RoutingProfile) transform) async {
final prev = state.valueOrNull ?? const RoutingProfile();
final next = transform(prev);
+3 -3
View File
@@ -58,11 +58,11 @@ class TrayService with TrayListener, WindowListener {
await trayManager.setIcon(
Platform.isWindows ? 'assets/tray_icon.ico' : 'assets/tray_icon.png',
);
await trayManager.setToolTip('穿山甲 Pangolin');
await trayManager.setToolTip('Pangolin');
await trayManager.setContextMenu(Menu(items: [
MenuItem(key: 'show', label: '显示主界面'),
MenuItem(key: 'show', label: 'Show Window'),
MenuItem.separator(),
MenuItem(key: 'quit', label: '退出'),
MenuItem(key: 'quit', label: 'Quit'),
]));
}
+142 -20
View File
@@ -7,19 +7,21 @@
// 冲突提示两类(prototype 里只是静态示例,这里落成真computed 逻辑):
// ①「已被上面规则覆盖」——同 type+value 的自定义规则被更靠前的规则遮蔽(纯本地计算,
// 首命中生效语义决定)。
// ②「系统强制走隧道,此规则不生效」——命中系统锁定目标。当前 RoutingProfile 契约
// 只下发 builtin 三个布尔开关,并未下发具体锁定域名清单(PANGOLIN_PRIVATE_SPLIT_DOMAINS
// 只在服务端 env,未经 API 暴露给客户端),故本屏对②采用保守启发式:仅当自定义规则
// 类型为 ip_cidr 且落在私网/回环地址段(RFC1918 + 127.0.0.0/8)时标记——这部分恒被
// 内置「局域网 / 私网直连」(builtin.lanDirect,强制不可关)接管,与用户规则动作冲突。
// 域名级私有服务分流(如 git.yanmeiai.com)不在此启发式覆盖范围,需服务端把锁定域名
// 清单下发给客户端后再补全(见 task-7-report.md 里的疑虑)。
// ②「系统强制走隧道,此规则不生效」——命中系统锁定目标,两类启发式并存:
// - ip_cidr 落在私网/回环地址段(RFC1918 + 127.0.0.0/8)——恒被内置「局域网 / 私网
// 直连」(builtin.lanDirect,强制不可关)接管。
// - 域名类规则(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';
@@ -62,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;
@@ -87,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)),
@@ -102,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),
@@ -136,12 +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), i < profile.rules.length - 1,
onDelete: () => notifier.removeRule(i)),
_ruleRow(
context, c, t, i, profile.rules[i],
_conflictFor(profile.rules, i, profile.systemLockedDomains),
i < profile.rules.length - 1,
onDelete: () => _guardSave(context, t, () => notifier.removeRule(i))),
],
),
),
@@ -172,14 +195,62 @@ class _RoutingBody extends ConsumerWidget {
]),
),
]),
const SizedBox(height: 20),
// ── 重置默认(桌面/移动共用同一按钮;二次确认防误触) ──
PangolinButton(
label: t.routingReset,
icon: PangolinIcons.refreshCw,
variant: PangolinButtonVariant.ghost,
expand: true,
onPressed: () => _confirmReset(context, ref, c, t),
),
],
);
}
Future<void> _confirmReset(BuildContext context, WidgetRef ref, PangolinScheme c, AppText t) async {
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
backgroundColor: c.surface,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(PangolinRadius.xl)),
title: Row(children: [
Container(
width: 34, height: 34,
decoration: BoxDecoration(color: c.dangerSubtle, shape: BoxShape.circle),
child: Icon(PangolinIcons.refreshCw, size: 18, color: c.danger),
),
const SizedBox(width: 12),
Expanded(
child: Text(t.routingResetConfirmTitle,
overflow: TextOverflow.ellipsis,
style: PangolinText.body.copyWith(color: c.fg1, fontWeight: FontWeight.w700)),
),
]),
content: Text(t.routingResetConfirmBody, style: PangolinText.sm.copyWith(color: c.fg2, height: 1.5)),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: Text(t.devCancel, style: PangolinText.sm.copyWith(color: c.fg2, fontWeight: FontWeight.w600)),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
child: Text(t.routingResetConfirmAction, style: PangolinText.sm.copyWith(color: c.danger, fontWeight: FontWeight.w700)),
),
],
),
);
if (ok != true) return;
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(
@@ -291,9 +362,9 @@ class _RoutingBody extends ConsumerWidget {
/// 规则行冲突类型:先判系统锁定(与规则顺序无关),再判是否被更靠前的同规则遮蔽。
enum _RuleConflict { none, shadowed, systemLocked }
_RuleConflict _conflictFor(List<RoutingRule> rules, int i) {
_RuleConflict _conflictFor(List<RoutingRule> rules, int i, List<String> systemLockedDomains) {
final r = rules[i];
if (_looksSystemLocked(r)) return _RuleConflict.systemLocked;
if (_looksSystemLocked(r, systemLockedDomains)) return _RuleConflict.systemLocked;
for (var j = 0; j < i; j++) {
final o = rules[j];
if (o.type == r.type && o.value.trim().toLowerCase() == r.value.trim().toLowerCase()) {
@@ -303,10 +374,29 @@ _RuleConflict _conflictFor(List<RoutingRule> rules, int i) {
return _RuleConflict.none;
}
/// 私网/回环地址段启发式(RFC1918 + 127.0.0.0/8),见文件头注释——真正的系统锁定域名清单
/// 未经 API 下发,这里只覆盖 ip_cidr 类型且落在该地址段的情形。
/// 私网/回环地址段启发式(RFC1918 + 127.0.0.0/8),见文件头注释
final _privateIpPrefix = RegExp(r'^(10\.|192\.168\.|127\.|172\.(1[6-9]|2\d|3[01])\.)');
bool _looksSystemLocked(RoutingRule r) => r.type == 'ip_cidr' && _privateIpPrefix.hasMatch(r.value);
/// 系统锁定判定:ip_cidr 私网/回环启发式,或域名类规则命中 [systemLockedDomains]。
bool _looksSystemLocked(RoutingRule r, List<String> systemLockedDomains) {
if (r.type == 'ip_cidr') return _privateIpPrefix.hasMatch(r.value);
if (systemLockedDomains.isEmpty) return false;
final value = r.value.trim().toLowerCase();
if (value.isEmpty) return false;
switch (r.type) {
case 'domain':
return systemLockedDomains.any((d) => d.toLowerCase() == value);
case 'domain_suffix':
return systemLockedDomains.any((d) {
final dl = d.toLowerCase();
return dl == value || dl.endsWith('.$value');
});
case 'domain_keyword':
return systemLockedDomains.any((d) => d.toLowerCase().contains(value));
default:
return false;
}
}
String _routingTypeLabel(AppText t, String type) => switch (type) {
'domain' => t.routingTypeDomain,
@@ -380,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,
@@ -413,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,
),
),
),
],
],
),
),
),
);
@@ -659,7 +659,7 @@
baseConfigurationReference = C57BBFD43F9175D1E23685EF /* Pods-RunnerTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 53;
CURRENT_PROJECT_VERSION = 55;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.RunnerTests;
@@ -674,7 +674,7 @@
baseConfigurationReference = F8904897A48DC81799B8752E /* Pods-RunnerTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 53;
CURRENT_PROJECT_VERSION = 55;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.RunnerTests;
@@ -689,7 +689,7 @@
baseConfigurationReference = B21E68FC1F5D33DD67A0DF5E /* Pods-RunnerTests.profile.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 53;
CURRENT_PROJECT_VERSION = 55;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pangolin.pangolin.RunnerTests;
@@ -960,7 +960,7 @@
CODE_SIGN_ENTITLEMENTS = PacketTunnel/PacketTunnel.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 53;
CURRENT_PROJECT_VERSION = 55;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
@@ -1010,7 +1010,7 @@
CODE_SIGN_ENTITLEMENTS = PacketTunnel/PacketTunnel.entitlements;
CODE_SIGN_IDENTITY = "Developer ID Application";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 53;
CURRENT_PROJECT_VERSION = 55;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
@@ -1059,7 +1059,7 @@
CODE_SIGN_ENTITLEMENTS = PacketTunnel/PacketTunnel.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 53;
CURRENT_PROJECT_VERSION = 55;
DEVELOPMENT_TEAM = BYL4KQHMTN;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
+1 -1
View File
@@ -13,7 +13,7 @@
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<string>Pangolin</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
@@ -36,4 +36,67 @@ void main() {
expect(p.builtin.lanDirect, isTrue);
expect(p.builtin.privateViaTunnel, isTrue);
});
test('systemLockedDomains:fromJson 读取,默认空,toJson 不输出(只读字段)', () {
final withLocks = RoutingProfile.fromJson({
'mode': 'rule',
'rules': [],
'final': 'proxy',
'system_locked_domains': ['git.yanmeiai.com', 'admin.yanmeiai.com'],
});
expect(withLocks.systemLockedDomains, ['git.yanmeiai.com', 'admin.yanmeiai.com']);
expect(withLocks.toJson().containsKey('system_locked_domains'), isFalse);
final withoutLocks = RoutingProfile.fromJson({'mode': 'rule', 'rules': [], 'final': 'proxy'});
expect(withoutLocks.systemLockedDomains, isEmpty);
});
test('RoutingProfile.defaults() 对齐服务端 routing.Default()', () {
final d = RoutingProfile.defaults();
expect(d.mode, 'rule');
expect(d.builtin.chinaDirect, isTrue);
expect(d.builtin.lanDirect, isTrue);
expect(d.builtin.privateViaTunnel, isTrue);
expect(d.rules, isEmpty);
expect(d.finalAction, 'proxy');
});
test('RoutingRule.copyWith 用哨兵让 note 可清空为 null', () {
const r = RoutingRule(type: 'domain', value: 'a.com', action: 'proxy', note: 'ci');
final cleared = r.copyWith(note: null);
expect(cleared.note, isNull, reason: '显式传 null 应清空 note,而不是被 ?? 吞掉');
final unchanged = r.copyWith(value: 'b.com');
expect(unchanged.note, 'ci', reason: '不传 note 时应保留原值');
});
test('RoutingRule / Builtin / RoutingProfile 值相等(operator==)', () {
const r1 = RoutingRule(type: 'domain', value: 'a.com', action: 'proxy', note: 'x');
const r2 = RoutingRule(type: 'domain', value: 'a.com', action: 'proxy', note: 'x');
const r3 = RoutingRule(type: 'domain', value: 'a.com', action: 'direct', note: 'x');
expect(r1, r2);
expect(r1.hashCode, r2.hashCode);
expect(r1 == r3, isFalse);
const b1 = Builtin(chinaDirect: true, lanDirect: false, privateViaTunnel: true);
const b2 = Builtin(chinaDirect: true, lanDirect: false, privateViaTunnel: true);
const b3 = Builtin();
expect(b1, b2);
expect(b1.hashCode, b2.hashCode);
expect(b1 == b3, isFalse);
const p1 = RoutingProfile(mode: 'rule', rules: [r1], finalAction: 'proxy');
const p2 = RoutingProfile(mode: 'rule', rules: [r2], finalAction: 'proxy');
final p3 = RoutingProfile.fromJson({
'mode': 'rule',
'rules': [
{'type': 'domain', 'value': 'a.com', 'action': 'proxy', 'note': 'x', 'enabled': true}
],
'final': 'proxy',
'system_locked_domains': ['git.yanmeiai.com'],
});
expect(p1, p2);
expect(p1.hashCode, p2.hashCode);
expect(p1 == p3, isFalse, reason: 'systemLockedDomains 不同应视为不相等');
});
}
@@ -115,6 +115,36 @@ void main() {
expect(api.saved, hasLength(3));
});
test('resetToDefault() 还原出厂档案,保留 systemLockedDomains,并落盘', () async {
final api = _FakeAccountApi()
..initial = RoutingProfile.fromJson({
'mode': 'global',
'builtin': {'china_direct': false, 'lan_direct': true, 'private_via_tunnel': true},
'rules': [
{'type': 'domain', 'value': 'a.com', 'action': 'reject'},
],
'final': 'direct',
'system_locked_domains': ['git.yanmeiai.com'],
});
final c = _makeContainer(api);
addTearDown(c.dispose);
await _waitLoggedIn(c);
await c.read(routingProfileProvider.future);
await c.read(routingProfileProvider.notifier).resetToDefault();
final state = c.read(routingProfileProvider).value!;
expect(state.mode, 'rule');
expect(state.builtin.chinaDirect, isTrue);
expect(state.rules, isEmpty);
expect(state.finalAction, 'proxy');
expect(state.systemLockedDomains, ['git.yanmeiai.com'],
reason: '只读字段随重置保留,不因重置默认档案而丢失');
expect(api.saved, hasLength(1));
expect(api.saved.single.mode, 'rule');
});
test('保存失败:回退到变更前 state 且 rethrow,不静默吞', () async {
final api = _FakeAccountApi();
final c = _makeContainer(api);
@@ -103,11 +103,101 @@ void main() {
expect(find.text(StringsZh().routingRuleShadowed), findsOneWidget);
});
testWidgets('a domain rule matching a system-locked domain is flagged forced', (tester) async {
final profile = RoutingProfile.fromJson({
'mode': 'rule',
'builtin': {'china_direct': true, 'lan_direct': true, 'private_via_tunnel': true},
'rules': [
{'type': 'domain_suffix', 'value': 'git.yanmeiai.com', 'action': 'direct'},
],
'final': 'proxy',
'system_locked_domains': ['git.yanmeiai.com'],
});
await tester.pumpWidget(ProviderScope(
overrides: [
appTextProvider.overrideWithValue(StringsZh()),
routingProfileProvider.overrideWith(() => _FakeRoutingNotifier(profile)),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: PangolinTheme.light,
home: const RoutingScreen(),
),
));
await tester.pumpAndSettle();
expect(find.text(StringsZh().routingForcedRow), findsOneWidget);
});
testWidgets('reset button opens confirm dialog and resets on confirm', (tester) async {
final profile = RoutingProfile.fromJson({
'mode': 'rule',
'builtin': {'china_direct': true, 'lan_direct': true, 'private_via_tunnel': true},
'rules': [
{'type': 'domain_suffix', 'value': 'x.com', 'action': 'direct'},
],
'final': 'proxy',
});
final notifier = _FakeRoutingNotifier(profile);
await tester.pumpWidget(ProviderScope(
overrides: [
appTextProvider.overrideWithValue(StringsZh()),
routingProfileProvider.overrideWith(() => notifier),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: PangolinTheme.light,
home: const RoutingScreen(),
),
));
await tester.pumpAndSettle();
expect(find.text('x.com'), findsOneWidget);
// 重置按钮在 FINAL 区之后,滚到可见再点(屏内不止一个 Scrollable,取外层 ListView)。
await tester.scrollUntilVisible(
find.text(StringsZh().routingReset),
200,
scrollable: find.byType(Scrollable).first,
);
await tester.pumpAndSettle();
await tester.tap(find.text(StringsZh().routingReset));
await tester.pumpAndSettle();
// 确认弹层出现,取消不触发重置。
expect(find.text(StringsZh().routingResetConfirmBody), findsOneWidget);
await tester.tap(find.text(StringsZh().devCancel));
await tester.pumpAndSettle();
expect(notifier.resetCalled, isFalse);
expect(find.text('x.com'), findsOneWidget);
// 再次点击并确认 → 触发重置。
await tester.tap(find.text(StringsZh().routingReset));
await tester.pumpAndSettle();
await tester.tap(find.text(StringsZh().routingResetConfirmAction));
await tester.pumpAndSettle();
expect(notifier.resetCalled, isTrue);
expect(find.text('x.com'), findsNothing);
});
}
class _FakeRoutingNotifier extends RoutingProfileNotifier {
_FakeRoutingNotifier(this._v);
final RoutingProfile _v;
bool resetCalled = false;
@override
Future<RoutingProfile> build() async => _v;
/// 绕过真实 _persist(需要 accountApiProvider/网络),只验证「确认后触发重置」的
/// UI 交互链路;真正的 _persist 复用行为由 routing_provider_test.dart 覆盖。
@override
Future<void> resetToDefault() async {
resetCalled = true;
state = AsyncData(RoutingProfile.defaults().copyWith(systemLockedDomains: _v.systemLockedDomains));
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
; 编译: ISCC.exe pangolin.iss (或用 Inno Setup Compiler 打开)
; 前置: 先在 client/ 跑 `flutter build windows`(Release),产物在
; ..\..\build\windows\x64\runner\Release
#define MyAppName "穿山甲 Pangolin"
#define MyAppName "Pangolin"
#define MyAppVersion "1.0.73"
#define MyAppPublisher "Pangolin"
#define MyAppExeName "pangolin_vpn.exe"
+40
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",
@@ -2257,6 +2273,30 @@
"ru": "Сбросить настройки",
"es": "Restablecer"
},
"routingResetConfirmTitle": {
"zh": "重置为默认规则?",
"en": "Reset to defaults?",
"ja": "デフォルトのルールに戻しますか?",
"ko": "기본 규칙으로 재설정할까요?",
"ru": "Сбросить к правилам по умолчанию?",
"es": "¿Restablecer las reglas predeterminadas?"
},
"routingResetConfirmBody": {
"zh": "将清除你自定义的所有规则,恢复到出厂分流表。",
"en": "This clears all your custom rules and restores the factory routing table.",
"ja": "カスタムルールをすべて削除し、出荷時の分流テーブルに戻します。",
"ko": "사용자 지정 규칙을 모두 삭제하고 초기 분산 규칙으로 복원합니다.",
"ru": "Это удалит все ваши пользовательские правила и восстановит заводскую таблицу маршрутизации.",
"es": "Esto borra todas tus reglas personalizadas y restaura la tabla de enrutamiento de fábrica."
},
"routingResetConfirmAction": {
"zh": "重置",
"en": "Reset",
"ja": "リセット",
"ko": "재설정",
"ru": "Сбросить",
"es": "Restablecer"
},
"routingBack": {
"zh": "返回设置",
"en": "Back to settings",
+30 -4
View File
@@ -244,10 +244,18 @@ components:
description: 国内域名/IP 直连
lan_direct:
type: boolean
description: 局域网直连
readOnly: true
description: >-
reserved/always-on:局域网直连由系统层恒渲染(route_exclude_address +
固定 LAN 直连规则),渲染器不读此开关,当前始终生效;字段保留供未来扩展
per-user 关闭,目前无实际效果。
private_via_tunnel:
type: boolean
description: 私有服务域名强制走隧道(家庭内网穿透场景)
readOnly: true
description: >-
reserved/always-on:配置了 PANGOLIN_PRIVATE_SPLIT_DOMAINS 时,这些私有
服务域名恒强制走隧道,渲染器不读此开关,当前始终生效;字段保留供未来扩展
per-user 关闭,目前无实际效果。
RoutingProfile:
type: object
@@ -267,6 +275,24 @@ components:
type: string
enum: [proxy, direct]
RoutingProfileResponse:
description: GET /me/routing 响应体:档案字段 + 只读的系统强制域名清单
allOf:
- $ref: '#/components/schemas/RoutingProfile'
- type: object
required: [system_locked_domains]
properties:
system_locked_domains:
type: array
readOnly: true
items:
type: string
description: >-
系统强制走隧道的私有服务域名(PANGOLIN_PRIVATE_SPLIT_DOMAINS)。
用户对这些域名的自定义规则会静默失效;仅供客户端提示用户,不可写入
(POST 请求体中出现该字段会被忽略,不会持久化)。
example: [nas.example.com]
RoutingValidationError:
type: object
required: [code, message_zh, message_en, errors]
@@ -500,11 +526,11 @@ paths:
summary: 获取当前用户的分流配置(可配置分流;未自定义时返回默认档案)
responses:
'200':
description: 分流档案
description: 分流档案(含只读 system_locked_domains
content:
application/json:
schema:
$ref: '#/components/schemas/RoutingProfile'
$ref: '#/components/schemas/RoutingProfileResponse'
'401':
description: 未认证
content:
+16
View File
@@ -6,6 +6,9 @@
export GOPROXY="${GOPROXY:-https://goproxy.cn,direct}"
export PUB_HOSTED_URL="${PUB_HOSTED_URL:-https://pub.flutter-io.cn}"
export FLUTTER_STORAGE_BASE_URL="${FLUTTER_STORAGE_BASE_URL:-https://storage.flutter-io.cn}"
# npm/npx 国内镜像:site 流水线(Astro 官网 + Next.js 用户中心 + npx wrangler)在
# 墙内 nas runner 上直连 registry.npmjs.org 会慢/抖断,与 Go/Flutter 同样需镜像。
export NPM_CONFIG_REGISTRY="${NPM_CONFIG_REGISTRY:-https://registry.npmmirror.com}"
# Forgejo/Gitea repo coordinates (used by lib-forgejo.sh). Secrets
# FORGEJO_TOKEN / FORGEJO_URL are injected by the CI runner, not set here.
@@ -44,3 +47,16 @@ flutter_pub_get_retry() {
echo "==> flutter pub get 5 次仍失败,放弃" >&2
return 1
}
# npm_ci_retry — 同理:npmmirror 偶发抖断时重试 `npm ci`。在含 package-lock.json 的
# 目录调用(site 各 web 子项目根)。已由 NPM_CONFIG_REGISTRY 指向国内镜像。
npm_ci_retry() {
local i
for i in 1 2 3 4 5; do
if npm ci; then return 0; fi
echo "==> npm ci 失败(第 ${i}/5 次,registry 抖?),8s 后重试..." >&2
sleep 8
done
echo "==> npm ci 5 次仍失败,放弃" >&2
return 1
}
+39 -1
View File
@@ -192,6 +192,12 @@ SE="${APP}/Contents/Library/SystemExtensions/${SYSEXT_BUNDLE_ID}.systemextension
[ -d "$SE" ] || { echo "ERROR: sysext bundle not found: ${SE}" >&2; exit 1; }
# ── [6/7] inside-out 重签(sysext → app frameworks → app),同 local_test.sh cmd_sign ──
# ⚠️ 这两份 entitlements 是最终产物的**真相源**——codesign --force 会覆盖 Xcode 用
# 仓库 .entitlements 打的签名。两边的 application-groups 必须同为 ${APP_GROUP}
# macOS 原生格式 <TeamID>.<name>,见 CLAUDE.md),且 sysext Info.plist 的
# NEMachServiceName 必须以它为前缀。曾因这里硬编码成 iOS 的 group. 前缀,导致
# nesessionmanager 报 NetworkExtensionErrorDomain Code=6、sysextd 校验失败当场
# 卸载新扩展,客户端永远建不出 VPN 配置(见 todo #28)。改这里请同步 local_test.sh。
cat > "${WORK}/app.entitlements" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -204,6 +210,8 @@ cat > "${WORK}/app.entitlements" <<PLIST
<key>com.apple.security.app-sandbox</key><false/>
<key>com.apple.security.network.client</key><true/>
<key>com.apple.security.network.server</key><true/>
<key>com.apple.security.application-groups</key>
<array><string>${APP_GROUP}</string></array>
<key>keychain-access-groups</key>
<array><string>${APP_GROUP}</string></array>
</dict></plist>
@@ -217,8 +225,12 @@ cat > "${WORK}/sysext.entitlements" <<PLIST
<key>com.apple.developer.networking.networkextension</key>
<array><string>packet-tunnel-provider-systemextension</string></array>
<key>com.apple.security.app-sandbox</key><true/>
<!-- 沙箱 sysext 必须显式网络权限才能对外建连/收发(同仓库 PacketTunnel.entitlements)。
曾漏掉这两键 → 隧道扩展被沙箱拒绝出站,连不上节点(v1.1.2 事故,连上隧道但不通)。 -->
<key>com.apple.security.network.client</key><true/>
<key>com.apple.security.network.server</key><true/>
<key>com.apple.security.application-groups</key>
<array><string>group.com.pangolin.pangolin</string></array>
<array><string>${APP_GROUP}</string></array>
</dict></plist>
PLIST
@@ -249,6 +261,32 @@ codesign --force --options runtime --timestamp \
codesign --verify --deep --strict --verbose=2 "$APP"
echo "==> compile-macos: signed + verified (${IDENTITY})"
# ── App Group / NEMachServiceName 一致性闸(读最终签名,不是仓库源文件)──────
# 规则没上闸 = 没有规则:这道闸就是为 todo #28 那次事故立的,放在公证前,
# 不一致直接 fail,避免把装不上的包公证并发出去。
echo "==> compile-macos: verifying App Group / NEMachServiceName consistency"
codesign -d --entitlements - --xml "$APP" > "${WORK}/app.signed.plist" 2>/dev/null || true
codesign -d --entitlements - --xml "$SE" > "${WORK}/se.signed.plist" 2>/dev/null || true
APP_G="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.application-groups:0' "${WORK}/app.signed.plist" 2>/dev/null || true)"
SE_G="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.application-groups:0' "${WORK}/se.signed.plist" 2>/dev/null || true)"
MACH="$(/usr/libexec/PlistBuddy -c 'Print :NetworkExtension:NEMachServiceName' "${SE}/Contents/Info.plist" 2>/dev/null || true)"
echo " app App Group : ${APP_G:-<missing>}"
echo " sysext App Group : ${SE_G:-<missing>}"
echo " NEMachServiceName: ${MACH:-<missing>}"
[ "$APP_G" = "$APP_GROUP" ] || { echo "ERROR: app App Group 应为 ${APP_GROUP},实为 ${APP_G:-<missing>}" >&2; exit 1; }
[ "$SE_G" = "$APP_GROUP" ] || { echo "ERROR: sysext App Group 应为 ${APP_GROUP},实为 ${SE_G:-<missing>}" >&2; exit 1; }
case "$MACH" in
"${APP_GROUP}"*) ;;
*) echo "ERROR: NEMachServiceName(${MACH:-<missing>}) 必须以 App Group(${APP_GROUP}) 为前缀,否则 sysextd 校验失败 Code=6" >&2; exit 1 ;;
esac
# 沙箱 sysext 无 network.client/server = 无权对外建连 → 隧道起了也连不上节点(v1.1.2 事故)。
SE_NC="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.network.client' "${WORK}/se.signed.plist" 2>/dev/null || true)"
SE_NS="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.network.server' "${WORK}/se.signed.plist" 2>/dev/null || true)"
echo " sysext network.client=${SE_NC:-<missing>} network.server=${SE_NS:-<missing>}"
[ "$SE_NC" = "true" ] || { echo "ERROR: sysext 缺 com.apple.security.network.client —— 沙箱扩展无权出站,隧道连不上节点" >&2; exit 1; }
[ "$SE_NS" = "true" ] || { echo "ERROR: sysext 缺 com.apple.security.network.server" >&2; exit 1; }
echo " OK: ${APP_GROUP}"
# ── [7/7] 公证(notarytoolAPI key 三件套) + staple + 打包 ──────────────────
echo "==> compile-macos: notarizing (notarytool submit --wait, ~1-5min)"
NOTARIZE_ZIP="${WORK}/notarize.zip"
+7 -4
View File
@@ -4,16 +4,19 @@
# web/website/astro.config.mjs) — must match the deploy target host name so
# canonical URLs / sitemap resolve correctly.
#
# Run inside a node:20 container by .gitea/workflows/deploy-site.yml; this
# script itself just runs npm and assumes it is invoked from the repo root.
# 由 .gitea/workflows/deploy-site.yml 在 ubuntu runner 上从 repo 根调用(runner
# 镜像自带 node/npx,直接跑)。source _env.sh 取 npm 国内镜像 + 重试助手(墙内)。
set -euo pipefail
# shellcheck source=scripts/ci/_env.sh
. scripts/ci/_env.sh
SITE_URL="${SITE_URL:-https://pangolin.yanmeiai.com}"
export SITE_URL
echo "==> compile-site: SITE_URL=${SITE_URL}"
echo "==> compile-site: SITE_URL=${SITE_URL} NPM_CONFIG_REGISTRY=${NPM_CONFIG_REGISTRY}"
cd web/website
npm ci
npm_ci_retry
npm run build
echo "==> compile-site: done — dist/ contents:"
+5 -2
View File
@@ -11,12 +11,15 @@
# 由 .gitea/workflows/deploy-site.yml 在 ubuntu runner 上调用,从 repo 根运行。
set -euo pipefail
# shellcheck source=scripts/ci/_env.sh
. scripts/ci/_env.sh
export NEXT_PUBLIC_API_MODE="${NEXT_PUBLIC_API_MODE:-http}"
export NEXT_PUBLIC_API_DOMAINS="${NEXT_PUBLIC_API_DOMAINS:-https://api.yanmeiai.com}"
echo "==> compile-usercenter: API_MODE=${NEXT_PUBLIC_API_MODE} API_DOMAINS=${NEXT_PUBLIC_API_DOMAINS}"
echo "==> compile-usercenter: API_MODE=${NEXT_PUBLIC_API_MODE} API_DOMAINS=${NEXT_PUBLIC_API_DOMAINS} NPM_CONFIG_REGISTRY=${NPM_CONFIG_REGISTRY}"
cd web/usercenter
npm ci
npm_ci_retry
npm run build
echo "==> compile-usercenter: done — out/ contents:"
+12
View File
@@ -52,6 +52,18 @@ install -m755 /tmp/pangolin-server "$BIN/pangolin-server"
install -m755 /tmp/pangolin-agent "$BIN/pangolin-agent"
install -m755 /tmp/pangolin-migrate "$BIN/pangolin-migrate"
install -m755 /tmp/pangolin-nodectl "$BIN/pangolin-nodectl"
# ── 控制面收口(幂等):HTTP API 只绑 loopback,经 cloudflared 隧道对外,关公网 8080 ──
# 现网 server.env 曾漂移成 ADDR=:8080(全网卡明文暴露 http://<公网IP>:8080,绕过 CF/TLS)。
# 这里在重启前把它纠回 127.0.0.1:8080 并撤掉 ufw 放行,随本次部署自动生效——不再手改线上。
# 幂等:仅当精确匹配公网形态 ADDR=:8080 才改;已收口则跳过。备份原文件。
if grep -qxF 'ADDR=:8080' /etc/pangolin/server.env; then
cp -p /etc/pangolin/server.env "/etc/pangolin/server.env.bak-addr-$TAG"
sed -i 's/^ADDR=:8080\$/ADDR=127.0.0.1:8080/' /etc/pangolin/server.env
echo "==> deploy-server: ADDR 收口 :8080 -> 127.0.0.1:8080"
fi
if command -v ufw >/dev/null 2>&1; then
ufw delete allow 8080/tcp >/dev/null 2>&1 || true
fi
systemctl start pangolin-server
systemctl is-active pangolin-server
REMOTE
+3
View File
@@ -10,6 +10,9 @@
# 由 compile-site.sh 先产出 web/website/dist/;从 repo 根调用。
set -euo pipefail
# shellcheck source=scripts/ci/_env.sh
. scripts/ci/_env.sh # NPM_CONFIG_REGISTRY:让 `npx wrangler@4` 从国内镜像拉包
if [ ! -d web/website/dist ]; then
echo "==> deploy-site: web/website/dist/ 不存在 — 拒绝部署" >&2
exit 1
+82 -13
View File
@@ -11,6 +11,7 @@
# copy 覆盖安装到 /Applications
# run 直跑 /Applications 版本(绕 Gatekeeper,实时输出日志,并打印测试账号)
# all 依次执行 build → sign → copy → run
# macos 一条龙(推荐):递增构建号 → build → App Group 一致性闸 → 公证 → 装 → 跑
#
# ── iOS / iPad 真机(USB 连接;与上面 macOS 流程完全独立)──
# ios-devices 列出已连接的 iOS 物理设备(拿 device id)
@@ -23,9 +24,10 @@
set -euo pipefail
# ─────────── 配置(按需改)───────────
# 联调控制面。默认指向联调节点;要装生产地址的包用 env 覆盖:
# API_URL=https://api.yanmeiai.com scripts/local_test.sh ipad
API_URL="${API_URL:-http://103.119.13.48:8080}"
# 控制面基址。默认生产(Cloudflare Tunnel);8080 已收口只绑 127.0.0.1,公网直连
# 不再可用——联调自建控制面时用 env 显式覆盖:
# API_URL=http://<联调地址>:8080 scripts/local_test.sh macos
API_URL="${API_URL:-https://api.yanmeiai.com}"
SIGN_ID="Developer ID Application: Yanmei (beijing) Technology Co., Ltd (BYL4KQHMTN)"
APP_PROFILE_NAME="Pangolin App DevID" # 主 app 的 Developer ID 描述文件名
SE_PROFILE_NAME="Pangolin PacketTunnel DevID" # PacketTunnel 的描述文件名
@@ -38,8 +40,12 @@ IP_SVC="https://api.ipify.org" # 返回纯文本公网 IP
# 注:DevID profile 已含 system-extension.install + NE(-systemextension 变体);
# app/sysext entitlements 与之对齐(见 write_entitlements)。
# ── iOS/iPad 真机分发(ad-hoc,**公司**证书)────────────────────────────────
TEAM_ID="BYL4KQHMTN" # Yanmei (beijing) Technology Co., Ltd
# macOS App Group —— 必须是原生格式 <TeamID>.<name>,不是 iOS 的 group. 前缀(CLAUDE.md 铁律)。
# 主 app 与 sysext 必须落在**同一个**;sysext 的 NEMachServiceName 必须以它为前缀。
APP_GROUP="${TEAM_ID}.com.pangolin.pangolin"
# ── iOS/iPad 真机分发(ad-hoc,**公司**证书)────────────────────────────────
IOS_BUNDLE_ID="com.pangolin.pangolinVpn"
# 期望的签名主体。装机前逐字核对,不符即中止 —— 防止悄悄退回个人开发证书。
IOS_EXPECT_SIGNER="Apple Distribution: Yanmei (beijing) Technology Co., Ltd (${TEAM_ID})"
@@ -49,6 +55,7 @@ SRC="${BASH_SOURCE[0]}"
DIR="${SRC%/*}"; [ "$DIR" = "$SRC" ] && DIR="."
cd "$DIR/.."; REPO_ROOT="$PWD"
CLIENT="$REPO_ROOT/client"
PBXPROJ="$CLIENT/macos/Runner.xcodeproj/project.pbxproj"
APP="$CLIENT/build/macos/Build/Products/Release/pangolin_vpn.app"
# sysext bundle 名 = 标识符(PRODUCT_NAME=com.pangolin.pangolin.PacketTunnel,见 CLAUDE.md),
# 不是短名 PacketTunnel.systemextension。
@@ -73,38 +80,96 @@ find_profile(){
return 1
}
# ⚠️ 两份 entitlements 的 application-groups 必须**同值**且等于 $APP_GROUP。
# 历史事故:sysext 这份曾硬编码成 iOS 的 group. 前缀,与 Info.plist 的
# NEMachServiceName(<TeamID>. 前缀)对不上 → nesessionmanager 报
# NetworkExtensionErrorDomain Code=6 → sysextd 校验失败当场卸载新扩展 →
# VpnChannel.start() 卡在 step① 永远建不出 VPN 配置。改这里务必同步 compile-macos.sh。
write_entitlements(){
cat > "$WORK/app.entitlements" <<'PLIST'
cat > "$WORK/app.entitlements" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>com.apple.application-identifier</key><string>BYL4KQHMTN.com.pangolin.pangolin</string>
<key>com.apple.developer.team-identifier</key><string>BYL4KQHMTN</string>
<key>com.apple.application-identifier</key><string>${TEAM_ID}.com.pangolin.pangolin</string>
<key>com.apple.developer.team-identifier</key><string>${TEAM_ID}</string>
<key>com.apple.developer.system-extension.install</key><true/>
<key>com.apple.developer.networking.networkextension</key>
<array><string>packet-tunnel-provider-systemextension</string></array>
<key>com.apple.security.app-sandbox</key><false/>
<key>com.apple.security.network.client</key><true/>
<key>com.apple.security.network.server</key><true/>
<key>com.apple.security.application-groups</key>
<array><string>${APP_GROUP}</string></array>
<key>keychain-access-groups</key>
<array><string>BYL4KQHMTN.com.pangolin.pangolin</string></array>
<array><string>${TEAM_ID}.com.pangolin.pangolin</string></array>
</dict></plist>
PLIST
cat > "$WORK/sysext.entitlements" <<'PLIST'
cat > "$WORK/sysext.entitlements" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>com.apple.application-identifier</key><string>BYL4KQHMTN.com.pangolin.pangolin.PacketTunnel</string>
<key>com.apple.developer.team-identifier</key><string>BYL4KQHMTN</string>
<key>com.apple.application-identifier</key><string>${TEAM_ID}.com.pangolin.pangolin.PacketTunnel</string>
<key>com.apple.developer.team-identifier</key><string>${TEAM_ID}</string>
<key>com.apple.developer.networking.networkextension</key>
<array><string>packet-tunnel-provider-systemextension</string></array>
<key>com.apple.security.app-sandbox</key><true/>
<!-- 沙箱 sysext 必须显式网络权限才能对外建连(同仓库 PacketTunnel.entitlements;
v1.1.2 CI 重签漏掉这两键 → 隧道连不上节点)。 -->
<key>com.apple.security.network.client</key><true/>
<key>com.apple.security.network.server</key><true/>
<key>com.apple.security.application-groups</key>
<array><string>group.com.pangolin.pangolin</string></array>
<array><string>${APP_GROUP}</string></array>
</dict></plist>
PLIST
}
# ── App Group 一致性闸(装机前拦截,规则没上闸 = 没有规则)────────────────────
# 读**最终产物的签名**(不是仓库里的 .entitlements 源文件),因为真正决定成败的是
# 签进去的那份;Xcode 与重签脚本都可能覆盖它。
verify_app_group(){
[ -d "$APP" ] || die "先 build:找不到 $APP"
[ -d "$SE" ] || die "找不到 sysext: $SE"
log "App Group / NEMachServiceName 一致性闸"
codesign -d --entitlements - --xml "$APP" > "$WORK/app.ents.plist" 2>/dev/null || true
codesign -d --entitlements - --xml "$SE" > "$WORK/se.ents.plist" 2>/dev/null || true
local app_g se_g mach
app_g="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.application-groups:0' "$WORK/app.ents.plist" 2>/dev/null || true)"
se_g="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.application-groups:0' "$WORK/se.ents.plist" 2>/dev/null || true)"
mach="$(/usr/libexec/PlistBuddy -c 'Print :NetworkExtension:NEMachServiceName' "$SE/Contents/Info.plist" 2>/dev/null || true)"
echo " 主 app App Group : ${app_g:-<缺失>}"
echo " sysext App Group : ${se_g:-<缺失>}"
echo " NEMachServiceName: ${mach:-<缺失>}"
[ -n "$app_g" ] || die "主 app 缺 com.apple.security.application-groups —— 与扩展无法共享容器/Mach 通道"
[ -n "$se_g" ] || die "sysext 缺 com.apple.security.application-groups"
[ "$app_g" = "$APP_GROUP" ] || die "主 app App Group 应为 $APP_GROUP,实为 $app_g"
[ "$se_g" = "$APP_GROUP" ] || die "sysext App Group 应为 $APP_GROUP,实为 $se_g"
case "$mach" in
"$APP_GROUP"*) ;;
*) die "NEMachServiceName($mach)必须以 App Group($APP_GROUP)为前缀,否则 sysextd 校验失败 Code=6" ;;
esac
# 沙箱 sysext 无 network.client/server = 无权对外建连 → 隧道起了也连不上节点(v1.1.2 事故)。
local se_nc se_ns
se_nc="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.network.client' "$WORK/se.ents.plist" 2>/dev/null || true)"
se_ns="$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.network.server' "$WORK/se.ents.plist" 2>/dev/null || true)"
echo " sysext network.client=${se_nc:-<缺失>} network.server=${se_ns:-<缺失>}"
[ "$se_nc" = "true" ] || die "sysext 缺 com.apple.security.network.client —— 沙箱扩展无权出站,隧道连不上节点"
[ "$se_ns" = "true" ] || die "sysext 缺 com.apple.security.network.server"
echo " ✅ 一致($APP_GROUP)"
}
# ── 递增 sysext 的 CFBundleVersion ───────────────────────────────────────
# PacketTunnel target 不吃 FLUTTER_BUILD_NUMBER,版本号是 project.pbxproj 里写死的
# CURRENT_PROJECT_VERSION。不递增 → sysextd 视为同版本**不更新**,装上去跑的还是旧扩展
# (CLAUDE.md「每次构建必递增 CFBundleVersion」)。与 compile-macos.sh 同法 sed 全量替换。
cmd_bump_build(){
local cur next
cur="$(grep -m1 -E 'CURRENT_PROJECT_VERSION = [0-9]+;' "$PBXPROJ" | tr -dc '0-9')"
[ -n "$cur" ] || die "读不到 CURRENT_PROJECT_VERSION: $PBXPROJ"
next=$((cur + 1))
sed -i '' -E "s/CURRENT_PROJECT_VERSION = [0-9]+;/CURRENT_PROJECT_VERSION = ${next};/g" "$PBXPROJ"
log "sysext 构建号 ${cur}${next}"
}
cs(){ codesign --force --options runtime --timestamp "$@"; }
cmd_build(){
@@ -386,10 +451,14 @@ case "${1:-}" in
run) cmd_run ;;
# Xcode 工程已配 Developer ID 手动签名(Release 配置),build 即出 DevID 包,无需 sign。
all) cmd_build; cmd_notarize; cmd_copy; cmd_run ;;
# 装机一条龙。比 all 多两步:①先递增 sysext 构建号(否则 sysextd 不换扩展)
# ②公证前过 App Group 一致性闸(不一致直接中止,别浪费 1-5 分钟公证)。
macos) cmd_bump_build; cmd_build; verify_app_group; cmd_notarize; cmd_copy; cmd_run ;;
verify) verify_app_group ;; # 只跑一致性闸(不构建),排障用
ks-baseline) cmd_ks_baseline ;; # ① VPN 断开下记录真实公网 IP
ks-test) cmd_ks_test ;; # ② VPN 连接(killswitch 开)下杀扩展做漏测
ks-status) cmd_ks_status ;; # 看 VPN 状态 + killswitch 配置打点日志
ios-devices) cmd_ios_devices ;; # 列出已连接的 iOS 物理设备(拿 device id)
ipad|ios) cmd_ipad "${2:-}" ;; # 构建 iOS release 并装到 iPad(可传设备 id/名字子串)
*) echo "用法: $0 {all|build|sign|notarize|copy|run|ks-baseline|ks-test|ks-status|ios-devices|ipad [id]}"; exit 2 ;;
*) echo "用法: $0 {macos|all|build|sign|verify|notarize|copy|run|ks-baseline|ks-test|ks-status|ios-devices|ipad [id]}"; exit 2 ;;
esac
+30 -4
View File
@@ -259,11 +259,11 @@ paths:
tags: [Account]
responses:
"200":
description: 分流档案
description: 分流档案(含只读 system_locked_domains
content:
application/json:
schema:
$ref: "#/components/schemas/RoutingProfile"
$ref: "#/components/schemas/RoutingProfileResponse"
"401":
$ref: "#/components/responses/Unauthorized"
"500":
@@ -1209,10 +1209,18 @@ components:
description: 国内域名/IP 直连
lan_direct:
type: boolean
description: 局域网直连
readOnly: true
description: >-
reserved/always-on:局域网直连由系统层恒渲染(route_exclude_address +
固定 LAN 直连规则),渲染器不读此开关,当前始终生效;字段保留供未来扩展
per-user 关闭,目前无实际效果。
private_via_tunnel:
type: boolean
description: 私有服务域名强制走隧道(家庭内网穿透场景)
readOnly: true
description: >-
reserved/always-on:配置了 PANGOLIN_PRIVATE_SPLIT_DOMAINS 时,这些私有
服务域名恒强制走隧道,渲染器不读此开关,当前始终生效;字段保留供未来扩展
per-user 关闭,目前无实际效果。
RoutingProfile:
type: object
@@ -1232,6 +1240,24 @@ components:
type: string
enum: [proxy, direct]
RoutingProfileResponse:
description: GET /me/routing 响应体:档案字段 + 只读的系统强制域名清单
allOf:
- $ref: "#/components/schemas/RoutingProfile"
- type: object
required: [system_locked_domains]
properties:
system_locked_domains:
type: array
readOnly: true
items:
type: string
description: >-
系统强制走隧道的私有服务域名(PANGOLIN_PRIVATE_SPLIT_DOMAINS)。
用户对这些域名的自定义规则会静默失效;仅供客户端提示用户,不可写入
(POST 请求体中出现该字段会被忽略,不会持久化)。
example: [nas.example.com]
RoutingValidationError:
type: object
required: [code, message_zh, message_en, errors]
+17 -12
View File
@@ -48,14 +48,16 @@ import (
)
func main() {
listenAddr := flag.String("addr", "", "HTTP listen address (default :8080, overridden by ADDR env)")
listenAddr := flag.String("addr", "", "HTTP listen address (default 127.0.0.1:8080, overridden by ADDR env)")
flag.Parse()
if *listenAddr == "" {
if v := os.Getenv("ADDR"); v != "" {
*listenAddr = v
} else {
*listenAddr = ":8080"
// 默认只绑 loopback:控制面对外一律经 cloudflared 隧道(见 CLAUDE.md),
// 源站不该裸监听公网。要跨主机监听须显式设 ADDR=:8080(明知代价)。
*listenAddr = "127.0.0.1:8080"
}
}
@@ -408,7 +410,18 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
accountAPI := httpapi.NewAccountAPI(sqlDB)
// ── Routing profile (可配置分流) ───────────────────────────────────────────
routingAPI := httpapi.NewRoutingAPI(routing.NewStore(sqlDB))
// 私有服务域名分流(家庭内网穿透,如 nas/git/win.yanmeiai.com):逗号分隔;
// 这些域名用系统 DNS 解析、在外强制走隧道(排在国内分流前)。用户对这些域名的
// 自定义规则会静默失效——同一份 slice 注入 RoutingAPI,GET /v1/me/routing
// 附带 system_locked_domains 供客户端提示,以及 NodeAPI(渲染 sing-box 配置)。
var privateSplitDomains []string
for _, d := range strings.Split(os.Getenv("PANGOLIN_PRIVATE_SPLIT_DOMAINS"), ",") {
if d = strings.TrimSpace(d); d != "" {
privateSplitDomains = append(privateSplitDomains, d)
}
}
routingStore := routing.NewStore(sqlDB)
routingAPI := httpapi.NewRoutingAPI(routingStore, privateSplitDomains)
// ── Nodes + Connect ───────────────────────────────────────────────────────
var nodeAPI *httpapi.NodeAPI
@@ -423,15 +436,7 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
slog.Warn("PANGOLIN_PUBLIC_URL 未设置:国内分流(split_cn)将被静默跳过,客户端全量走隧道。" +
"如需国内直连,设为控制面对外公网基址(如 http://<公网IP>:8080)")
}
// 私有服务域名分流(家庭内网穿透,如 nas/git/win.yanmeiai.com):
// 逗号分隔;这些域名用系统 DNS 解析、在外强制走隧道(排在国内分流前)。
var privateSplitDomains []string
for _, d := range strings.Split(os.Getenv("PANGOLIN_PRIVATE_SPLIT_DOMAINS"), ",") {
if d = strings.TrimSpace(d); d != "" {
privateSplitDomains = append(privateSplitDomains, d)
}
}
nodeAPI = httpapi.NewNodeAPI(nodeStore, nodeSvc.Hub(), nodeSvc.Load(), os.Getenv("NODE_DERIVE_KEY"), publicURL, privateSplitDomains, routing.NewStore(sqlDB))
nodeAPI = httpapi.NewNodeAPI(nodeStore, nodeSvc.Hub(), nodeSvc.Load(), os.Getenv("NODE_DERIVE_KEY"), publicURL, privateSplitDomains, routingStore)
}
// 国内分流(#5)的 rule-set 静态服务:GET /v1/rules/{name}.srs(自托管,
+26 -15
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 时静默
@@ -270,9 +274,15 @@ func BuildClientConfig(node *nodes.NodeRow, dpUUID, deriveKey string, opts Clien
if len(extraExclude) > 0 {
// IP 直连真生效:并入 TUN 入站的 route_exclude_address(auto_route 层排除,
// 见 tunIn 构造处注释——单靠 route.rules 的 ip_cidr→direct 在 macOS
// strict_route 下不生效)。与既有 LAN 网段去重合并。
exclude := []string{"192.168.0.0/16", "10.0.0.0/8"}
seen := map[string]bool{"192.168.0.0/16": true, "10.0.0.0/8": true}
// strict_route 下不生效)。单源读 tunIn 现有种子(不重复硬编码 LAN 网段;
// 其为 192.168+10,与上面 route.rules 的 LAN 直连 4 段有意不同——不能改成
// LAN 全集,否则会漏排除/多排除),与 extraExclude 去重合并、写回。
base, _ := tunIn["route_exclude_address"].([]string)
exclude := append([]string{}, base...)
seen := make(map[string]bool, len(base))
for _, e := range base {
seen[e] = true
}
for _, e := range extraExclude {
if !seen[e] {
seen[e] = true
@@ -374,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"
@@ -64,6 +64,19 @@ func openRoutingDB(t *testing.T) *sql.DB {
return db
}
// seedConnectUser inserts a minimal users row so routing_profiles inserts
// (which now declare FOREIGN KEY (user_id) REFERENCES users(id)) satisfy the
// constraint — this DB opens with _pragma=foreign_keys(1) (internal/db/db.go),
// so SQLite does enforce it, unlike a bare default SQLite connection.
func seedConnectUser(t *testing.T, db *sql.DB, id int64) {
t.Helper()
uuid := "u-connect"
if _, err := db.Exec(`INSERT INTO users (id,uuid,email,pw_hash,dp_uuid,status,created_at)
VALUES (?,?,?, 'x','dp-'||?, 'active', ?)`, id, uuid, uuid+"@x", uuid, time.Now().UTC()); err != nil {
t.Fatal(err)
}
}
// newOnlineHub returns a real *nodes.Hub (backed by miniredis) with nodeUUID
// registered online, so ConnectNode's a.hub.IsOnline(...) gate passes and
// Push(...) succeeds without a real Redis deployment.
@@ -98,6 +111,7 @@ func TestConnectNode_ReadsRoutingProfile(t *testing.T) {
const uid = int64(42)
db := openRoutingDB(t)
seedConnectUser(t, db, uid)
rst := routing.NewStore(db)
p := routing.Default()
p.Rules = []routing.Rule{
@@ -167,6 +181,7 @@ func TestConnectNode_RoutingStoreErr_FailsSafe(t *testing.T) {
const uid = int64(44)
db := openRoutingDB(t)
seedConnectUser(t, db, uid)
// 写入一条无法反序列化的 profile_json,模拟 Get 出错。
if _, err := db.Exec(`INSERT INTO routing_profiles (user_id, profile_json, updated_at) VALUES (?,?,?)`,
uid, "{not-json", time.Now().UTC()); err != nil {
+24 -2
View File
@@ -14,10 +14,28 @@ import (
// user hasn't customized one yet; POST validates and upserts.
type RoutingAPI struct {
store *routing.Store
// lockedDomains are the system-forced-tunnel private-service domains
// (PANGOLIN_PRIVATE_SPLIT_DOMAINS, same slice injected into NodeAPI) —
// read-only, surfaced to GET so clients can warn users that rules against
// these domains silently have no effect. Never written to the persisted
// Profile.
lockedDomains []string
}
// NewRoutingAPI creates a RoutingAPI backed by the given routing.Store.
func NewRoutingAPI(store *routing.Store) *RoutingAPI { return &RoutingAPI{store: store} }
// lockedDomains is the system-forced private-service domain list (may be nil).
func NewRoutingAPI(store *routing.Store, lockedDomains []string) *RoutingAPI {
return &RoutingAPI{store: store, lockedDomains: lockedDomains}
}
// profileResponse wraps routing.Profile for GET /v1/me/routing, adding the
// read-only system_locked_domains list. It deliberately lives here — not on
// routing.Profile itself — so the field can never leak into the writable
// Profile contract that SaveProfile decodes POST bodies into.
type profileResponse struct {
*routing.Profile
SystemLockedDomains []string `json:"system_locked_domains"`
}
// GetProfile handles GET /v1/me/routing.
func (a *RoutingAPI) GetProfile(w http.ResponseWriter, r *http.Request) {
@@ -34,7 +52,11 @@ func (a *RoutingAPI) GetProfile(w http.ResponseWriter, r *http.Request) {
if p == nil {
p = routing.Default()
}
writeJSON(w, http.StatusOK, p)
locked := a.lockedDomains
if locked == nil {
locked = []string{}
}
writeJSON(w, http.StatusOK, profileResponse{Profile: p, SystemLockedDomains: locked})
}
// SaveProfile handles POST /v1/me/routing. On validation failure it returns
+81 -2
View File
@@ -65,7 +65,7 @@ func doAuthReq(t *testing.T, method, target string, body *strings.Reader, uid in
func TestRoutingGetDefaultThenSave(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 7)
api := NewRoutingAPI(routing.NewStore(db))
api := NewRoutingAPI(routing.NewStore(db), nil)
// GET 无档案 → 200 + Default
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 7, api.GetProfile)
@@ -120,7 +120,7 @@ func TestRoutingGetDefaultThenSave(t *testing.T) {
func TestRoutingGetUnauthorized(t *testing.T) {
db := openRoutingTestDB(t)
api := NewRoutingAPI(routing.NewStore(db))
api := NewRoutingAPI(routing.NewStore(db), nil)
req := httptest.NewRequest(http.MethodGet, "/v1/me/routing", nil)
rr := httptest.NewRecorder()
api.GetProfile(rr, req)
@@ -128,3 +128,82 @@ func TestRoutingGetUnauthorized(t *testing.T) {
t.Fatalf("expected 401, got %d", rr.Code)
}
}
// TestRoutingGetExposesSystemLockedDomains: GET must surface the injected
// lockedDomains list under system_locked_domains, without it ever ending up
// as part of routing.Profile's own field set.
func TestRoutingGetExposesSystemLockedDomains(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 8)
api := NewRoutingAPI(routing.NewStore(db), []string{"nas.x.com"})
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 8, api.GetProfile)
if rr.Code != 200 {
t.Fatalf("GET code %d", rr.Code)
}
var resp struct {
SystemLockedDomains []string `json:"system_locked_domains"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(resp.SystemLockedDomains) != 1 || resp.SystemLockedDomains[0] != "nas.x.com" {
t.Fatalf("want system_locked_domains=[nas.x.com], got %v", resp.SystemLockedDomains)
}
}
// TestRoutingGetSystemLockedDomainsNilBecomesEmptyArray: a nil lockedDomains
// slice (no PANGOLIN_PRIVATE_SPLIT_DOMAINS configured) must serialize as
// `[]`, not `null` — clients shouldn't need a nil-check.
func TestRoutingGetSystemLockedDomainsNilBecomesEmptyArray(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 9)
api := NewRoutingAPI(routing.NewStore(db), nil)
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 9, api.GetProfile)
if rr.Code != 200 {
t.Fatalf("GET code %d", rr.Code)
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(rr.Body.Bytes(), &raw); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if got := string(raw["system_locked_domains"]); got != "[]" {
t.Fatalf("want system_locked_domains=`[]`, got %s", got)
}
}
// TestRoutingSaveIgnoresSystemLockedDomains: a client POSTing a body that
// includes system_locked_domains must not have it persisted — SaveProfile
// decodes straight into routing.Profile, which has no such field, so the
// key is silently dropped. Verify against the raw stored row (not the GET
// response, which always injects it from a.lockedDomains regardless of what
// was ever saved).
func TestRoutingSaveIgnoresSystemLockedDomains(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 10)
store := routing.NewStore(db)
api := NewRoutingAPI(store, []string{"nas.x.com"})
body := `{"mode":"rule","builtin":{"china_direct":true,"lan_direct":true,"private_via_tunnel":true},` +
`"rules":[],"final":"proxy","system_locked_domains":["evil.attacker.com"]}`
rr := doAuthReq(t, http.MethodPost, "/v1/me/routing", strings.NewReader(body), 10, api.SaveProfile)
if rr.Code != 200 {
t.Fatalf("POST code %d body %s", rr.Code, rr.Body)
}
stored, err := store.Get(context.Background(), 10)
if err != nil {
t.Fatal(err)
}
if stored == nil {
t.Fatal("expected a persisted profile")
}
raw, err := json.Marshal(stored)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(raw), "system_locked_domains") || strings.Contains(string(raw), "evil.attacker.com") {
t.Fatalf("system_locked_domains must never be persisted, got stored profile JSON: %s", raw)
}
}
+68 -9
View File
@@ -21,8 +21,17 @@ type Rule struct {
// Builtin toggles the built-in routing behaviors that previously were
// hardcoded into the server's sing-box config rendering.
type Builtin struct {
ChinaDirect bool `json:"china_direct"`
LanDirect bool `json:"lan_direct"`
ChinaDirect bool `json:"china_direct"`
// LanDirect is reserved/always-on: the system layer (route_exclude_address
// + the hardcoded LAN direct rule in clientconfig.go) renders unconditionally
// regardless of this flag's value — the renderer does not read it. Kept in
// the wire contract for a possible future per-user opt-out; today it has no
// effect on rendering.
LanDirect bool `json:"lan_direct"`
// PrivateViaTunnel is reserved/always-on: when PANGOLIN_PRIVATE_SPLIT_DOMAINS
// is configured, those domains are always force-routed through the tunnel —
// the renderer does not read this flag. Kept in the wire contract for a
// possible future per-user opt-out; today it has no effect on rendering.
PrivateViaTunnel bool `json:"private_via_tunnel"`
}
@@ -62,13 +71,47 @@ 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
// (nil) slice when the profile is valid; every violation is reported
// independently (no short-circuiting) so callers can surface all errors at
// once.
// (non-nil) slice when the profile is valid — so JSON encoding produces `[]`
// rather than `null` — and every violation is reported independently (no
// short-circuiting) so callers can surface all errors at once.
func (p *Profile) Validate() []FieldError {
var errs []FieldError
errs := []FieldError{}
if p.Mode != "rule" && p.Mode != "global" && p.Mode != "direct" {
errs = append(errs, FieldError{-1, "mode", "must be rule|global|direct"})
}
@@ -90,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)] {
@@ -102,14 +155,20 @@ func (p *Profile) Validate() []FieldError {
return errs
}
// dedupKey identifies a rule for Normalize's de-duplication. Using a struct
// (rather than string-concatenating Type+Value+Action with a separator)
// avoids false-collision when a value itself contains the separator
// character.
type dedupKey struct{ Type, Value, Action string }
// Normalize trims rule values and de-duplicates rules by (type, value,
// action), keeping the first occurrence's position (and its Note/Enabled).
func (p *Profile) Normalize() {
seen := map[string]bool{}
seen := map[dedupKey]bool{}
out := p.Rules[:0]
for _, r := range p.Rules {
r.Value = strings.TrimSpace(r.Value)
k := r.Type + "|" + r.Value + "|" + r.Action
k := dedupKey{r.Type, r.Value, r.Action}
if seen[k] {
continue
}
+68 -2
View File
@@ -1,13 +1,32 @@
package routing
import "testing"
import (
"encoding/json"
"testing"
)
// TestValidateEmptyErrorsSerializeAsArray guards the JSON shape API clients
// depend on: a valid profile's Validate() must marshal to `[]`, not `null`.
func TestValidateEmptyErrorsSerializeAsArray(t *testing.T) {
raw, err := json.Marshal(Default().Validate())
if err != nil {
t.Fatal(err)
}
if string(raw) != "[]" {
t.Fatalf("want `[]`, got %s", raw)
}
}
func TestValidate(t *testing.T) {
ok := Default()
ok.Rules = []Rule{{Type: "domain_suffix", Value: "example.com", Action: "direct", Enabled: true}}
if e := ok.Validate(); len(e) != 0 {
e := ok.Validate()
if len(e) != 0 {
t.Fatalf("valid profile got errors %v", e)
}
if e == nil {
t.Fatal("Validate must return a non-nil empty slice (serializes to [] not null)")
}
bad := Default()
bad.Mode = "weird" // 非法 mode
@@ -23,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++ {
@@ -48,3 +98,19 @@ func TestNormalizeDedupAndTrim(t *testing.T) {
t.Fatalf("want first-occurrence order preserved, got %v", p.Rules)
}
}
// TestNormalizeDedupNoSeparatorCollision guards against the historical
// string-concatenation dedup key ("type|value|action"): two distinct rules
// whose Value contains "|" could concatenate to the same string even though
// (type, value, action) differ. The struct-keyed dedup must tell them apart.
func TestNormalizeDedupNoSeparatorCollision(t *testing.T) {
p := Default()
p.Rules = []Rule{
{Type: "domain", Value: "a|b", Action: "proxy", Enabled: true},
{Type: "domain", Value: "a", Action: "b|proxy", Enabled: true},
}
p.Normalize()
if len(p.Rules) != 2 {
t.Fatalf("want 2 distinct rules preserved (no false collision), got %d: %v", len(p.Rules), p.Rules)
}
}
@@ -32,6 +32,27 @@ func seedU(t *testing.T, db *sql.DB, id int64, uuid string) {
}
}
// TestSQLiteRoutingStoreGetNoProfileRow isolates the "queried the DB, found
// no row" path from TestSQLiteRoutingStoreUpsertGet's combined
// empty→upsert→overwrite flow: a store backed by a real (non-nil) *sql.DB,
// with the user seeded but no routing_profiles row for them, must return
// (nil, nil) — not an error — via the sql.ErrNoRows branch in Store.Get.
func TestSQLiteRoutingStoreGetNoProfileRow(t *testing.T) {
db := openDB(t)
seedU(t, db, 2, "u2")
st := NewStore(db)
if st == nil {
t.Fatal("NewStore returned nil")
}
got, err := st.Get(context.Background(), 2)
if err != nil {
t.Fatalf("want nil error for no-rows, got %v", err)
}
if got != nil {
t.Fatalf("want nil profile for seeded user with no profile row, got %+v", got)
}
}
func TestSQLiteRoutingStoreUpsertGet(t *testing.T) {
db := openDB(t) // 内存库 + MigrateUp(sqlite)
seedU(t, db, 1, "u1")
@@ -104,29 +104,12 @@ func TestCodesLibMigrateRoundTrip(t *testing.T) {
// the reviewer's repro hit: the lib's `codes` table collides with the
// name 000022's down script renames legacy_codes back to.
m := newSQLiteStepper(t, db)
// 000027 (pay_promo_paid_unique), 000026 (notices), 000025
// (user_device_limit_override), 000024 (invite_rewards) and 000023
// (pay_purchases/source-enum) now sit on top of 000022
// (codes_lib_legacy_rename) and are unrelated to this collision — step
// them back down first so we land exactly on the 000022 boundary the
// test targets.
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000027 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000026 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000025 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000024 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000023 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000022 down: %v (this is the reviewer-reported collision — "+
// 所有排在 000022 之上的迁移(000023..最新,如 pay_purchases / invite_rewards /
// notices / routing_profiles …)都与本冲突无关 —— 一次性降到版本 21,恰好落在
// 000022(codes_lib_legacy_rename)down 之后的边界。用版本号显式定位而非硬编码
// Steps(-1) 计数,避免栈顶新增迁移(如 000028)后步数漂移、跳过 000022 down。
if err := m.Migrate(21); err != nil {
t.Fatalf("migrate down to v21 (past 000022 down): %v (this is the reviewer-reported collision — "+
"000022 down must DROP the codes-lib tables before renaming legacy_* back)", err)
}
@@ -1,5 +1,6 @@
CREATE TABLE routing_profiles (
user_id INTEGER NOT NULL PRIMARY KEY,
profile_json TEXT NOT NULL,
updated_at DATETIME NOT NULL
updated_at DATETIME NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
+250 -32
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-09 · 真相源 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>29</strong>全部</div>
<div class="stat-pill"><strong>15</strong>待开始</div>
<div class="stat-pill"><strong>0</strong>开发中</div>
<div class="stat-pill"><strong>6</strong>待验收</div>
<div class="stat-pill"><strong>8</strong>已验收</div>
</div>
@@ -376,12 +376,43 @@ 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">15</span>
<span class="s-arrow">▴ 收起</span>
</div>
<div class="section-list-wrap " id="list-wrap-open">
<ul class="todo-list" id="list-open">
<li class="todo-card s-open"
data-id="29"
data-level="high"
data-status="open"
data-tier="2"
data-tags="Windows,后端">
<div class="card-header">
<span class="item-id">#29</span>
<span class="item-title">Windows 端 chenxin 设备连接凭据已过期,需重新签发并补过期处理</span>
<div class="card-badges">
<span class="tag status-badge s-open">待开始</span>
<span class="tag t-block">高优 · 紧急</span>
<span class="tag tier-2">二级</span>
</div>
</div>
<div class="item-desc">设备 Win·chenxindevices.id=25dp_uuid 019f599b-d11a-7763-9099-9935f4b49070client_version v1.0.72)的 connect_credentials 已于 2026-08-01 18:19 UTC 过期,agent 随后把它从 /etc/sing-box/config.json 的 reality-in users 里清掉了(当前只剩 019f55d6 和 019f8c8f 两个)。客户端对此无感知,持续高频重连,sing-box 一路报 REALITY: processed invalid connection。实测最近 2 小时该出口 IP 124.88.8.196 刷了 1801 条失败日志,占服务端全部握手失败的约 99%,把真正的故障信号淹没了(这次排查 Mac 问题时一度被误导)。处理项:1) 先给该 dp_uuid 重新签发凭据,恢复 chenxin 可用;2) 查清为什么它没像 Mac 那样自动续期成功——Mac 的 019f55d6 已续到 2026-08-09,说明续期链路本身是通的,怀疑 v1.0.72 版本客户端的续期逻辑有缺陷或登录态已失效;3) 客户端在凭据过期时应给出明确提示并做退避重试,而不是无限高频重连;4) 服务端对同一 dp_uuid 的连续握手失败做限频或告警,避免单台故障设备淹没日志。</div>
<div class="card-footer">
<div class="tag-row"><span class="tag t-tag" data-tag="Windows">Windows</span> <span class="tag t-tag" data-tag="后端">后端</span></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-08-08</span>
</div>
</div>
</li>
<li class="todo-card s-open"
data-id="1"
data-level="mid"
@@ -630,6 +661,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"
@@ -660,43 +815,33 @@ header .header-meta{color:var(--fg-soft)}
</div>
</div>
</li>
</ul>
</div>
</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-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="">
<li class="todo-card s-open"
data-id="30"
data-level="low"
data-status="open"
data-tier="3"
data-tags="前端,iOS,Android,mac,Windows">
<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>
<span class="item-id">#30</span>
<span class="item-title">补齐 es/ja/ko/ru 四语的 28 条支付文案(当前回退英文)</span>
<div class="card-badges">
<span class="tag status-badge s-doing">开发中</span>
<span class="tag t-high">重要</span>
<span class="tag status-badge s-open">待开始</span>
<span class="tag t-low">一般 / 优化</span>
<span class="tag tier-3">三级</span>
</div>
</div>
<div class="item-desc">本次为修构建引入了英文兜底机制:主语言改为英语,StringsEs/Ja/Ko/Ru/Zh 一律 extends StringsEn,未覆写的文案自动回退英文,缺翻译不再是编译错误(原先四个语言文件各缺 28 条,直接把 kernel_snapshot 打挂)。构建期由 ci/check-l10n-coverage.mjs 列出缺口,只报 warning 不阻断。当前缺口:es/ja/ko/ru 各缺 28 条,合计 112 处,覆盖率均为 161/189 = 85.2 百分比;en/zh 已 100 百分比。缺的都是支付相关:purchaseTitle, paymentTitle, buyNow, payMethodAlipay, payMethodCrypto, choosePayMethod, proMonthly, proQuarterly, proYearly, perQuarter, perYear, payAmountLabel, payAddressLabel, payNetworkLabel, payExactAmountHint, copied, openAlipay, openAlipayHint, openAlipayFailed, awaitingPayment, paySucceeded, payExpiresAt, payDone, payFailed, payRetry, switchPayMethod, cancelOrder, qrNotSupported。注意红线词规范(禁 VPN/翻墙/科学上网等),文案定位为网络加速/体验优化+隐私,见各 strings 文件头部注释。补齐后 warning 自动消失。</div>
<div class="card-footer">
<div class="tag-row"></div>
<div class="tag-row"><span class="tag t-tag" data-tag="前端">前端</span> <span class="tag t-tag" data-tag="iOS">iOS</span> <span class="tag t-tag" data-tag="Android">Android</span> <span class="tag t-tag" data-tag="mac">mac</span> <span class="tag t-tag" data-tag="Windows">Windows</span></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-07-23</span>
<span class="meta-date">🕐 2026-08-08</span>
</div>
</div>
@@ -704,14 +849,56 @@ header .header-meta{color:var(--fg-soft)}
</ul>
</div>
</div>
<div class="section-block" id="section-doing">
<div class="section-title st-doing" data-toggle="doing">
🔨 开发中 <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">
<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">6</span>
<span class="s-arrow">▴ 收起</span>
</div>
<div class="section-list-wrap " id="list-wrap-done">
<ul class="todo-list" id="list-done">
<li class="todo-card s-done"
data-id="28"
data-level="high"
data-status="done"
data-tier="2"
data-tags="mac,CI/CD">
<div class="card-header">
<span class="item-id">#28</span>
<span class="item-title">修复 macOS PacketTunnel 系统扩展 App Group 不一致导致装不上</span>
<div class="card-badges">
<span class="tag status-badge s-done">待验收</span>
<span class="tag t-block">高优 · 紧急</span>
<span class="tag tier-2">二级</span>
<button class="reject-btn" data-id="28" data-title="修复 macOS PacketTunnel 系统扩展 App Group 不一致导致装不上">拒绝验收</button>
</div>
</div>
<div class="item-desc">根因:scripts/ci/compile-macos.sh 第 221 行把 sysext 的 application-groups 硬编码成 iOS 风格的 group.com.pangolin.pangolin,且第 195-210 行生成的 app.entitlements 完全没有 application-groups 键。二者与扩展 Info.plist 里的 NEMachServiceNameBYL4KQHMTN.com.pangolin.pangolin.PacketTunnel)对不上前缀 —— nesessionmanager 报 NetworkExtensionErrorDomain Code=6sysextd 校验失败当场卸载刚 staging 的新扩展;VpnChannel.start() 的 step1 activateSystemExtensionIfNeeded 抛 code=9,永远走不到 step2 的 loadOrCreateManagerNETunnelProviderManager 配置建不出来,scutil --nc list 里没有 Pangolin,客户端一个包都发不到服务器(服务端侧该 Mac 出口 IP 的握手尝试数为 0)。这违反了 CLAUDE.md 第 152 行已写明的铁律。注意这两个 entitlements 是 codesign --force 最终覆盖签名用的,仓库里的 .entitlements 源文件只在 Xcode 编译阶段生效,所以线上包坏而本地 all 流程正常。修复:compile-macos.sh 两处改用脚本第 99 行已定义的 APP_GROUP 变量,app.entitlements 补 application-groups。scripts/local_test.sh 的同款硬编码本次已修,并新增 verify_app_group 一致性闸(读最终产物签名,比对两端 App Group 与 NEMachServiceName 前缀)和 macos 一条龙子命令。建议把同样的闸加进 .gitea/workflows/ci.yml。改完需重新构建+公证+替换 api.yanmeiai.com/downloads/pangolin-macos-x64.zip。附带:受影响机器会堆积多个 terminated waiting to uninstall on reboot 的旧扩展(本机 13 个,已 38 天未重启),建议重启清理。</div>
<div class="card-footer">
<div class="tag-row"><span class="tag t-tag" data-tag="mac">mac</span> <span class="tag t-tag" data-tag="CI/CD">CI/CD</span></div>
<div class="item-meta">
<span class="tag owner-agent">🤖 agent</span>
<span class="meta-date">🕐 2026-08-08</span>
</div>
</div>
</li>
<li class="todo-card s-done"
data-id="18"
data-level="mid"
@@ -837,6 +1024,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>
+113 -3
View File
@@ -1,9 +1,9 @@
{
"meta": {
"title": "feature+windows — 项目 TODO",
"updated_at": "2026-07-22T16:59:57.735Z"
"updated_at": "2026-08-08T16:07:14.004Z"
},
"seq": 23,
"seq": 30,
"items": [
{
"id": 1,
@@ -368,11 +368,121 @@
"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
},
{
"id": 28,
"title": "修复 macOS PacketTunnel 系统扩展 App Group 不一致导致装不上",
"desc": "根因:scripts/ci/compile-macos.sh 第 221 行把 sysext 的 application-groups 硬编码成 iOS 风格的 group.com.pangolin.pangolin,且第 195-210 行生成的 app.entitlements 完全没有 application-groups 键。二者与扩展 Info.plist 里的 NEMachServiceNameBYL4KQHMTN.com.pangolin.pangolin.PacketTunnel)对不上前缀 —— nesessionmanager 报 NetworkExtensionErrorDomain Code=6sysextd 校验失败当场卸载刚 staging 的新扩展;VpnChannel.start() 的 step1 activateSystemExtensionIfNeeded 抛 code=9,永远走不到 step2 的 loadOrCreateManagerNETunnelProviderManager 配置建不出来,scutil --nc list 里没有 Pangolin,客户端一个包都发不到服务器(服务端侧该 Mac 出口 IP 的握手尝试数为 0)。这违反了 CLAUDE.md 第 152 行已写明的铁律。注意这两个 entitlements 是 codesign --force 最终覆盖签名用的,仓库里的 .entitlements 源文件只在 Xcode 编译阶段生效,所以线上包坏而本地 all 流程正常。修复:compile-macos.sh 两处改用脚本第 99 行已定义的 APP_GROUP 变量,app.entitlements 补 application-groups。scripts/local_test.sh 的同款硬编码本次已修,并新增 verify_app_group 一致性闸(读最终产物签名,比对两端 App Group 与 NEMachServiceName 前缀)和 macos 一条龙子命令。建议把同样的闸加进 .gitea/workflows/ci.yml。改完需重新构建+公证+替换 api.yanmeiai.com/downloads/pangolin-macos-x64.zip。附带:受影响机器会堆积多个 terminated waiting to uninstall on reboot 的旧扩展(本机 13 个,已 38 天未重启),建议重启清理。",
"level": "high",
"tier": 2,
"tags": [
"mac",
"CI/CD"
],
"owner": "agent",
"status": "done",
"created_at": "2026-08-08T01:20:23.304Z",
"done": false,
"completed_at": null,
"version": null
},
{
"id": 29,
"title": "Windows 端 chenxin 设备连接凭据已过期,需重新签发并补过期处理",
"desc": "设备 Win·chenxindevices.id=25dp_uuid 019f599b-d11a-7763-9099-9935f4b49070client_version v1.0.72)的 connect_credentials 已于 2026-08-01 18:19 UTC 过期,agent 随后把它从 /etc/sing-box/config.json 的 reality-in users 里清掉了(当前只剩 019f55d6 和 019f8c8f 两个)。客户端对此无感知,持续高频重连,sing-box 一路报 REALITY: processed invalid connection。实测最近 2 小时该出口 IP 124.88.8.196 刷了 1801 条失败日志,占服务端全部握手失败的约 99%,把真正的故障信号淹没了(这次排查 Mac 问题时一度被误导)。处理项:1) 先给该 dp_uuid 重新签发凭据,恢复 chenxin 可用;2) 查清为什么它没像 Mac 那样自动续期成功——Mac 的 019f55d6 已续到 2026-08-09,说明续期链路本身是通的,怀疑 v1.0.72 版本客户端的续期逻辑有缺陷或登录态已失效;3) 客户端在凭据过期时应给出明确提示并做退避重试,而不是无限高频重连;4) 服务端对同一 dp_uuid 的连续握手失败做限频或告警,避免单台故障设备淹没日志。",
"level": "high",
"tier": 2,
"tags": [
"Windows",
"后端"
],
"owner": "agent",
"status": "open",
"created_at": "2026-08-08T01:20:48.075Z",
"done": false,
"completed_at": null,
"version": null
},
{
"id": 30,
"title": "补齐 es/ja/ko/ru 四语的 28 条支付文案(当前回退英文)",
"desc": "本次为修构建引入了英文兜底机制:主语言改为英语,StringsEs/Ja/Ko/Ru/Zh 一律 extends StringsEn,未覆写的文案自动回退英文,缺翻译不再是编译错误(原先四个语言文件各缺 28 条,直接把 kernel_snapshot 打挂)。构建期由 ci/check-l10n-coverage.mjs 列出缺口,只报 warning 不阻断。当前缺口:es/ja/ko/ru 各缺 28 条,合计 112 处,覆盖率均为 161/189 = 85.2 百分比;en/zh 已 100 百分比。缺的都是支付相关:purchaseTitle, paymentTitle, buyNow, payMethodAlipay, payMethodCrypto, choosePayMethod, proMonthly, proQuarterly, proYearly, perQuarter, perYear, payAmountLabel, payAddressLabel, payNetworkLabel, payExactAmountHint, copied, openAlipay, openAlipayHint, openAlipayFailed, awaitingPayment, paySucceeded, payExpiresAt, payDone, payFailed, payRetry, switchPayMethod, cancelOrder, qrNotSupported。注意红线词规范(禁 VPN/翻墙/科学上网等),文案定位为网络加速/体验优化+隐私,见各 strings 文件头部注释。补齐后 warning 自动消失。",
"level": "low",
"tier": 3,
"tags": [
"前端",
"iOS",
"Android",
"mac",
"Windows"
],
"owner": "agent",
"status": "open",
"created_at": "2026-08-08T01:41:54.388Z",
"done": false,
"completed_at": null,
"version": null
}
]
}
+16 -4
View File
@@ -25,6 +25,17 @@ import { makeT } from '../../lib/i18n';
import { getClient } from '../../lib/api/client';
import { bilingual } from '../../lib/api/errors';
/** basePath( next.config.js ) window.location ,
* Next basePath,,()
* */
const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? '/user';
/** 把本站相对路径补上 basePath(供 window.location 原生跳转用)。 */
function withBase(path: string): string {
const p = path.startsWith('/') ? path : `/${path}`;
return `${BASE_PATH}${p}`;
}
/** redirect 白名单:仅本站相对路径(单个 '/' 开头),其余一律回 '/'。 */
function safeRedirect(raw: string | null): string {
if (!raw) return '/';
@@ -45,14 +56,15 @@ export default function SsoPage() {
const redirect = safeRedirect(params.get('redirect'));
// 票据只用一次,立刻从地址栏抹掉,不留浏览器历史(与 jiu 一致)。
// 原生 history/location 不吃 Next 的 basePath,须手动补,否则地址与跳转都会漂到站点根。
try {
window.history.replaceState(null, '', '/sso/');
window.history.replaceState(null, '', withBase('/sso/'));
} catch {
/* ignore */
}
if (!ticket) {
window.location.replace('/');
window.location.replace(withBase('/'));
return;
}
@@ -61,14 +73,14 @@ export default function SsoPage() {
.exchangeWebTicket(ticket)
.then(() => {
if (!alive) return;
window.location.replace(redirect);
window.location.replace(withBase(redirect));
})
.catch((e) => {
if (!alive) return;
setMsg(bilingual(e, lang));
setFailed(true);
setTimeout(() => {
window.location.replace('/');
window.location.replace(withBase('/'));
}, 1500);
});