跳到主要内容

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

浏览文件

github.go

245 行 · 8.9 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package limatmpl
5
6import (
7 "cmp"
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "net/http"
14 "os"
15 "path"
16 "strings"
17)
18
19const defaultFilename = ".lima.yaml"
20
21// transformGitHubURL transforms a github: URL to a raw.githubusercontent.com URL.
22// Input format: ORG/REPO[/PATH][@BRANCH]
23//
24// If REPO is missing, it will be set the same as ORG.
25// If BRANCH is missing, it will be queried from GitHub.
26// If PATH filename has no extension, it will get .yaml.
27// If PATH is just a directory (trailing slash), it will be set to .lima.yaml
28// IF FILE is .lima.yaml and contents looks like a symlink, it will be replaced by the symlink target.
29func transformGitHubURL(ctx context.Context, input string) (string, error) {
30 input, origBranch, _ := strings.Cut(input, "@")
31
32 parts := strings.Split(input, "/")
33 for len(parts) < 2 {
34 parts = append(parts, "")
35 }
36 org := parts[0]
37 if org == "" {
38 return "", fmt.Errorf("github: URL must contain at least an ORG, got %#q", input)
39 }
40 // If REPO is omitted (github:ORG or github:ORG//PATH), default it to ORG
41 repo := cmp.Or(parts[1], org)
42 filePath := strings.Join(parts[2:], "/")
43
44 // A `..` in REPO, PATH, or BRANCH collapses server-side and moves the fetch
45 // to an unrelated org. Redirect bodies re-enter here, so treat them as untrusted.
46 if repo == ".." {
47 return "", fmt.Errorf("repo %#q in github: URL %#q escapes the org", repo, input)
48 }
49 if escapesRepo(filePath) {
50 return "", fmt.Errorf("path %#q in github: URL %#q escapes the repository", filePath, input)
51 }
52 if escapesRepo(origBranch) {
53 return "", fmt.Errorf("branch %#q in github: URL %#q escapes the repository", origBranch, input)
54 }
55
56 if filePath == "" {
57 filePath = defaultFilename
58 } else {
59 // If path ends with / then it's a directory, so append .lima
60 if strings.HasSuffix(filePath, "/") {
61 filePath += defaultFilename
62 }
63
64 // If the filename (excluding first char for hidden files) has no extension, add .yaml
65 filename := path.Base(filePath)
66 if !strings.Contains(filename[1:], ".") {
67 filePath += ".yaml"
68 }
69 }
70
71 // Query default branch if no branch was specified
72 branch := origBranch
73 if branch == "" {
74 var err error
75 branch, err = getGitHubDefaultBranch(ctx, org, repo)
76 if err != nil {
77 return "", fmt.Errorf("failed to get default branch for %s/%s: %w", org, repo, err)
78 }
79 }
80
81 // If filename has a .yaml/.yml extension, check if it's a symlink/redirect to another file
82 ext := strings.ToLower(path.Ext(filePath))
83 if ext == ".yaml" || ext == ".yml" {
84 return resolveGitHubSymlink(ctx, org, repo, branch, filePath, origBranch)
85 }
86 return githubUserContentURL(org, repo, branch, filePath), nil
87}
88
89func githubUserContentURL(org, repo, branch, filePath string) string {
90 // Emit a cleaned path so we never rely on the server to resolve `../`,
91 // even for in-repo segments that don't escape.
92 return fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/%s", org, repo, branch, path.Clean(filePath))
93}
94
95func getGitHubUserContent(ctx context.Context, org, repo, branch, filePath string) (*http.Response, error) {
96 url := githubUserContentURL(org, repo, branch, filePath)
97 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
98 if err != nil {
99 return nil, fmt.Errorf("failed to create request: %w", err)
100 }
101 req.Header.Set("User-Agent", "lima")
102 return http.DefaultClient.Do(req)
103}
104
105// getGitHubDefaultBranch queries the GitHub API to get the default branch for a repository.
106func getGitHubDefaultBranch(ctx context.Context, org, repo string) (string, error) {
107 apiURL := fmt.Sprintf("https://api.github.com/repos/%s/%s", org, repo)
108
109 req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, http.NoBody)
110 if err != nil {
111 return "", fmt.Errorf("failed to create request: %w", err)
112 }
113
114 req.Header.Set("User-Agent", "lima")
115 req.Header.Set("Accept", "application/vnd.github.v3+json")
116
117 // Check for GitHub token in environment for authenticated requests (higher rate limit)
118 token := cmp.Or(os.Getenv("GH_TOKEN"), os.Getenv("GITHUB_TOKEN"))
119 if token != "" {
120 req.Header.Set("Authorization", "token "+token)
121 }
122
123 resp, err := http.DefaultClient.Do(req)
124 if err != nil {
125 return "", fmt.Errorf("failed to query GitHub API: %w", err)
126 }
127 defer resp.Body.Close()
128
129 body, err := io.ReadAll(resp.Body)
130 if err != nil {
131 return "", fmt.Errorf("failed to read GitHub API response: %w", err)
132 }
133 if resp.StatusCode != http.StatusOK {
134 return "", fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, string(body))
135 }
136
137 var repoData struct {
138 DefaultBranch string `json:"default_branch"`
139 }
140 if err := json.Unmarshal(body, &repoData); err != nil {
141 return "", fmt.Errorf("failed to parse GitHub API response: %w", err)
142 }
143 if repoData.DefaultBranch == "" {
144 return "", fmt.Errorf("repository %s/%s has no default branch", org, repo)
145 }
146 return repoData.DefaultBranch, nil
147}
148
149// resolveGitHubSymlink checks if a file at the given path is a symlink/redirect to another file.
150// If the file contains a single line without newline, space, or colon then it's treated as a path to the actual file.
151// Returns a URL to the redirect path if found, or a URL for original path otherwise.
152func resolveGitHubSymlink(ctx context.Context, org, repo, branch, filePath, origBranch string) (string, error) {
153 resp, err := getGitHubUserContent(ctx, org, repo, branch, filePath)
154 if err != nil {
155 return "", fmt.Errorf("failed to fetch file: %w", err)
156 }
157 defer resp.Body.Close()
158
159 // Special rule for branch/tag propagation for github:ORG// requests.
160 if resp.StatusCode == http.StatusNotFound && repo == org {
161 defaultBranch, err := getGitHubDefaultBranch(ctx, org, repo)
162 if err == nil {
163 return resolveGitHubRedirect(ctx, org, repo, defaultBranch, filePath, branch)
164 }
165 }
166 if resp.StatusCode != http.StatusOK {
167 return "", fmt.Errorf("file %#q not found or inaccessible: status %d", resp.Request.URL, resp.StatusCode)
168 }
169
170 // Read first 1KB to check the file content
171 buf := make([]byte, 1024)
172 n, err := resp.Body.Read(buf)
173 if err != nil && !errors.Is(err, io.EOF) {
174 return "", fmt.Errorf("failed to read %#q content: %w", resp.Request.URL, err)
175 }
176 content := string(buf[:n])
177
178 // Symlink can also be a github: redirect if we are in a github:ORG// repo.
179 if repo == org && strings.HasPrefix(content, "github:") {
180 return validateGitHubRedirect(content, org, origBranch, resp.Request.URL.String())
181 }
182
183 // A symlink must be a single line (without trailing newline), no spaces, no colons
184 if !(content == "" || strings.ContainsAny(content, "\n :")) {
185 // symlink is relative to the directory of filePath, and must stay within the repo
186 filePath, err = symlinkTarget(filePath, content)
187 if err != nil {
188 return "", err
189 }
190 }
191 return githubUserContentURL(org, repo, branch, filePath), nil
192}
193
194// symlinkTarget resolves a symlink target relative to the directory of filePath.
195// It returns an error if the target escapes the repository root, so a symlink
196// cannot redirect the fetch to a different repository via `../` segments.
197func symlinkTarget(filePath, target string) (string, error) {
198 resolved := path.Join(path.Dir(filePath), target)
199 if escapesRepo(resolved) {
200 return "", fmt.Errorf("symlink target %#q in %#q escapes the repository", target, filePath)
201 }
202 return resolved, nil
203}
204
205// escapesRepo reports whether the cleaned path climbs above the repository root.
206func escapesRepo(p string) bool {
207 p = path.Clean(p)
208 return p == ".." || strings.HasPrefix(p, "../")
209}
210
211// resolveGitHubRedirect checks if a file at the given path is a github: URL to another file within the same repo.
212// Returns the URL, or an error if the file doesn't exist, or doesn't start with github:ORG.
213func resolveGitHubRedirect(ctx context.Context, org, repo, defaultBranch, filePath, origBranch string) (string, error) {
214 // Refetch the filepath from the defaultBranch
215 resp, err := getGitHubUserContent(ctx, org, repo, defaultBranch, filePath)
216 if err != nil {
217 return "", fmt.Errorf("failed to fetch file: %w", err)
218 }
219 defer resp.Body.Close()
220 if resp.StatusCode != http.StatusOK {
221 return "", fmt.Errorf("file %#q not found or inaccessible: status %d", resp.Request.URL, resp.StatusCode)
222 }
223 body, err := io.ReadAll(resp.Body)
224 if err != nil {
225 return "", fmt.Errorf("failed to read %#q content: %w", resp.Request.URL, err)
226 }
227 return validateGitHubRedirect(string(body), org, origBranch, resp.Request.URL.String())
228}
229
230func validateGitHubRedirect(body, org, origBranch, url string) (string, error) {
231 redirect, _, _ := strings.Cut(body, "\n")
232 redirect = strings.TrimSpace(redirect)
233
234 if !strings.HasPrefix(redirect, "github:"+org+"/") {
235 return "", fmt.Errorf("redirect %#q is not a `github:%s` URL (from %#q)", redirect, org, url)
236 }
237 if strings.ContainsRune(redirect, '@') {
238 return "", fmt.Errorf("redirect %#q must not include a branch/tag/sha (from %#q)", redirect, url)
239 }
240 // If the origBranch is empty, then we need to look up the default branch in the redirect
241 if origBranch != "" {
242 redirect += "@" + origBranch
243 }
244 return redirect, nil
245}