From 893d71b46df9dfa628e6d2f4fdea8a8666c37cb3 Mon Sep 17 00:00:00 2001 From: jeffjiang Date: Mon, 16 Nov 2026 19:44:45 +0800 Subject: [PATCH 1/2] Add app store commands to clash-cli profiles, rules append/remove and dns policy drive the App's configuration store through the new app-store-v1 controller capability. --- cli/HELP.txt | 40 ++- cli/appstore.go | 498 ++++++++++++++++++++++++++++++++++ cli/appstore_test.go | 628 +++++++++++++++++++++++++++++++++++++++++++ cli/args.go | 4 +- cli/commands.go | 12 +- cli/main.go | 15 +- 6 files changed, 1186 insertions(+), 11 deletions(-) create mode 100644 cli/appstore.go create mode 100644 cli/appstore_test.go diff --git a/cli/HELP.txt b/cli/HELP.txt index 7379189..d90c776 100644 --- a/cli/HELP.txt +++ b/cli/HELP.txt @@ -1,6 +1,6 @@ --- name: clash-cli -description: 通过 Clash App 内置的 clash-cli,在 Mac 终端里实时监控和控制 Clash App(本机 Mac,或局域网里的 iPhone / iPad / Apple TV)。支持状态/连接/流量/规则查询、规则命中分析、节点与策略组切换、节点测速、DNS 查询。当用户提到 Clash App、切换节点、查看连接、实时流量、规则匹配、节点测速、外部控制器时使用。 +description: 通过 Clash App 内置的 clash-cli,在 Mac 终端里实时监控和控制 Clash App(本机 Mac,或局域网里的 iPhone / iPad / Apple TV)。支持状态/连接/流量/规则查询、规则命中分析、节点与策略组切换、节点测速、DNS 查询,以及 App 配置里追加规则与 DNS 策略的读写。当用户提到 Clash App、切换节点、查看连接、实时流量、规则匹配、节点测速、外部控制器、追加规则、nameserver-policy 时使用。 --- # Clash App 控制器(Clash App 内置的 clash-cli) @@ -60,7 +60,9 @@ clash-cli status | `clash-cli traffic [秒]` | 实时流量(瞬时速率 + 累计) | | `clash-cli connections [N]` | 活跃连接列表(host → 策略链 → 命中规则 → 上下行),默认前 20 | | `clash-cli configs` | 当前运行配置(端口/tun/dns 等),只输出 JSON,可直接接 `jq`;`--json` 是控制器原样的回答。端口实际监听在哪看 `clash-cli status`:port、socks-port、mixed-port、redir-port、tproxy-port 先看 `allow-lan`,关着时只在 127.0.0.1 上,`bind-address` 写什么都不起作用;开着时才按 `bind-address`(没写就是 `*`),再由 `lan-allowed-ips`/`lan-disallowed-ips` 筛设备。App 里「允许局域网连接」关着时会把 `allow-lan` 改成 false。`listeners:` 里自己写的监听不归它管 | -| `clash-cli rules [N]` | 规则列表(默认前 10,0 = 全部) | +| `clash-cli rules [N]` | 规则列表(默认前 10,0 = 全部);这是运行态,改配置见 §4 的配置库 | +| `clash-cli profiles` | App 里的配置列表(`*` 当前),带追加规则条数;`--json` 是控制器原样的回答 | +| `clash-cli dns policy [--profile ]` | 这份配置的 DNS 策略:`nameserver-policy` 与 `fake-ip-filter`(缺省当前配置) | | `clash-cli rule match <域名\|IP\|URL>` | **规则命中分析**:这条连接会命中哪条规则、走哪条链 | | `clash-cli provider list` | 节点集与规则集 | | `clash-cli dns query <域名> [type]` | 走内核 DNS 查询,返回 Answer 数组 | @@ -98,7 +100,7 @@ clash-cli status ## 4. 影响边界(写操作) - **写操作**:`proxy set`、`mode`、`group unfix`、`group test`、`provider update`、`conn close `、`flush` - 会改变运行状态,执行前先确认目标存在(`proxy get`、`proxies`、`connections`)。 + 会改变运行状态;`rules append|remove`、`dns policy set|clear` 会改配置库(见本节末尾)。执行前先确认目标存在(`proxy get`、`proxies`、`connections`、`profiles`)。 每次写操作前,人读输出会先打印要改的是哪台设备、哪个内核版本。 - `provider update` 让隧道向服务器检查一次,按结果报:已更新(条数前后对比)、没有变化、打开 Clash 后生效(新内容已取到,App 打开后用上;原因在 --json 的 pendingReason 里); 检查失败时报集合名和内核给的原因(原样),退出码 1。检查失败或控制器报错时退出码非 0(隧道还在检查、等不及回答的 504 也算控制器报错)。 @@ -108,6 +110,34 @@ clash-cli status - **`reload`、`check` 不可用**:配置由 Clash App 管理(组合、切换、检查都在 App 里),这两个命令返回退出码 5。 要换配置、更新订阅或检查配置文件,请在 App 里操作。 +### 配置库:`rules append|remove`、`dns policy` + +这一组命令改的是 App 的**配置库**(`~/Library/Group Containers/group.com.hako.network/working/store/profiles.json` 里的 +`override.appendRules`、`override.prependRules`,以及 `legacyRuntimePatchJSON` 里的 `dns.nameserver-policy`、`dns.fake-ip-filter`), +**不是现在的运行态**:改动**下次连接生效**(现在连着的连接仍按旧规则),也不重建派生产物(那是 App 在连接时做的)。 +内核没给 `app-store-v1` 能力时,这些命令退出码 5,并说明「还不支持 App 配置读写(app-store-v1)」。 + +```bash +clash-cli profiles # 列配置,* 是当前;--json 拿原样回答 +clash-cli rules append 'DOMAIN-SUFFIX,corp.example.com,DIRECT' \ + 'IP-CIDR,10.0.0.0/8,DIRECT,no-resolve' +clash-cli rules remove 'IP-CIDR,10.0.0.0/8,DIRECT,no-resolve' +clash-cli rules append 'DOMAIN,foo.example.com,PROXY' --profile XSUS # 指定配置(id 或名称) +clash-cli dns policy # 看 nameserver-policy / fake-ip-filter +clash-cli dns policy set '+.corp.example.com=10.78.226.116,10.78.226.117' +clash-cli dns policy clear # 清空 nameserver-policy +clash-cli dns policy clear --fake-ip-filter +``` + +- `--profile` 缺省是当前配置(`profiles` 里带 `*` 的那个),也可以给 id 或名称;有同名配置时要求用 id。 +- `rules append` 合并写入并去重:本来就在的规则跳过,输出里说明跳过几条;`rules remove` 只删完全一致的规则。 + 去重后没有变化时不写入,只报现有条数。 +- `dns policy set` 按域名合并:同一个域名再设一次会整体替换它的地址列表;要清空某个域名就用 `dns policy clear`。 + `dns policy clear` 默认只清 `nameserver-policy`,加 `--fake-ip-filter` 时只清 `fake-ip-filter`(两者互斥,各跑一次)。 +- 写入由控制器原子落盘,并保留配置里其它字段(`prependRules`、`tun`、`sniffer`、未知字段)不被改动。 +- 校验在控制器那侧:每条规则 1..512 字节、不含换行、最多 5000 条;域名非空且 ≤253 字节,地址是合法 IP 或 + `https://`/`tls://`/`quic://`/`h3://`/`dhcp://` 前缀且 ≤512 字节。非法时控制器回 400、不落盘,CLI 原样转述(退出码 1)。 + ## 5. 环境与安全注意事项 - 拿到密钥的人可以完全控制 Clash(模式、局域网共享、选节点、断连接、清缓存)。不要把密钥贴进公开的地方; @@ -117,8 +147,8 @@ clash-cli status - 全局选项(放在命令前后都行;与环境变量同时给出时用选项的值):`-u` / `--url`、`--secret`、`--secret-stdin`、 `--fingerprint`、`--timeout`、`--json`。`CLASH_TIMEOUT` 写得不合法时无论给不给 `--timeout` 都报退出码 2。 - 切换节点时节点名必须与策略组成员**精确匹配**(含空格/emoji/特殊字符,如「🇭🇰香港trojan1」)。 -- 退出码:0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒;5 不是 Clash App 的控制器或不支持(含 `reload`、`check`); - 6 证书指纹不符或未确认。 +- 退出码:0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒;5 不是 Clash App 的控制器或不支持(含 `reload`、`check`, + 以及内核没有 `app-store-v1` 时的配置读写);6 证书指纹不符或未确认。 - 已知指纹记在 `~/.config/clash-cli/known_hosts`(App 内置版在沙盒容器里: `~/Library/Containers/.clash-cli/Data/.config/clash-cli/known_hosts`)。 diff --git a/cli/appstore.go b/cli/appstore.go new file mode 100644 index 0000000..ae65a99 --- /dev/null +++ b/cli/appstore.go @@ -0,0 +1,498 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "slices" + "sort" + "strings" +) + +// The App keeps its configuration library (store/profiles.json) as the source of +// truth and rebuilds the derived files on connect. These commands only edit the +// inputs (appendRules/prependRules and the DNS policy inside the runtime patch), +// so they never race with the App's generator: changes apply on the next connect. + +const ( + appStoreCapability = "app-store-v1" + appStoreRoot = "/clash/v1/app" + appStoreEffective = "next-connect" + appStoreNote = "改动在下次连接生效(现在连着的连接仍按旧规则)" +) + +type appProfileActive struct { + ProfileID string `json:"profileID"` + Revision string `json:"revision"` +} + +type appProfile struct { + ID string `json:"id"` + Label string `json:"label"` + Order int `json:"order"` + ActiveRevision string `json:"activeRevision"` + Active bool `json:"active"` + AppendedRules int `json:"appendedRules"` + PrependedRules bool `json:"prependedRules"` + Patched bool `json:"patched"` +} + +type appProfilesIndex struct { + Active appProfileActive `json:"active"` + Profiles []appProfile `json:"profiles"` +} + +type appProfileRules struct { + ID string `json:"id"` + PrependRules bool `json:"prependRules"` + AppendRules []string `json:"appendRules"` + PatchJSON string `json:"patchJSON"` +} + +type appDNSPolicy struct { + NameserverPolicy map[string][]string `json:"nameserverPolicy"` + FakeIPFilter []string `json:"fakeIPFilter"` +} + +// appDNSPolicyWrite leaves a nil field out of the request, which the controller +// reads as "keep this part as it is". +type appDNSPolicyWrite struct { + NameserverPolicy *map[string][]string `json:"nameserverPolicy,omitempty"` + FakeIPFilter *[]string `json:"fakeIPFilter,omitempty"` +} + +type appRulesResult struct { + ProfileID string `json:"profileID"` + Label string `json:"label,omitempty"` + Added int `json:"added"` + Removed int `json:"removed,omitempty"` + Count int `json:"count"` + AppendRules []string `json:"appendRules"` + Effective string `json:"effective"` +} + +type appDNSPolicyResult struct { + ProfileID string `json:"profileID"` + Label string `json:"label,omitempty"` + NameserverPolicy map[string][]string `json:"nameserverPolicy,omitempty"` + FakeIPFilter []string `json:"fakeIPFilter,omitempty"` + Cleared string `json:"cleared,omitempty"` + Effective string `json:"effective"` +} + +func (s *session) requireAppStore() error { + if slices.Contains(s.caps.Capabilities, appStoreCapability) { + return nil + } + return failure(exitUnsupported, "unsupported", + "这个 Clash App(内核 %s)还不支持 App 配置读写(%s),请更新 App", s.caps.CoreVersion, appStoreCapability) +} + +func appProfilePath(id, suffix string) string { + return appStoreRoot + "/profiles/" + pathEscape(id) + "/" + suffix +} + +func appProfileTitle(profile appProfile) string { + switch { + case profile.Label != "" && profile.ID != "": + return fmt.Sprintf("%s(%s)", profile.Label, profile.ID) + case profile.Label != "": + return profile.Label + case profile.ID != "": + return profile.ID + } + return "未命名的配置" +} + +func (s *session) appProfiles() (appProfilesIndex, json.RawMessage, error) { + var index appProfilesIndex + var raw json.RawMessage + if err := s.call(http.MethodGet, appStoreRoot+"/profiles", nil, nil, &raw); err != nil { + return index, nil, err + } + if err := json.Unmarshal(raw, &index); err != nil { + return index, raw, failure(exitPeerError, "bad-response", "配置列表不是 JSON: %v", err) + } + return index, raw, nil +} + +func (s *session) resolveAppProfile(name string) (appProfile, error) { + index, _, err := s.appProfiles() + if err != nil { + return appProfile{}, err + } + if name == "" { + if index.Active.ProfileID == "" { + return appProfile{}, failure(exitPeerError, "bad-response", "控制器没有说哪个配置是当前配置(clash-cli profiles 查看)") + } + for _, profile := range index.Profiles { + if profile.ID == index.Active.ProfileID { + return profile, nil + } + } + return appProfile{ID: index.Active.ProfileID, Active: true, ActiveRevision: index.Active.Revision}, nil + } + for _, profile := range index.Profiles { + if profile.ID == name { + return profile, nil + } + } + var matches []appProfile + for _, profile := range index.Profiles { + if profile.Label == name { + matches = append(matches, profile) + } + } + switch len(matches) { + case 1: + return matches[0], nil + case 0: + return appProfile{}, usage("clash-cli --profile %q:没有这个配置(clash-cli profiles 查看现有配置)", name) + } + return appProfile{}, usage("clash-cli --profile %q:有 %d 个同名配置,请改用 id(clash-cli profiles 查看)", name, len(matches)) +} + +func (s *session) appRules(id string) (appProfileRules, json.RawMessage, error) { + var rules appProfileRules + var raw json.RawMessage + if err := s.call(http.MethodGet, appProfilePath(id, "rules"), nil, nil, &raw); err != nil { + return rules, nil, err + } + if err := json.Unmarshal(raw, &rules); err != nil { + return rules, raw, failure(exitPeerError, "bad-response", "%s 的规则不是 JSON: %v", id, err) + } + if rules.AppendRules == nil { + rules.AppendRules = []string{} + } + return rules, raw, nil +} + +func (s *session) writeAppRules(id string, prepend bool, appendRules []string) error { + if appendRules == nil { + appendRules = []string{} + } + return s.call(http.MethodPut, appProfilePath(id, "rules"), nil, struct { + PrependRules bool `json:"prependRules"` + AppendRules []string `json:"appendRules"` + }{prepend, appendRules}, nil) +} + +func (s *session) appDNSPolicy(id string) (appDNSPolicy, json.RawMessage, error) { + var policy appDNSPolicy + var raw json.RawMessage + if err := s.call(http.MethodGet, appProfilePath(id, "dns-policy"), nil, nil, &raw); err != nil { + return policy, nil, err + } + if err := json.Unmarshal(raw, &policy); err != nil { + return policy, raw, failure(exitPeerError, "bad-response", "%s 的 DNS 策略不是 JSON: %v", id, err) + } + return policy, raw, nil +} + +func (s *session) writeAppDNSPolicy(id string, policy appDNSPolicyWrite) error { + return s.call(http.MethodPut, appProfilePath(id, "dns-policy"), nil, policy, nil) +} + +func cmdAppProfiles(s *session, p parsedArguments) error { + if len(p.positional) > 1 { + return usage("clash-cli profiles") + } + if err := s.requireAppStore(); err != nil { + return err + } + index, raw, err := s.appProfiles() + if err != nil { + return err + } + s.out.succeed(raw, func() { printAppProfiles(s.out, index) }) + return nil +} + +func printAppProfiles(out *output, index appProfilesIndex) { + if len(index.Profiles) == 0 { + out.printf("App 里还没有配置\n") + return + } + var rows [][]string + for _, profile := range index.Profiles { + marker := "" + if profile.Active || profile.ID == index.Active.ProfileID { + marker = "*" + } + revision := profile.ActiveRevision + if revision == "" { + revision = "-" + } + label := profile.Label + if label == "" { + label = "-" + } + rows = append(rows, []string{marker, label, profile.ID, revision, fmt.Sprint(profile.AppendedRules)}) + } + out.table([]string{"当前", "名称", "id", "修订", "追加规则"}, rows) +} + +// cmdRulesEdit handles `rules append|remove`, which edits the App's configuration +// instead of the running rule list. +func cmdRulesEdit(s *session, p parsedArguments, verb string, rules []string) error { + if len(rules) == 0 { + return usage("clash-cli rules %s <规则>... [--profile ]", verb) + } + for _, rule := range rules { + if strings.TrimSpace(rule) == "" { + return usage("clash-cli rules %s:规则不能是空的", verb) + } + } + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + current, _, err := s.appRules(profile.ID) + if err != nil { + return err + } + var merged []string + added, removed := 0, 0 + switch verb { + case "append": + merged, added = mergeAppendRules(current.AppendRules, rules) + case "remove": + merged, removed = removeAppendRules(current.AppendRules, rules) + } + result := appRulesResult{ + ProfileID: profile.ID, Label: profile.Label, Added: added, Removed: removed, + Count: len(merged), AppendRules: merged, Effective: appStoreEffective, + } + if added == 0 && removed == 0 { + s.out.succeed(result, func() { + s.out.printf("%s的追加规则没有变化(现有 %d 条)\n", appProfileTitle(profile), len(merged)) + }) + return nil + } + s.announce() + if err := s.writeAppRules(profile.ID, current.PrependRules, merged); err != nil { + return err + } + s.out.succeed(result, func() { + switch verb { + case "append": + s.out.printf("✓ %s追加 %d 条规则,现在共 %d 条\n", appProfileTitle(profile), added, len(merged)) + if skipped := len(rules) - added; skipped > 0 { + s.out.printf(" · 其中 %d 条本来就有,没有重复追加\n", skipped) + } + case "remove": + s.out.printf("✓ %s移除 %d 条规则,现在共 %d 条\n", appProfileTitle(profile), removed, len(merged)) + } + s.out.printf(" · %s\n", appStoreNote) + }) + return nil +} + +// mergeAppendRules appends the rules that are missing, keeping the existing order +// and dropping duplicates from both the existing list and the arguments. +func mergeAppendRules(existing, added []string) ([]string, int) { + merged := make([]string, 0, len(existing)+len(added)) + seen := make(map[string]bool, len(existing)+len(added)) + for _, rule := range existing { + if seen[rule] { + continue + } + seen[rule] = true + merged = append(merged, rule) + } + appended := 0 + for _, rule := range added { + if seen[rule] { + continue + } + seen[rule] = true + merged = append(merged, rule) + appended++ + } + return merged, appended +} + +func removeAppendRules(existing, removed []string) ([]string, int) { + drop := make(map[string]bool, len(removed)) + for _, rule := range removed { + drop[rule] = true + } + kept := make([]string, 0, len(existing)) + for _, rule := range existing { + if drop[rule] { + continue + } + kept = append(kept, rule) + } + return kept, len(existing) - len(kept) +} + +func cmdDNSPolicy(s *session, p parsedArguments) error { + args := p.positional[2:] + if len(args) == 0 { + return dnsPolicyShow(s, p) + } + switch args[0] { + case "set": + return dnsPolicySet(s, p, args[1:]) + case "clear": + return dnsPolicyClear(s, p, args[1:]) + } + return usage("clash-cli dns policy | dns policy set '+.域名=地址[,地址]'... | dns policy clear [--fake-ip-filter]") +} + +func dnsPolicyShow(s *session, p parsedArguments) error { + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + policy, raw, err := s.appDNSPolicy(profile.ID) + if err != nil { + return err + } + s.out.succeed(raw, func() { + s.out.printf("DNS 策略:%s\n", appProfileTitle(profile)) + printNameserverPolicy(s.out, policy.NameserverPolicy, " ") + printFakeIPFilter(s.out, policy.FakeIPFilter, " ") + }) + return nil +} + +func dnsPolicySet(s *session, p parsedArguments, pairs []string) error { + if len(pairs) == 0 { + return usage("clash-cli dns policy set '+.域名=地址[,地址]'... [--profile ]") + } + added, err := parseNameserverPairs(pairs) + if err != nil { + return err + } + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + current, _, err := s.appDNSPolicy(profile.ID) + if err != nil { + return err + } + merged := make(map[string][]string, len(current.NameserverPolicy)+len(added)) + for domain, servers := range current.NameserverPolicy { + merged[domain] = servers + } + for domain, servers := range added { + merged[domain] = servers + } + s.announce() + if err := s.writeAppDNSPolicy(profile.ID, appDNSPolicyWrite{NameserverPolicy: &merged}); err != nil { + return err + } + result := appDNSPolicyResult{ + ProfileID: profile.ID, Label: profile.Label, NameserverPolicy: merged, Effective: appStoreEffective, + } + s.out.succeed(result, func() { + s.out.printf("✓ %s写入 %d 条 nameserver-policy,现有 %d 条:\n", appProfileTitle(profile), len(added), len(merged)) + for _, domain := range sortedKeys(added) { + s.out.printf(" %s → %s\n", domain, strings.Join(added[domain], ",")) + } + s.out.printf(" · %s\n", appStoreNote) + }) + return nil +} + +func dnsPolicyClear(s *session, p parsedArguments, rest []string) error { + fakeIPFilter := p.has("fake-ip-filter") + if len(rest) > 0 { + return usage("clash-cli dns policy clear [--fake-ip-filter] [--profile ]") + } + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + write := appDNSPolicyWrite{} + cleared := "nameserverPolicy" + result := appDNSPolicyResult{ProfileID: profile.ID, Label: profile.Label, Effective: appStoreEffective} + if fakeIPFilter { + empty := []string{} + write.FakeIPFilter = &empty + cleared = "fakeIPFilter" + result.FakeIPFilter = empty + } else { + empty := map[string][]string{} + write.NameserverPolicy = &empty + cleared = "nameserverPolicy" + } + result.Cleared = cleared + s.announce() + if err := s.writeAppDNSPolicy(profile.ID, write); err != nil { + return err + } + s.out.succeed(result, func() { + label := map[string]string{"nameserverPolicy": "nameserver-policy", "fakeIPFilter": "fake-ip-filter"}[cleared] + s.out.printf("✓ 已清空 %s的 %s\n", appProfileTitle(profile), label) + s.out.printf(" · %s\n", appStoreNote) + }) + return nil +} + +func parseNameserverPairs(pairs []string) (map[string][]string, error) { + policy := make(map[string][]string, len(pairs)) + for _, pair := range pairs { + domain, servers, ok := strings.Cut(pair, "=") + domain = strings.TrimSpace(domain) + if !ok || domain == "" || strings.TrimSpace(servers) == "" { + return nil, usage("clash-cli dns policy set:参数写成 '+.域名=地址[,地址]',收到 %q", pair) + } + var list []string + for _, server := range strings.Split(servers, ",") { + server = strings.TrimSpace(server) + if server == "" { + return nil, usage("clash-cli dns policy set:%s 的地址里有一个是空的", domain) + } + list = append(list, server) + } + policy[domain] = append(policy[domain], list...) + } + return policy, nil +} + +func printNameserverPolicy(out *output, policy map[string][]string, indent string) { + if len(policy) == 0 { + out.printf("%snameserver-policy:没有设置\n", indent) + return + } + out.printf("%snameserver-policy(%d 条):\n", indent, len(policy)) + for _, domain := range sortedKeys(policy) { + out.printf("%s %s → %s\n", indent, domain, strings.Join(policy[domain], ",")) + } +} + +func printFakeIPFilter(out *output, filter []string, indent string) { + if len(filter) == 0 { + out.printf("%sfake-ip-filter:没有设置\n", indent) + return + } + out.printf("%sfake-ip-filter(%d 条):\n", indent, len(filter)) + for _, item := range filter { + out.printf("%s %s\n", indent, item) + } +} + +func sortedKeys[V any](items map[string]V) []string { + names := make([]string, 0, len(items)) + for name := range items { + names = append(names, name) + } + sort.Strings(names) + return names +} diff --git a/cli/appstore_test.go b/cli/appstore_test.go new file mode 100644 index 0000000..00aa186 --- /dev/null +++ b/cli/appstore_test.go @@ -0,0 +1,628 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// fakeAppStore is a stand-in controller: it serves the App store endpoints from +// fixture JSON and records the bodies that were written. +type fakeAppStore struct { + mu sync.Mutex + capabilities []string + profiles string + profilesCode int + rules map[string]string + dns map[string]string + runtimeRules string + codes map[string]int + puts []fakePut +} + +type fakePut struct { + Path string + Body string +} + +func (f *fakeAppStore) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + body, _ := io.ReadAll(r.Body) + if r.Method == http.MethodPut { + f.puts = append(f.puts, fakePut{Path: r.URL.Path, Body: string(body)}) + } + if code := f.codes[r.Method+r.URL.Path]; code != 0 { + w.WriteHeader(code) + fmt.Fprint(w, `{"message":"控制器拒绝了这次改动"}`) + return + } + switch { + case r.URL.Path == "/clash/v1/capabilities": + _ = json.NewEncoder(w).Encode(capabilities{API: 1, Platform: "macos", CoreVersion: "1.19.32", Capabilities: f.capabilities}) + case r.URL.Path == "/clash/v1/app/profiles": + if f.profilesCode != 0 { + w.WriteHeader(f.profilesCode) + fmt.Fprint(w, `{"message":"the App has not published its profile index yet"}`) + return + } + fmt.Fprint(w, f.profiles) + case r.URL.Path == "/rules": + fmt.Fprint(w, f.runtimeRules) + case strings.HasPrefix(r.URL.Path, "/clash/v1/app/profiles/"): + rest := strings.TrimPrefix(r.URL.Path, "/clash/v1/app/profiles/") + id, kind, ok := strings.Cut(rest, "/") + if !ok { + http.NotFound(w, r) + return + } + if r.Method == http.MethodPut { + w.WriteHeader(http.StatusNoContent) + return + } + store := map[string]string{} + switch kind { + case "rules": + store = f.rules + case "dns-policy": + store = f.dns + } + payload, found := store[id] + if !found { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, `{"message":"unknown profile"}`) + return + } + fmt.Fprint(w, payload) + default: + http.NotFound(w, r) + } +} + +func (f *fakeAppStore) written(t *testing.T) (string, map[string]any) { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + if len(f.puts) != 1 { + t.Fatalf("expected exactly one write, got %d: %+v", len(f.puts), f.puts) + } + var decoded map[string]any + if err := json.Unmarshal([]byte(f.puts[0].Body), &decoded); err != nil { + t.Fatalf("write body is not JSON (%q): %v", f.puts[0].Body, err) + } + return f.puts[0].Path, decoded +} + +const testProfileIndex = `{"active":{"profileID":"p2","revision":"r9"},"profiles":[` + + `{"id":"p1","label":"Home","order":1,"activeRevision":"r3","appendedRules":0},` + + `{"id":"p2","label":"XSUS","order":-1,"activeRevision":"r9","active":true,"appendedRules":2,"prependedRules":true,"patched":false}]}` + +func newAppStoreSession(t *testing.T, store *fakeAppStore) (*session, *bytes.Buffer) { + t.Helper() + server := httptest.NewServer(store) + t.Cleanup(server.Close) + var stdout, stderr bytes.Buffer + env := environment{ + getenv: func(string) string { return "" }, + stdin: strings.NewReader(""), + stdout: &stdout, stderr: &stderr, + homeDir: t.TempDir(), + } + out := &output{stdout: &stdout, stderr: &stderr} + s, err := connect(env, globalOptions{url: server.URL, timeout: 3 * time.Second}, out) + if err != nil { + t.Fatalf("connect: %v", err) + } + return s, &stdout +} + +func args(positional ...string) parsedArguments { + return parsedArguments{positional: positional, flags: map[string]string{}} +} + +func withFlags(parsed parsedArguments, pairs ...string) parsedArguments { + for i := 0; i+1 < len(pairs); i += 2 { + parsed.flags[pairs[i]] = pairs[i+1] + } + return parsed +} + +func exitOf(t *testing.T, err error) int { + t.Helper() + var cli *cliError + if !errors.As(err, &cli) { + t.Fatalf("expected a *cliError, got %v", err) + } + return cli.exit +} + +func TestAppStoreMissingCapability(t *testing.T) { + cases := [][]string{ + {"profiles"}, + {"rules", "append", "DOMAIN-SUFFIX,a.com,DIRECT"}, + {"dns", "policy"}, + } + for _, positional := range cases { + t.Run(strings.Join(positional, " "), func(t *testing.T) { + store := &fakeAppStore{profiles: testProfileIndex} + s, stdout := newAppStoreSession(t, store) + var err error + switch positional[0] { + case "profiles": + err = cmdAppProfiles(s, args(positional...)) + case "rules": + err = cmdRules(s, args(positional...)) + case "dns": + err = cmdDNS(s, args(positional...)) + } + if err == nil { + t.Fatalf("expected a capability failure, got none (stdout %q)", stdout.String()) + } + if exit := exitOf(t, err); exit != exitUnsupported { + t.Fatalf("expected exit %d, got %d (%v)", exitUnsupported, exit, err) + } + if !strings.Contains(err.Error(), "还不支持 App 配置读写") || !strings.Contains(err.Error(), appStoreCapability) { + t.Fatalf("message should name the missing capability, got %q", err.Error()) + } + if len(store.puts) != 0 { + t.Fatalf("nothing should be written, got %+v", store.puts) + } + }) + } +} + +func TestAppStoreProfilesTable(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex} + s, stdout := newAppStoreSession(t, store) + if err := cmdAppProfiles(s, args("profiles")); err != nil { + t.Fatalf("profiles: %v", err) + } + output := stdout.String() + lines := strings.Split(strings.TrimSpace(output), "\n") + if len(lines) != 3 { + t.Fatalf("expected a header and two rows, got %q", output) + } + for _, want := range []string{"当前", "名称", "id", "修订", "追加规则"} { + if !strings.Contains(lines[0], want) { + t.Fatalf("header %q is missing %q", lines[0], want) + } + } + var active, inactive string + for _, line := range lines[1:] { + if strings.HasPrefix(strings.TrimSpace(line), "*") { + active = line + continue + } + inactive = line + } + if active == "" || inactive == "" { + t.Fatalf("expected one marked row and one unmarked row, got %q", output) + } + if !strings.Contains(active, "XSUS") { + t.Fatalf("the marked row should be the active profile, got %q", active) + } + if !strings.Contains(active, "p2") || !strings.Contains(active, "r9") || !strings.Contains(active, "2") { + t.Fatalf("active row should carry id/revision/rule count, got %q", active) + } + if !strings.Contains(inactive, "Home") { + t.Fatalf("inactive row should name the other profile, got %q", inactive) + } +} + +func TestAppStoreProfilesJSON(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex} + s, stdout := newAppStoreSession(t, store) + s.out.json = true + if err := cmdAppProfiles(s, args("profiles")); err != nil { + t.Fatalf("profiles: %v", err) + } + var envelope struct { + OK bool `json:"ok"` + Data struct { + Active struct { + ProfileID string `json:"profileID"` + Revision string `json:"revision"` + } `json:"active"` + Profiles []struct { + ID string `json:"id"` + AppendedRules int `json:"appendedRules"` + } `json:"profiles"` + } `json:"data"` + } + if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil { + t.Fatalf("stdout is not the JSON envelope (%q): %v", stdout.String(), err) + } + if !envelope.OK || envelope.Data.Active.ProfileID != "p2" || envelope.Data.Active.Revision != "r9" { + t.Fatalf("unexpected envelope: %s", stdout.String()) + } + if len(envelope.Data.Profiles) != 2 || envelope.Data.Profiles[1].AppendedRules != 2 { + t.Fatalf("profiles should be passed through unchanged: %s", stdout.String()) + } +} + +func TestAppStoreProfilesUnpublished(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profilesCode: http.StatusServiceUnavailable} + s, _ := newAppStoreSession(t, store) + err := cmdAppProfiles(s, args("profiles")) + if exit := exitOf(t, err); exit != exitPeerError { + t.Fatalf("expected exit %d, got %d (%v)", exitPeerError, exit, err) + } + if !strings.Contains(err.Error(), "has not published") { + t.Fatalf("the controller message should be passed through, got %q", err.Error()) + } +} + +func TestAppStoreRulesAppend(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{"rules-match-v1", appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":true,"appendRules":["DOMAIN-SUFFIX,a.com,DIRECT","OLD,RULE"],"patchJSON":"{}"}`, + }, + } + s, stdout := newAppStoreSession(t, store) + err := cmdRules(s, args("rules", "append", "DOMAIN-SUFFIX,a.com,DIRECT", "DOMAIN-SUFFIX,b.com,PROXY")) + if err != nil { + t.Fatalf("rules append: %v", err) + } + path, body := store.written(t) + if path != "/clash/v1/app/profiles/p2/rules" { + t.Fatalf("the write should target the active profile, got %q", path) + } + if body["prependRules"] != true { + t.Fatalf("prependRules should be passed through, got %v", body["prependRules"]) + } + got, _ := body["appendRules"].([]any) + want := []string{"DOMAIN-SUFFIX,a.com,DIRECT", "OLD,RULE", "DOMAIN-SUFFIX,b.com,PROXY"} + if len(got) != len(want) { + t.Fatalf("expected %v, got %v", want, got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("expected %v, got %v", want, got) + } + } + if _, exists := body["patchJSON"]; exists { + t.Fatalf("patchJSON is not writable, got %v", body) + } + text := stdout.String() + if !strings.Contains(text, "追加 1 条") || !strings.Contains(text, "共 3 条") { + t.Fatalf("expected the count and the newly added rules, got %q", text) + } + if !strings.Contains(text, "下次连接生效") { + t.Fatalf("expected the next-connect hint, got %q", text) + } + if !strings.Contains(text, "1 条本来就有") { + t.Fatalf("expected the duplicate note, got %q", text) + } +} + +func TestAppStoreRulesAppendNoop(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":false,"appendRules":["OLD,RULE"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdRules(s, args("rules", "append", "OLD,RULE")); err != nil { + t.Fatalf("rules append: %v", err) + } + if len(store.puts) != 0 { + t.Fatalf("an unchanged list should not be written, got %+v", store.puts) + } + if !strings.Contains(stdout.String(), "没有变化") { + t.Fatalf("expected a no-op message, got %q", stdout.String()) + } +} + +func TestAppStoreRulesRemoveByLabel(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p1": `{"id":"p1","prependRules":false,"appendRules":["A,RULE","B,RULE"]}`, + "p2": `{"id":"p2","prependRules":false,"appendRules":["A,RULE","B,RULE","C,RULE"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + err := cmdRules(s, withFlags(args("rules", "remove", "B,RULE"), "profile", "Home")) + if err != nil { + t.Fatalf("rules remove: %v", err) + } + path, body := store.written(t) + if path != "/clash/v1/app/profiles/p1/rules" { + t.Fatalf("--profile should select by label, got %q", path) + } + got, _ := body["appendRules"].([]any) + if len(got) != 1 || got[0] != "A,RULE" { + t.Fatalf("only the matching rule should go, got %v", got) + } + if !strings.Contains(stdout.String(), "移除 1 条规则") { + t.Fatalf("expected the removal count, got %q", stdout.String()) + } +} + +func TestAppStoreRulesRemoveMatches(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":false,"appendRules":["A,RULE","B,RULE","C,RULE"]}`, + }, + } + s, _ := newAppStoreSession(t, store) + if err := cmdRules(s, args("rules", "remove", "B,RULE", "MISSING,RULE")); err != nil { + t.Fatalf("rules remove: %v", err) + } + _, body := store.written(t) + got, _ := body["appendRules"].([]any) + if len(got) != 2 || got[0] != "A,RULE" || got[1] != "C,RULE" { + t.Fatalf("expected the untouched rules in order, got %v", got) + } +} + +func TestAppStoreRulesUnknownProfile(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex} + s, _ := newAppStoreSession(t, store) + err := cmdRules(s, withFlags(args("rules", "append", "A,RULE"), "profile", "Nope")) + if exit := exitOf(t, err); exit != exitUsage { + t.Fatalf("expected exit %d, got %d (%v)", exitUsage, exit, err) + } + if !strings.Contains(err.Error(), "--profile") || !strings.Contains(err.Error(), "profiles") { + t.Fatalf("the message should point at --profile and the profiles command, got %q", err.Error()) + } + if len(store.puts) != 0 { + t.Fatalf("nothing should be written, got %+v", store.puts) + } +} + +func TestAppStoreRulesAmbiguousLabel(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: `{"active":{"profileID":"p1","revision":"r1"},"profiles":[` + + `{"id":"p1","label":"Same","order":0,"active":true},{"id":"p2","label":"Same","order":1}]}`, + } + s, _ := newAppStoreSession(t, store) + err := cmdRules(s, withFlags(args("rules", "append", "A,RULE"), "profile", "Same")) + if exit := exitOf(t, err); exit != exitUsage { + t.Fatalf("expected exit %d, got %d (%v)", exitUsage, exit, err) + } + if !strings.Contains(err.Error(), "同名") { + t.Fatalf("expected a duplicate-label hint, got %q", err.Error()) + } +} + +func TestAppStoreRulesWriteRejected(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":false,"appendRules":[]}`, + }, + codes: map[string]int{"PUT/clash/v1/app/profiles/p2/rules": http.StatusBadRequest}, + } + s, stdout := newAppStoreSession(t, store) + err := cmdRules(s, args("rules", "append", "TOO,LONG")) + if exit := exitOf(t, err); exit != exitPeerError { + t.Fatalf("expected exit %d, got %d (%v)", exitPeerError, exit, err) + } + if !strings.Contains(err.Error(), "控制器拒绝了这次改动") { + t.Fatalf("the controller message should be passed through, got %q", err.Error()) + } + if strings.Contains(stdout.String(), "✓") { + t.Fatalf("a rejected write should not claim success, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicyShow(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{ + "p2": `{"nameserverPolicy":{"+.didichuxing.com":["10.78.226.116"]},"fakeIPFilter":["+.example.com"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdDNS(s, args("dns", "policy")); err != nil { + t.Fatalf("dns policy: %v", err) + } + text := stdout.String() + for _, want := range []string{"DNS 策略:XSUS(p2)", "+.didichuxing.com → 10.78.226.116", "+.example.com"} { + if !strings.Contains(text, want) { + t.Fatalf("expected %q in the output, got %q", want, text) + } + } +} + +func TestAppStoreDNSPolicyShowEmpty(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{"p2": `{}`}, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdDNS(s, args("dns", "policy")); err != nil { + t.Fatalf("dns policy: %v", err) + } + if !strings.Contains(stdout.String(), "nameserver-policy:没有设置") || !strings.Contains(stdout.String(), "fake-ip-filter:没有设置") { + t.Fatalf("empty parts should say so, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicySetMerges(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{ + "p2": `{"nameserverPolicy":{"+.a.com":["1.1.1.1"]},"fakeIPFilter":["+.keep.com"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + err := cmdDNS(s, args("dns", "policy", "set", "+.b.com=2.2.2.2, 3.3.3.3")) + if err != nil { + t.Fatalf("dns policy set: %v", err) + } + path, body := store.written(t) + if path != "/clash/v1/app/profiles/p2/dns-policy" { + t.Fatalf("unexpected path %q", path) + } + if _, exists := body["fakeIPFilter"]; exists { + t.Fatalf("fakeIPFilter should be left alone, got %v", body) + } + policy, _ := body["nameserverPolicy"].(map[string]any) + if len(policy) != 2 { + t.Fatalf("the existing entry should be merged, got %v", policy) + } + servers, _ := policy["+.b.com"].([]any) + if len(servers) != 2 || servers[0] != "2.2.2.2" || servers[1] != "3.3.3.3" { + t.Fatalf("expected two trimmed servers, got %v", policy["+.b.com"]) + } + if !strings.Contains(stdout.String(), "写入 1 条") { + t.Fatalf("expected the merged count, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicySetRejectsBadPair(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex, dns: map[string]string{"p2": `{}`}} + s, _ := newAppStoreSession(t, store) + err := cmdDNS(s, args("dns", "policy", "set", "+.b.com")) + if exit := exitOf(t, err); exit != exitUsage { + t.Fatalf("expected exit %d, got %d (%v)", exitUsage, exit, err) + } +} + +func TestAppStoreDNSPolicyClear(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{ + "p2": `{"nameserverPolicy":{"+.a.com":["1.1.1.1"]},"fakeIPFilter":["+.keep.com"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdDNS(s, args("dns", "policy", "clear")); err != nil { + t.Fatalf("dns policy clear: %v", err) + } + _, body := store.written(t) + policy, ok := body["nameserverPolicy"].(map[string]any) + if !ok || len(policy) != 0 { + t.Fatalf("clear should send an empty nameserverPolicy, got %v", body) + } + if _, exists := body["fakeIPFilter"]; exists { + t.Fatalf("fakeIPFilter should be left alone, got %v", body) + } + if !strings.Contains(stdout.String(), "已清空 XSUS(p2)的 nameserver-policy") { + t.Fatalf("expected the clear message, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicyClearFakeIPFilter(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{"p2": `{"fakeIPFilter":["+.keep.com"]}`}, + } + s, _ := newAppStoreSession(t, store) + if err := cmdDNS(s, withFlags(args("dns", "policy", "clear"), "fake-ip-filter", "1")); err != nil { + t.Fatalf("dns policy clear --fake-ip-filter: %v", err) + } + _, body := store.written(t) + if _, exists := body["nameserverPolicy"]; exists { + t.Fatalf("nameserverPolicy should be left alone, got %v", body) + } + filter, ok := body["fakeIPFilter"].([]any) + if !ok || len(filter) != 0 { + t.Fatalf("expected an empty fakeIPFilter, got %v", body) + } +} + +func TestAppStoreRuntimeRulesUnchanged(t *testing.T) { + store := &fakeAppStore{ + profiles: testProfileIndex, + runtimeRules: `{"rules":[{"type":"DOMAIN-SUFFIX","payload":"a.com","proxy":"DIRECT"}]}`, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdRules(s, args("rules", "5")); err != nil { + t.Fatalf("rules 5: %v", err) + } + if !strings.Contains(stdout.String(), "规则 1 条") { + t.Fatalf("the running rule list should still work, got %q", stdout.String()) + } + if len(store.puts) != 0 { + t.Fatalf("reading rules must not write, got %+v", store.puts) + } +} + +func TestMergeAppendRules(t *testing.T) { + merged, appended := mergeAppendRules([]string{"A", "B", "A"}, []string{"B", "C", "C", "D"}) + if appended != 2 { + t.Fatalf("expected 2 new rules, got %d (%v)", appended, merged) + } + want := []string{"A", "B", "C", "D"} + if len(merged) != len(want) { + t.Fatalf("expected %v, got %v", want, merged) + } + for i := range want { + if merged[i] != want[i] { + t.Fatalf("expected %v, got %v", want, merged) + } + } +} + +func TestAppStoreRunReportsMissingCapability(t *testing.T) { + store := &fakeAppStore{profiles: testProfileIndex} + server := httptest.NewServer(store) + defer server.Close() + for _, tc := range []struct { + name string + args []string + }{{"human", []string{"profiles"}}, {"json", []string{"--json", "profiles"}}} { + t.Run(tc.name, func(t *testing.T) { + var stdout, stderr bytes.Buffer + env := environment{ + args: tc.args, + getenv: func(key string) string { + if key == "CLASH_API" { + return server.URL + } + return "" + }, + stdin: strings.NewReader(""), + stdout: &stdout, stderr: &stderr, + homeDir: t.TempDir(), + } + if exit := run(env); exit != exitUnsupported { + t.Fatalf("expected exit %d, got %d (stdout %q, stderr %q)", exitUnsupported, exit, stdout.String(), stderr.String()) + } + if tc.name == "human" { + if !strings.Contains(stderr.String(), "还不支持 App 配置读写") { + t.Fatalf("expected the hint on stderr, got %q", stderr.String()) + } + return + } + var envelope struct { + OK bool `json:"ok"` + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil { + t.Fatalf("stdout is not a JSON envelope (%q): %v", stdout.String(), err) + } + if envelope.OK || envelope.Error.Code != "unsupported" || !strings.Contains(envelope.Error.Message, appStoreCapability) { + t.Fatalf("unexpected envelope: %s", stdout.String()) + } + }) + } +} diff --git a/cli/args.go b/cli/args.go index 4f5dfa9..9181743 100644 --- a/cli/args.go +++ b/cli/args.go @@ -17,9 +17,9 @@ var ( globalValueOptions = map[string]string{"u": "url", "url": "url", "secret": "secret", "fingerprint": "fingerprint", "timeout": "timeout"} globalBoolOptions = map[string]string{"json": "json", "secret-stdin": "secret-stdin"} commandValueOptions = map[string]string{"level": "level", "test-url": "test-url", "delay-timeout": "delay-timeout", - "geodata-dir": "geodata-dir", "interval": "interval"} + "geodata-dir": "geodata-dir", "interval": "interval", "profile": "profile"} commandBoolOptions = map[string]string{"f": "follow", "follow": "follow", "resolve": "resolve", "all": "all", - "h": "help", "help": "help"} + "fake-ip-filter": "fake-ip-filter", "h": "help", "help": "help"} ) func parseArguments(args []string, options *globalOptions) (parsedArguments, error) { diff --git a/cli/commands.go b/cli/commands.go index fd2d32d..099526f 100644 --- a/cli/commands.go +++ b/cli/commands.go @@ -32,6 +32,7 @@ func init() { "conn": cmdConn, "traffic": cmdTraffic, "rules": cmdRules, + "profiles": cmdAppProfiles, "configs": cmdConfigs, "dns": cmdDNS, "logs": cmdLogs, @@ -987,7 +988,11 @@ func cmdLogs(s *session, p parsedArguments) error { } func cmdRules(s *session, p parsedArguments) error { - return listRules(s, p.positional[1:]) + rest := p.positional[1:] + if len(rest) > 0 && (rest[0] == "append" || rest[0] == "remove") { + return cmdRulesEdit(s, p, rest[0], rest[1:]) + } + return listRules(s, rest) } func listRules(s *session, rest []string) error { @@ -1213,8 +1218,11 @@ func ruleMatch(s *session, target string, pairs []string, resolve bool) error { func cmdDNS(s *session, p parsedArguments) error { args := p.positional[1:] + if len(args) > 0 && args[0] == "policy" { + return cmdDNSPolicy(s, p) + } if len(args) < 2 || (args[0] != "query" && args[0] != "explain") { - return usage("clash-cli dns query <域名> [type] | dns explain <域名> [type]") + return usage("clash-cli dns query <域名> [type] | dns explain <域名> [type] | dns policy [set|clear]") } recordType := "A" if len(args) > 2 { diff --git a/cli/main.go b/cli/main.go index 7f7d0c6..8bb71f9 100644 --- a/cli/main.go +++ b/cli/main.go @@ -260,8 +260,19 @@ const usageText = `clash-cli —— Clash App 内置的命令行工具 conn close 关闭一条或全部连接(all 会打断下载与 SSH) flush fakeip|dns 清空 fake-ip 池或 DNS 缓存 +配置库(改 App 里存的那份配置,不动现在的连接,下次连接生效): + profiles App 里的配置列表(* 当前) + rules append <规则>... 往这份配置里追加规则(--profile ,缺省当前配置) + rules remove <规则>... 从这份配置里删掉这些规则 + dns policy 这份配置的 DNS 策略 + dns policy set '+.域名=地址[,地址]'... + 合并写入 nameserver-policy + dns policy clear [--fake-ip-filter] + 清空 nameserver-policy(或 fake-ip-filter) + 改的是 App 的配置库(store/profiles.json),不重建派生产物;内核还不支持时退出码 5。 + 不提供: reload、check(配置由 Clash App 管理和检查,退出码 5)。 -退出码: 0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒;5 不是 Clash App 的控制器或不支持; -6 证书指纹不符或未确认。 +退出码: 0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒; +5 不是 Clash App 的控制器或不支持(含配置库不支持);6 证书指纹不符或未确认。 ` From f28a5f9edc1d8df1e85fe88936b239775deda588 Mon Sep 17 00:00:00 2001 From: jeffjiang Date: Mon, 16 Nov 2026 21:25:21 +0800 Subject: [PATCH 2/2] Rebuild published configs when a profile's CLI-edited inputs change The app-store endpoints write config inputs (override rules and the runtime DNS patch) straight into the profile store. Without this, the derived files (published rules, the resolved runtime config) are only rebuilt when the app decides to regenerate them, so an edit made over the controller stayed invisible until an unrelated change forced a rebuild. A stamp keeps a fingerprint of the inputs the published revision was built from, and the activation preflight compares it before starting. --- .../Shared/ConfigResourceStore.swift | 2 + .../ConfigStore/ActiveRevisionMigration.swift | 14 +++- .../ProfileActivationCoordinator.swift | 1 + .../ConfigStore/ProfileInputsStamp.swift | 77 +++++++++++++++++++ 4 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift diff --git a/apple/ClashClient/Shared/ConfigResourceStore.swift b/apple/ClashClient/Shared/ConfigResourceStore.swift index a6d443a..68517df 100644 --- a/apple/ClashClient/Shared/ConfigResourceStore.swift +++ b/apple/ClashClient/Shared/ConfigResourceStore.swift @@ -209,6 +209,8 @@ final class ConfigResourceStore { activeDirectoryURL.appendingPathComponent(Name.compatibilityConfiguration) } + var workingDirectoryURL: URL { workingURL } + init( containerURL: URL, maximumConfigurationBytes: Int = ConfigResourceStore.defaultMaximumConfigurationBytes, diff --git a/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift b/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift index f96d0ce..be5e932 100644 --- a/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift +++ b/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift @@ -89,7 +89,11 @@ final class ActiveRevisionMigrator { profileID: currentPointer.profileID, revision: currentPointer.revision ) - if validates(active) { + let inputsChanged = ProfileInputsStamp.inputsChanged( + currentPointer, + workingDirectory: store.workingDirectoryURL + ) + if !inputsChanged, validates(active) { return StartupConfigurationPreparation( configuration: active, recovery: .current @@ -112,8 +116,12 @@ final class ActiveRevisionMigrator { } expectedPointer = rebuiltPointer } catch { - - + if validates(active) { + return StartupConfigurationPreparation( + configuration: active, + recovery: .current + ) + } } } diff --git a/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift b/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift index a89b1e2..faa2f00 100644 --- a/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift +++ b/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift @@ -3469,6 +3469,7 @@ final class ProfileActivationCoordinator { } PublishedSourceLedger.record(published, digest: sourceDigest?.ledger) PublishedRulesAsWritten.record(published, section: rulesAsWritten, workingDirectory: coreHomeDir) + ProfileInputsStamp.record(published, profile: profile, workingDirectory: coreHomeDir) diff --git a/apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift b/apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift new file mode 100644 index 0000000..de1432f --- /dev/null +++ b/apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift @@ -0,0 +1,77 @@ +import CryptoKit +import Foundation + +enum ProfileInputsStamp { + static let fileName = "published-inputs.json" + private static let schemaVersion = 1 + private static let storeDirectoryName = "store" + + private struct Record: Codable { + let schemaVersion: Int + let profileID: String + let revision: String + let inputs: String + } + + private struct Inputs: Encodable { + let appendRules: [String] + let prependRules: Bool + let legacyRuntimePatchJSON: String? + } + + private static func url(workingDirectory: URL) -> URL { + workingDirectory + .appendingPathComponent(storeDirectoryName, isDirectory: true) + .appendingPathComponent(fileName) + } + + private static func digest(of profile: Profile) -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + guard let data = try? encoder.encode(Inputs( + appendRules: profile.override.appendRules, + prependRules: profile.override.prependRules, + legacyRuntimePatchJSON: profile.legacyRuntimePatchJSON + )) else { return "" } + return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } + + static func record(_ pointer: ActiveConfigurationPointer, profile: Profile, workingDirectory: URL) { + let file = url(workingDirectory: workingDirectory) + let record = Record( + schemaVersion: schemaVersion, + profileID: pointer.profileID, + revision: pointer.revision, + inputs: digest(of: profile) + ) + guard let data = try? JSONEncoder().encode(record) else { return } + try? FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try? data.write(to: file, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + } + + private static func read(workingDirectory: URL) -> Record? { + guard let data = try? Data(contentsOf: url(workingDirectory: workingDirectory)) else { return nil } + return try? JSONDecoder().decode(Record.self, from: data) + } + + static func inputsChanged(_ pointer: ActiveConfigurationPointer, workingDirectory: URL) -> Bool { + guard let profile = storedProfile(pointer.profileID, workingDirectory: workingDirectory) else { + return false + } + guard let record = read(workingDirectory: workingDirectory) else { return true } + return record.schemaVersion != schemaVersion + || record.profileID != pointer.profileID + || record.revision != pointer.revision + || record.inputs != digest(of: profile) + } + + private static func storedProfile(_ profileID: String, workingDirectory: URL) -> Profile? { + let file = workingDirectory + .appendingPathComponent(storeDirectoryName, isDirectory: true) + .appendingPathComponent("profiles.json") + return ProfileStore(fileURL: file).load().first { $0.id == profileID } + } +}