跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

import.go

356 行 · 10.5 KB历史下载
1package managedproxy
2
3import (
4 "crypto/sha256"
5 "encoding/hex"
6 "errors"
7 "fmt"
8 "maps"
9 "net/http"
10 "strconv"
11 "strings"
12
13 "go.yaml.in/yaml/v3"
14 "golang.org/x/net/http/httpguts"
15)
16
17// NodeIssue contains display metadata only, never node credentials or field values.
18type NodeIssue struct {
19 Index int `json:"index"`
20 Name string `json:"name,omitempty"`
21 Type string `json:"type,omitempty"`
22 Reason string `json:"reason"`
23}
24
25// Parse enforces Cage's import boundaries. Call Validate before committing a
26// candidate source; protocol parameters are interpreted by the bundled core.
27// Store.Import also retains skipped-node details.
28func Parse(data []byte, sourceID string) ([]Node, error) {
29 nodes, _, err := parseNodes(data, sourceID)
30 return nodes, err
31}
32
33// Node-only import keeps remote files from changing listeners, routes, or file paths.
34func parseNodes(data []byte, sourceID string) ([]Node, []NodeIssue, error) {
35 if len(data) == 0 || len(data) > MaxImport {
36 return nil, nil, errors.New("配置为空或超过 8 MiB")
37 }
38 var input struct {
39 Proxies []map[string]any `yaml:"proxies"`
40 Payload []map[string]any `yaml:"payload"`
41 }
42 if yaml.Unmarshal(data, &input) != nil {
43 return nil, nil, errors.New("无法读取 YAML,请导入 Clash/Mihomo 节点订阅或配置;暂不支持 Base64 列表或分享链接")
44 }
45 proxies := input.Proxies
46 if len(proxies) == 0 {
47 proxies = input.Payload
48 }
49 if len(proxies) == 0 || len(proxies) > 3000 {
50 return nil, nil, errors.New("配置需要包含 1–3000 个 proxies 节点;仅含远程 provider 的配置请改为导入节点订阅链接")
51 }
52 types := map[string]bool{}
53 for _, k := range strings.Fields("http socks5 ss ssr vmess vless trojan hysteria hysteria2 tuic anytls mieru") {
54 types[k] = true
55 }
56 counts := map[string]int{}
57 keyErrors := make([]error, len(proxies))
58 for i, p := range proxies {
59 // Canonicalize only fields Cage reads or rewrites. Protocol parameters
60 // and opaque maps such as HTTP headers belong to the bundled core.
61 keyErrors[i] = normalizeImportKeys(p, "name", "type", "server", "udp", "dialer-proxy")
62 name, _ := p["name"].(string)
63 counts[name]++
64 }
65 issues := make([]NodeIssue, len(proxies))
66 names := map[string]string{}
67 indexes := map[string]int{}
68 candidates := make([]Node, 0, len(proxies))
69 for i, p := range proxies {
70 name, _ := p["name"].(string)
71 typ, _ := p["type"].(string)
72 server, _ := p["server"].(string)
73 issue := NodeIssue{Index: i + 1}
74 if len(name) <= 240 {
75 issue.Name = name
76 }
77 if types[typ] {
78 issue.Type = typ
79 }
80 switch {
81 case keyErrors[i] != nil:
82 issue.Reason = keyErrors[i].Error()
83 case strings.TrimSpace(name) == "" || len(name) > 240:
84 issue.Reason = "节点名称为空或过长"
85 case counts[name] > 1:
86 issue.Reason = "节点名称重复,无法确定代理链引用"
87 case !types[typ]:
88 issue.Reason = "节点协议暂不支持"
89 case server == "" || len(server) > 253:
90 issue.Reason = "节点服务器缺失或过长"
91 default:
92 if err := normalizeWebSocket(p); err != nil {
93 issue.Reason = err.Error()
94 } else if unsafeOption(p) {
95 issue.Reason = "节点不能引用本机文件、网络接口或额外路由"
96 } else if typ == "hysteria2" {
97 if err := normalizeHysteria2(p); err != nil {
98 issue.Reason = err.Error()
99 }
100 }
101 }
102 issues[i] = issue
103 if issue.Reason != "" {
104 continue
105 }
106 h := sha256.Sum256([]byte(sourceID + "\x00" + name))
107 id := hex.EncodeToString(h[:12])
108 names[name], indexes[id] = id, i
109 candidates = append(candidates, Node{ID: id, Name: name, Type: typ, Config: p})
110 }
111 byID := map[string]Node{}
112 for _, n := range candidates {
113 p := n.Config
114 p["name"], p["udp"] = n.ID, false
115 if v, exists := p["dialer-proxy"]; exists {
116 target, ok := v.(string)
117 if !ok || names[target] == "" {
118 issues[indexes[n.ID]].Reason = "代理链必须引用同一来源中成功导入的具体节点,不能引用 DIRECT 或选择分组"
119 } else {
120 p["dialer-proxy"] = names[target]
121 }
122 }
123 byID[n.ID] = n
124 }
125 // Resolve every dependency before retaining nodes. Dropping a failed dialer
126 // would silently remove a transit hop; its dependents must be skipped too.
127 state := map[string]int{}
128 var usable func(string) bool
129 usable = func(id string) bool {
130 i := indexes[id]
131 if issues[i].Reason != "" {
132 return false
133 }
134 if state[id] == 2 {
135 return true
136 }
137 if state[id] == 1 {
138 issues[i].Reason = "代理链存在循环"
139 return false
140 }
141 state[id] = 1
142 if target, _ := byID[id].Config["dialer-proxy"].(string); target != "" && !usable(target) {
143 if issues[i].Reason == "" {
144 issues[i].Reason = "代理链依赖的中转节点不可用或存在循环"
145 }
146 return false
147 }
148 state[id] = 2
149 return true
150 }
151 out := make([]Node, 0, len(candidates))
152 for _, n := range candidates {
153 if usable(n.ID) {
154 out = append(out, n)
155 }
156 }
157 skipped := []NodeIssue{}
158 for _, issue := range issues {
159 if issue.Reason != "" {
160 skipped = append(skipped, issue)
161 }
162 }
163 if len(out) == 0 {
164 var details []string
165 for _, issue := range skipped[:min(3, len(skipped))] {
166 details = append(details, fmt.Sprintf("第 %d 个节点 %q:%s", issue.Index, issue.Name, issue.Reason))
167 }
168 return nil, skipped, fmt.Errorf("没有可导入的节点,已跳过 %d 个;%s", len(skipped), strings.Join(details, ";"))
169 }
170 return out, skipped, nil
171}
172
173// Mihomo's decoder matches keys case-insensitively and treats '_' as '-'.
174func optionKey(key string) string {
175 return strings.ToLower(strings.ReplaceAll(key, "_", "-"))
176}
177
178func normalizeImportKeys(p map[string]any, keys ...string) error {
179 for _, canonical := range keys {
180 found := ""
181 for key := range p {
182 if optionKey(key) != optionKey(canonical) {
183 continue
184 }
185 if found != "" {
186 return fmt.Errorf("节点字段 %s 存在重复写法,请仅保留一种", canonical)
187 }
188 found = key
189 }
190 if found != "" && found != canonical {
191 p[canonical] = p[found]
192 delete(p, found)
193 }
194 }
195 return nil
196}
197
198func normalizeHysteria2(p map[string]any) error {
199 if err := normalizeImportKeys(p, "mport", "ports", "pinSHA256", "fingerprint"); err != nil {
200 return err
201 }
202 for _, alias := range []struct {
203 from, to string
204 normalize func(any) (string, error)
205 }{
206 {"mport", "ports", hysteria2Ports},
207 {"pinSHA256", "fingerprint", hysteria2Pin},
208 } {
209 raw, exists := p[alias.from]
210 if !exists {
211 continue
212 }
213 value, err := alias.normalize(raw)
214 if err != nil {
215 return fmt.Errorf("Hysteria2 字段 %s 无效,未忽略该字段", alias.from)
216 }
217 if current, exists := p[alias.to]; exists {
218 canonical, err := alias.normalize(current)
219 if err != nil || canonical != value {
220 return fmt.Errorf("Hysteria2 字段 %s 与 %s 冲突", alias.from, alias.to)
221 }
222 }
223 p[alias.to] = value
224 delete(p, alias.from)
225 }
226 return nil
227}
228
229// Legacy WebSocket fields are accepted by the core but ignored by its transport.
230// Normalize only nodes carrying aliases, leaving other protocol options alone.
231func normalizeWebSocket(p map[string]any) error {
232 legacy := false
233 for key := range p {
234 if optionKey(key) == "ws-path" || optionKey(key) == "ws-headers" {
235 legacy = true
236 }
237 }
238 if !legacy {
239 return nil
240 }
241 if err := normalizeImportKeys(p, "ws-path", "ws-headers", "ws-opts", "network"); err != nil {
242 return err
243 }
244 if p["type"] != "vmess" && p["type"] != "vless" && p["type"] != "trojan" {
245 return errors.New("旧 WebSocket 字段仅适用于 VMess、VLESS 或 Trojan 节点")
246 }
247 if p["network"] != "ws" {
248 return errors.New("旧 WebSocket 字段需要显式设置 network: ws,请核对节点传输方式")
249 }
250 opts := map[string]any{}
251 if raw, exists := p["ws-opts"]; exists {
252 current, ok := raw.(map[string]any)
253 if !ok {
254 return errors.New("WebSocket 字段 ws-opts 无效,未忽略旧字段")
255 }
256 opts = maps.Clone(current)
257 }
258 if err := normalizeImportKeys(opts, "path", "headers"); err != nil {
259 return err
260 }
261 if raw, exists := p["ws-path"]; exists {
262 path, ok := raw.(string)
263 if !ok {
264 return errors.New("WebSocket 字段 ws-path 无效,未忽略该字段")
265 }
266 if current, exists := opts["path"]; exists && current != path {
267 return errors.New("WebSocket 字段 ws-path 与 ws-opts.path 冲突")
268 }
269 opts["path"] = path
270 delete(p, "ws-path")
271 }
272 if raw, exists := p["ws-headers"]; exists {
273 headers, err := webSocketHeaders(raw)
274 if err != nil {
275 return err
276 }
277 if current, exists := opts["headers"]; exists {
278 modern, err := webSocketHeaders(current)
279 if err != nil {
280 return err
281 }
282 for key, value := range modern {
283 if previous, exists := headers[key]; exists && previous != value {
284 return errors.New("WebSocket 字段 ws-headers 与 ws-opts.headers 冲突")
285 }
286 headers[key] = value
287 }
288 }
289 opts["headers"] = headers
290 delete(p, "ws-headers")
291 }
292 p["ws-opts"] = opts
293 return nil
294}
295
296func webSocketHeaders(raw any) (map[string]any, error) {
297 input, ok := raw.(map[string]any)
298 if !ok {
299 return nil, errors.New("WebSocket 请求头必须为字符串映射,未忽略该字段")
300 }
301 headers := make(map[string]any, len(input))
302 for key, rawValue := range input {
303 value, ok := rawValue.(string)
304 if !ok || !httpguts.ValidHeaderFieldName(key) || !httpguts.ValidHeaderFieldValue(value) {
305 return nil, errors.New("WebSocket 请求头无效,未忽略该字段")
306 }
307 key = http.CanonicalHeaderKey(key)
308 if previous, exists := headers[key]; exists && previous != value {
309 return nil, errors.New("WebSocket 请求头存在大小写不同的冲突写法")
310 }
311 headers[key] = value
312 }
313 return headers, nil
314}
315
316func hysteria2Ports(raw any) (string, error) {
317 var ports string
318 switch v := raw.(type) {
319 case string:
320 ports = strings.TrimSpace(v)
321 case int:
322 ports = strconv.Itoa(v)
323 }
324 parts := strings.Split(strings.ReplaceAll(ports, "/", ","), ",")
325 if ports == "" || len(parts) > 28 {
326 return "", errors.New("invalid ports")
327 }
328 for i, part := range parts {
329 rangeParts := strings.Split(strings.TrimSpace(part), "-")
330 if len(rangeParts) > 2 {
331 return "", errors.New("invalid port range")
332 }
333 for j, port := range rangeParts {
334 n, err := strconv.Atoi(strings.TrimSpace(port))
335 if err != nil || n < 1 || n > 65535 {
336 return "", errors.New("invalid port")
337 }
338 rangeParts[j] = strconv.Itoa(n)
339 }
340 parts[i] = strings.Join(rangeParts, "-")
341 }
342 return strings.Join(parts, ","), nil
343}
344
345func hysteria2Pin(raw any) (string, error) {
346 value, ok := raw.(string)
347 if !ok {
348 return "", errors.New("invalid pin")
349 }
350 value = strings.TrimSpace(strings.ReplaceAll(value, ":", ""))
351 pin, err := hex.DecodeString(value)
352 if err != nil || len(pin) != sha256.Size {
353 return "", errors.New("invalid pin")
354 }
355 return hex.EncodeToString(pin), nil
356}