跳到主要内容

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

浏览文件

guard.go

451 行 · 15.4 KB历史下载
1// Package guard asks the user before the VM changes a file their machine runs
2// on its own (direnv's .envrc when they enter the folder, the editor's tasks,
3// git hooks' config): the shares' SFTP server calls Allow before each write
4// (sshocker's Guard), in the hostagent. Files the agent edits as a matter of
5// course (Makefile, package.json) are guarded only when the user lists them.
6package guard
7
8import (
9 "bufio"
10 "context"
11 "errors"
12 "fmt"
13 "io/fs"
14 "os"
15 "path"
16 "runtime"
17 "strings"
18 "sync"
19 "time"
20 "unicode"
21
22 "github.com/lima-vm/sshocker/pkg/reversesshfs"
23 "github.com/sylvinus/agent-vm/internal/desktop"
24)
25
26// FileName is the list's file in agent-vm's state folder: one path a line,
27// added to Defaults; "!path" removes one.
28const FileName = "guarded"
29
30// Defaults are guarded unless the user removes them, each with what runs it.
31// A path naming a folder guards everything in it.
32var Defaults = map[string]string{
33 ".envrc": "direnv runs it when you enter the folder.",
34
35 ".vscode/tasks.json": "VS Code can run its tasks when the folder opens.",
36 ".vscode/settings.json": "VS Code reads commands from it (terminal profiles, tools to run).",
37 ".vscode/launch.json": "VS Code runs it when you debug.",
38 ".vscode/mcp.json": "VS Code starts the MCP servers it lists.",
39
40 ".devcontainer/devcontainer.json": "VS Code runs its initializeCommand on your machine when you reopen the folder in a container.",
41 ".devcontainer.json": "VS Code runs its initializeCommand on your machine when you reopen the folder in a container.",
42
43 ".idea/runConfigurations": "JetBrains IDEs run these configurations on your machine.",
44 ".idea/watchers.xml": "JetBrains IDEs run its file watchers on your machine each time you save.",
45 ".zed/settings.json": "Zed starts the language servers it names.",
46 ".zed/tasks.json": "Zed runs its tasks.",
47 ".dir-locals.el": "Emacs applies its settings, which can evaluate code, when you open a file.",
48
49 ".claude/settings.json": "Claude Code runs the hooks it lists on your machine.",
50 ".claude/settings.local.json": "Claude Code runs the hooks it lists on your machine.",
51 ".mcp.json": "Claude Code starts the MCP servers it lists.",
52 ".cursor/mcp.json": "Cursor starts the MCP servers it lists.",
53 ".cursor/hooks.json": "Cursor runs the hooks it lists on your machine.",
54 ".codex/config.toml": "Codex starts the MCP servers and programs it lists.",
55 ".gemini/settings.json": "Gemini CLI starts the MCP servers and hooks it lists.",
56
57 ".pre-commit-config.yaml": "pre-commit runs its hooks on your commits.",
58 "lefthook.yml": "lefthook runs its hooks on your commits.",
59 ".lefthook.yml": "lefthook runs its hooks on your commits.",
60 "lefthook.yaml": "lefthook runs its hooks on your commits.",
61 ".lefthook.yaml": "lefthook runs its hooks on your commits.",
62 "lefthook-local.yml": "lefthook runs its hooks on your commits.",
63 ".lefthook-local.yml": "lefthook runs its hooks on your commits.",
64 ".husky": "Git runs these hooks on your commits.",
65 ".githooks": "Git runs these hooks on your commits when core.hooksPath points here.",
66
67 "mise.toml": "mise runs its hooks and tasks when you enter the folder.",
68 ".mise.toml": "mise runs its hooks and tasks when you enter the folder.",
69 "mise.local.toml": "mise runs its hooks and tasks when you enter the folder.",
70 ".mise.local.toml": "mise runs its hooks and tasks when you enter the folder.",
71 ".mise": "mise runs its config and tasks when you enter the folder.",
72 ".config/mise.toml": "mise runs its hooks and tasks when you enter the folder.",
73 ".config/mise": "mise runs its config and tasks when you enter the folder.",
74 ".yarnrc.yml": "yarn runs the program its yarnPath and plugins name.",
75 ".yarn/releases": "yarn runs these files.",
76 ".yarn/plugins": "yarn runs these files.",
77 ".pnpmfile.cjs": "pnpm runs it when you install.",
78 ".npmrc": "npm can run the program its script-shell or git settings name.",
79 ".cargo/config.toml": "cargo can run the program its runner and wrapper settings name.",
80 ".cargo/config": "cargo can run the program its runner and wrapper settings name.",
81 ".lfsconfig": "git-lfs sends your files and credentials to the server it names.",
82}
83
84// WindowsDefaults are guarded as well on a Windows host, where Explorer
85// contacts the server a file names when it shows the file, and sends your
86// NTLM hash (CVE-2025-24054 for .library-ms, CVE-2025-50154 and
87// CVE-2025-59214 for .lnk, CVE-2024-43451 for .url). "*.ext" is any file
88// with that extension.
89var WindowsDefaults = map[string]string{
90 "*.library-ms": "Explorer contacts the server it names when it shows it, and sends your NTLM hash.",
91 "*.searchConnector-ms": "Explorer contacts the server it names when it shows it, and sends your NTLM hash.",
92 "*.lnk": "Explorer can contact the server its icon names when it shows it, and send your NTLM hash.",
93 "*.url": "Explorer can contact the server its icon names when it shows it, and send your NTLM hash.",
94 "*.scf": "Explorer contacts the server its icon names when it shows it, and sends your NTLM hash.",
95 "desktop.ini": "Explorer contacts the server it names when it shows the folder, and sends your NTLM hash.",
96}
97
98// deniedFor is how long a refusal holds before the user is asked again: a
99// program retrying a write does not get a dialog each time.
100const deniedFor = time.Minute
101
102// answerWithin is how long a dialog waits: past it, the write is refused.
103const answerWithin = 2 * time.Minute
104
105// A VM that gets maxRefusals questions refused or unanswered within refusalWindow
106// is not asked again for coolDown: it is refused at once.
107const (
108 maxRefusals = 3
109 refusalWindow = 5 * time.Minute
110 coolDown = 5 * time.Minute
111)
112
113// maxShown caps the part of a path the VM chose that a question shows.
114const maxShown = 100
115
116// maxScan caps the entries looked at in a folder that is moved or removed.
117// A folder with more is asked about, as one that may hold a guarded path.
118var maxScan = 20000
119
120// Guard asks about the writes to guarded paths.
121type Guard struct {
122 // VM is named in the question.
123 VM string
124 // Paths, relative, matched anywhere in a written path as whole names,
125 // compared as sshocker folds read-only names (case, normalization, ignorable
126 // characters): each with why it matters ("" for one the user added).
127 Paths map[string]string
128 // Ask shows the question and returns the answer (desktop.Ask). ok false
129 // when no one could be asked.
130 Ask func(ctx context.Context, title, msg string) (allow, ok bool)
131 // Tell says something without waiting (a refusal no one was asked).
132 Tell func(title, msg string)
133
134 rulesOnce sync.Once
135 rules []rule
136
137 askMu sync.Mutex // one question at a time
138 mu sync.Mutex // protects what follows
139 allowed map[string]bool
140 denied map[string]time.Time
141 refusals []time.Time
142 coolUntil time.Time
143 now func() time.Time // time.Now when nil
144}
145
146// rule is a guarded path, as its folded components, or with ext, a guarded
147// extension ("*.lnk": any file whose name ends so).
148type rule struct {
149 path string
150 comps []string
151 ext string
152}
153
154// Load is the guard of the VM vm: Defaults and the user's list.
155func Load(stateDir, vm string) (*Guard, error) {
156 g := &Guard{VM: vm, Paths: map[string]string{}, Ask: desktop.Ask, Tell: desktop.Notify}
157 // No one to ask (a server, CI): refused without a dialog.
158 if os.Getenv("AGENT_VM_GUARDED_WRITES") == "deny" {
159 g.Ask = func(context.Context, string, string) (bool, bool) { return false, true }
160 }
161 for p, why := range Defaults {
162 g.Paths[p] = why
163 }
164 if windowsHost {
165 for p, why := range WindowsDefaults {
166 g.Paths[p] = why
167 }
168 }
169 f, err := os.Open(stateDir + "/" + FileName)
170 if errors.Is(err, os.ErrNotExist) {
171 return g, nil
172 }
173 if err != nil {
174 return nil, err
175 }
176 defer f.Close()
177 sc := bufio.NewScanner(f)
178 for sc.Scan() {
179 line, _, _ := strings.Cut(sc.Text(), "#")
180 line = strings.TrimSpace(line)
181 if line == "" {
182 continue
183 }
184 if p, ok := strings.CutPrefix(line, "!"); ok {
185 for k := range g.Paths {
186 if strings.EqualFold(k, clean(p)) {
187 delete(g.Paths, k)
188 }
189 }
190 continue
191 }
192 if _, ok := g.Paths[clean(line)]; !ok {
193 g.Paths[clean(line)] = ""
194 }
195 }
196 return g, sc.Err()
197}
198
199func clean(p string) string { return strings.Trim(path.Clean("/"+strings.TrimSpace(p)), "/") }
200
201// windowsHost is whether the host is Windows, where a name stands for the file
202// it is made into: "a.lnk." and "a.lnk " are "a.lnk", and "a.lnk:s" makes it.
203var windowsHost = runtime.GOOS == "windows"
204
205func foldAll(p string) []string {
206 comps := strings.Split(p, "/")
207 for i, c := range comps {
208 if windowsHost {
209 c, _, _ = strings.Cut(c, ":")
210 c = strings.TrimRight(c, ". ")
211 }
212 comps[i] = reversesshfs.FoldName(c)
213 }
214 return comps
215}
216
217func (g *Guard) loadRules() []rule {
218 g.rulesOnce.Do(func() {
219 for p := range g.Paths {
220 if ext, ok := strings.CutPrefix(p, "*."); ok && !strings.Contains(ext, "/") {
221 g.rules = append(g.rules, rule{path: p, ext: foldAll("." + ext)[0]})
222 continue
223 }
224 g.rules = append(g.rules, rule{path: p, comps: foldAll(p)})
225 }
226 })
227 return g.rules
228}
229
230// hit is what makes a path guarded.
231type hit struct {
232 rule string // the guarded path
233 kind kind
234 key string // what an answer holds for: the same key is not asked twice
235}
236
237type kind int
238
239const (
240 // The path is the guarded path, or is in the folder that is.
241 kindPath kind = iota
242 // The path is a folder that holds the guarded path: creating, moving or removing it matters.
243 kindParent
244 // The path is a folder that holds a guarded file, found by looking inside.
245 kindInside
246 // The path is a folder with too many entries to look for a guarded file in.
247 kindTooBig
248)
249
250// match is the guarded path that rel is or is in, or with entry, that rel is a folder
251// for (a name of the path's leading folders), or holds. Names are compared as a file
252// system might: folded the way sshocker compares read-only names.
253func (g *Guard) match(rel string, entry bool) (hit, bool) {
254 comps := foldAll(rel)
255 for _, r := range g.loadRules() {
256 if r.ext != "" {
257 if strings.HasSuffix(comps[len(comps)-1], r.ext) {
258 return hit{r.path, kindPath, "p:" + strings.Join(comps, "/")}, true
259 }
260 continue
261 }
262 n := len(r.comps)
263 for i := 0; i+n <= len(comps); i++ {
264 if equal(comps[i:i+n], r.comps) {
265 return hit{r.path, kindPath, "p:" + strings.Join(comps[:i+n], "/")}, true
266 }
267 }
268 }
269 if !entry {
270 return hit{}, false
271 }
272 for _, r := range g.loadRules() {
273 if r.ext != "" {
274 continue
275 }
276 for k := min(len(r.comps)-1, len(comps)); k >= 1; k-- {
277 if equal(comps[len(comps)-k:], r.comps[:k]) {
278 return hit{r.path, kindParent, "d:" + strings.Join(comps, "/")}, true
279 }
280 }
281 }
282 return hit{}, false
283}
284
285func equal(a, b []string) bool {
286 for i := range a {
287 if a[i] != b[i] {
288 return false
289 }
290 }
291 return len(a) == len(b)
292}
293
294// holds is a guarded path inside the folder rel of root, if rel is one and
295// has one within maxScan entries; a folder with more is a hit of its own, as
296// it may hold one. Nothing outside root is looked at.
297func (g *Guard) holds(root, rel string) (hit, bool) {
298 r, err := os.OpenRoot(root)
299 if err != nil {
300 return hit{}, false
301 }
302 defer r.Close()
303 if fi, err := r.Lstat(rel); err != nil || !fi.IsDir() {
304 return hit{}, false
305 }
306 var found hit
307 seen := 0
308 _ = fs.WalkDir(r.FS(), rel, func(p string, d fs.DirEntry, err error) error {
309 if err != nil || p == rel {
310 return nil
311 }
312 if seen++; seen > maxScan {
313 found = hit{fmt.Sprintf("a folder with more than %d entries", maxScan), kindTooBig, "b:" + strings.Join(foldAll(rel), "/")}
314 return fs.SkipAll
315 }
316 if m, ok := g.match(p, false); ok {
317 found = hit{m.rule, kindInside, "i:" + strings.Join(foldAll(rel), "/")}
318 return fs.SkipAll
319 }
320 return nil
321 })
322 return found, found.rule != ""
323}
324
325// Allow reports whether the VM may write rel, under the share root: yes
326// unless rel is guarded and the user says no, or cannot be asked. entry is
327// sshocker's: rel is a name that is created, removed or moved, not a file
328// whose content changes.
329func (g *Guard) Allow(root, rel string, entry bool) bool {
330 h, ok := g.match(rel, entry)
331 if !ok && entry {
332 h, ok = g.holds(root, rel)
333 }
334 if !ok {
335 return true
336 }
337 key := root + "/" + h.key
338 if allow, decided := g.decided(key); decided {
339 return allow
340 }
341 g.askMu.Lock()
342 defer g.askMu.Unlock()
343 // Another share may have asked meanwhile.
344 if allow, decided := g.decided(key); decided {
345 return allow
346 }
347
348 why := g.Paths[h.rule]
349 if h.kind == kindTooBig {
350 why = "It may hold a file agent-vm guards."
351 } else if why == "" {
352 why = "You asked agent-vm to guard it (~/.agent-vm/" + FileName + ")."
353 }
354 title := "agent-vm: " + g.VM
355 msg := question(root, rel, h, why)
356 ctx, cancel := context.WithTimeout(context.Background(), answerWithin)
357 defer cancel()
358 allow, asked := g.Ask(ctx, title, msg)
359 if !asked && g.Tell != nil {
360 g.Tell(title, fmt.Sprintf("Refused: the VM wanted to change %s in %s, and no dialog could ask you.", h.rule, root))
361 }
362
363 g.mu.Lock()
364 defer g.mu.Unlock()
365 if allow {
366 if g.allowed == nil {
367 g.allowed = map[string]bool{}
368 }
369 g.allowed[key] = true
370 return true
371 }
372 now := g.time()
373 if g.denied == nil {
374 g.denied = map[string]time.Time{}
375 }
376 g.denied[key] = now.Add(deniedFor)
377 for len(g.refusals) > 0 && now.Sub(g.refusals[0]) > refusalWindow {
378 g.refusals = g.refusals[1:]
379 }
380 g.refusals = append(g.refusals, now)
381 if len(g.refusals) >= maxRefusals {
382 g.coolUntil = now.Add(coolDown)
383 g.refusals = nil
384 if g.Tell != nil {
385 g.Tell(title, fmt.Sprintf("The VM asked to change guarded files %d times and was refused: it is refused without asking for %d minutes.", maxRefusals, int(coolDown/time.Minute)))
386 }
387 }
388 return false
389}
390
391func (g *Guard) time() time.Time {
392 if g.now != nil {
393 return g.now()
394 }
395 return time.Now()
396}
397
398// decided is the standing answer for key: allowed, refused for a while, or
399// refused while the VM is cooling down.
400func (g *Guard) decided(key string) (allow, ok bool) {
401 g.mu.Lock()
402 defer g.mu.Unlock()
403 now := g.time()
404 if g.allowed[key] {
405 return true, true
406 }
407 if until, ok := g.denied[key]; ok && now.Before(until) {
408 return false, true
409 }
410 if now.Before(g.coolUntil) {
411 return false, true
412 }
413 return false, false
414}
415
416// question is the dialog's text. The path is the VM's choice: only the guarded path (ours)
417// and a cleaned tail of it are shown.
418func question(root, rel string, h hit, why string) string {
419 var what string
420 switch h.kind {
421 case kindPath:
422 what = "change " + h.rule
423 case kindParent:
424 what = "create, move or remove a folder that holds " + h.rule
425 case kindInside:
426 what = "move or remove a folder that holds " + h.rule
427 case kindTooBig:
428 what = "move or remove " + h.rule + " (too many to check for guarded files)"
429 }
430 return fmt.Sprintf("The VM wants to %s in %s.\n\nPath: %s\n\n%s\n\nAllow it? (Until the VM stops.)", what, root, shown(rel), why)
431}
432
433// shown is rel without what could fake or hide text in a dialog: control, format and
434// direction characters, markup, and all but its last maxShown characters.
435func shown(rel string) string {
436 var b []rune
437 for _, r := range rel {
438 switch {
439 case r == '<' || r == '>' || r == '&':
440 b = append(b, '?')
441 case unicode.IsControl(r) || unicode.In(r, unicode.Cf, unicode.Zl, unicode.Zp, unicode.Variation_Selector, unicode.Other_Default_Ignorable_Code_Point):
442 // dropped
443 default:
444 b = append(b, r)
445 }
446 }
447 if len(b) > maxShown {
448 return "..." + string(b[len(b)-maxShown:])
449 }
450 return string(b)
451}