oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package claude
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "maps"
9 "path/filepath"
10 "regexp"
11 "slices"
12 "sort"
13 "strconv"
14 "strings"
15
16 "amadan.net/oficina/equipo/internal/runner/provider"
17)
18
19// The darwin launch's certified shape (Mac runners spec §4.4, §8.2;
20// slice F task 8). A Mac has no namespace: the pinned CLI runs as the
21// runner user, unsandboxed, and only its Bash commands are in Seatbelt
22// under the settings below. So this is its own policy, not
23// provider.BuildPolicy with the bubblewrap fields faked: the manifest
24// names the exact CLI and its digest, argv, settings, MCP config,
25// worktree, attempt scratch, denied paths, environment and Xcode access.
26// Nothing in it is templated; the launcher regenerates it from the same
27// inputs and requires byte equality (ValidateDarwin) before it starts
28// anything, as validatePolicy does on Linux.
29//
30// Settings keys are those the pinned 2.1.312 reads (task 1, S2). Two
31// differ from the spec's first reading: an empty allowedDomains asks
32// rather than denies, so strictAllowlist is set as well (and the
33// permission port denies SandboxNetworkAccess); and
34// enableWeakerNestedSandbox is Linux only, so it is not set.
35
36const (
37 // DarwinPolicyVersion names this shape in every darwin manifest.
38 DarwinPolicyVersion = "darwin-engineering-1"
39 // DarwinImplement is an Engineering attempt (or a fix or rebase
40 // round): the shell and the file tools on the worktree.
41 DarwinImplement = "implement"
42 // DarwinAnswer asks a step's own session about its work: Read, Glob
43 // and Grep only, the worktree read-only.
44 DarwinAnswer = "answer"
45 // DarwinCheck is the token check (task 10): no native tool, no
46 // Equipo tool, an empty read-only workspace.
47 DarwinCheck = "check"
48 // DarwinTokenFD is the descriptor the token arrives on. The CLI reads
49 // /dev/fd/<n> named by CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR (task
50 // 1, S4); the token is never in the environment, where a sandboxed
51 // command could read it through KERN_PROCARGS2 (R4).
52 DarwinTokenFD = 3
53 // DarwinSettingsFile and DarwinMCPFile are written into the runtime
54 // copy (CLAUDE_CONFIG_DIR), which no sandboxed command can read or
55 // write, just before the start.
56 DarwinSettingsFile = "equipo-settings.json"
57 DarwinMCPFile = "equipo-mcp.json"
58 // DarwinPath is the CLI's PATH: only SIP-protected system
59 // directories. The CLI, unsandboxed and holding the token, resolves
60 // tools such as security and git through it.
61 DarwinPath = "/usr/bin:/bin:/usr/sbin:/sbin"
62 // DarwinLang is the locale every Mac launch uses.
63 DarwinLang = "en_US.UTF-8"
64 // DarwinMarkerEnv carries the attempt's marker (spec §5). Its name has
65 // none of the words the CLI's scrub removes (task 1, S5).
66 DarwinMarkerEnv = "EQUIPO_ATTEMPT"
67 // darwinXcodeSandboxed is wire.XcodeAccessSandboxed (wire is not a
68 // dependency of this package).
69 darwinXcodeSandboxed = "sandboxed"
70 darwinTokenFDEnv = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR"
71)
72
73// DarwinInputs are everything a Mac launch's policy is made from. Every
74// path is absolute and clean, as it will be used; the package mac
75// adapter (mac.EngineeringPolicy) fills them from the runner's places.
76type DarwinInputs struct {
77 // Action is DarwinImplement, DarwinAnswer or DarwinCheck. The Equipo
78 // tools are the action's own (provider.Profile); a check has none.
79 Action, Model string
80 // CLI is the pinned binary's path, CLIDigest the digest it must have,
81 // CLIDir its directory, InstallDir the runner's (writes denied).
82 CLI, CLIDigest, CLIDir, InstallDir string
83 // Runner is the runner binary, serving MCP in its tool-proxy mode on
84 // Socket, which lies in ToolRoot (<scratch root>/t).
85 Runner, ToolRoot, Socket string
86 // Workspace is the worktree at its real path, Scratch the attempt's
87 // scratch (TMPDIR), Home the runner user's home (HOME).
88 Workspace, Scratch, Home string
89 // ConfigDir is the connection's runtime copy (CLAUDE_CONFIG_DIR),
90 // inside RuntimeRoot; CredentialHome its dedicated home.
91 ConfigDir, CredentialHome, RuntimeRoot string
92 // Denied is the §4.2 list (denylist.DenyList).
93 Denied []string
94 // XcodeAccess is "" or "sandboxed". Only sandboxed access has
95 // XcodeWrites (DerivedData, the user's T, SwiftPM's caches) and Mach
96 // (the P2-recorded services).
97 XcodeAccess string
98 XcodeWrites, Mach []string
99 // DeveloperDir is xcode-select -p, or "" for none. Attempt is the
100 // marker. SessionID starts a session, or resumes it with Resume.
101 DeveloperDir, Attempt, SessionID string
102 Resume bool
103}
104
105// darwinManifest is the certified record. Its JSON names are the Linux
106// manifest's where they mean the same (the permission port and
107// ValidateInit read both), and NativeRoots marks it darwin.
108type darwinManifest struct {
109 Version string
110 NativeRoots
111 Action, ProviderVersion string
112 CLI, CLIDigest string
113 Argv []string
114 Env map[string]string
115 Workspace, Scratch string
116 CredentialHome, ConfigDir string
117 DeniedPaths, Tools []string
118 XcodeAccess string
119 Settings, MCP json.RawMessage
120 ThreadPolicy, TurnPolicy json.RawMessage
121}
122
123var (
124 darwinModel = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:\[\]-]{0,127}$`)
125 darwinSession = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`)
126 darwinMarker = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
127 darwinDigest = regexp.MustCompile(`^[0-9a-f]{64}$`)
128)
129
130// darwinLiteral is a path neither the sandbox nor a permission rule can
131// read as a pattern: absolute, clean, not /, no glob or control bytes.
132func darwinLiteral(p string) bool {
133 return p != "" && filepath.IsAbs(p) && filepath.Clean(p) == p && p != "/" && !strings.ContainsAny(p, "*?[]{}()\\\n\r\t\x00")
134}
135
136// overlaps: either path is the other or below it, compared as APFS
137// compares names (foldedWithin), so it refuses every spelling.
138func overlaps(a, b string) bool { return foldedWithin(a, b) || foldedWithin(b, a) }
139
140// darwinProfile is the native tools and Equipo tools of an action, and
141// whether its workspace is read-only.
142func darwinProfile(action string) (specialist string, tools []string, readOnly bool, err error) {
143 switch action {
144 case DarwinImplement, DarwinAnswer:
145 p, e := provider.Profile(action)
146 if e != nil {
147 return "", nil, false, e
148 }
149 return p.Specialist, p.MCPTools(), p.ReadOnly, nil
150 case DarwinCheck:
151 return "Coordinator", []string{}, true, nil
152 }
153 return "", nil, false, provider.ErrPolicy
154}
155
156// DarwinPolicy is the certified policy of one Mac launch, or
157// provider.ErrPolicy when the inputs would not mean what they say: a
158// path that is relative, unclean or a pattern; a writable place inside a
159// denied one or holding one; a worktree and scratch that overlap; Xcode
160// services or writes without sandboxed access.
161func DarwinPolicy(in DarwinInputs) (provider.Policy, error) {
162 specialist, tools, readOnly, err := darwinProfile(in.Action)
163 if err != nil {
164 return provider.Policy{}, provider.ErrPolicy
165 }
166 native, err := nativeTools(specialist)
167 if err != nil || !darwinModel.MatchString(in.Model) || !darwinSession.MatchString(in.SessionID) || !darwinMarker.MatchString(in.Attempt) || !darwinDigest.MatchString(in.CLIDigest) {
168 return provider.Policy{}, provider.ErrPolicy
169 }
170 paths := []string{in.CLI, in.CLIDir, in.InstallDir, in.Runner, in.ToolRoot, in.Socket, in.Workspace, in.Scratch, in.Home, in.ConfigDir, in.CredentialHome, in.RuntimeRoot}
171 if in.DeveloperDir != "" {
172 paths = append(paths, in.DeveloperDir)
173 }
174 for _, p := range append(append(paths, in.Denied...), in.XcodeWrites...) {
175 if !darwinLiteral(p) {
176 return provider.Policy{}, provider.ErrPolicy
177 }
178 }
179 if len(in.Denied) == 0 || !within(in.CLIDir, in.CLI) || in.CLIDir == in.CLI || !within(in.ToolRoot, in.Socket) || in.ToolRoot == in.Socket || !within(in.RuntimeRoot, in.ConfigDir) || in.RuntimeRoot == in.ConfigDir || overlaps(in.Workspace, in.Scratch) {
180 return provider.Policy{}, provider.ErrPolicy
181 }
182 switch in.XcodeAccess {
183 case "":
184 if len(in.XcodeWrites) != 0 || len(in.Mach) != 0 {
185 return provider.Policy{}, provider.ErrPolicy
186 }
187 case darwinXcodeSandboxed:
188 if in.Action != DarwinImplement || len(in.XcodeWrites) == 0 {
189 return provider.Policy{}, provider.ErrPolicy
190 }
191 default:
192 return provider.Policy{}, provider.ErrPolicy
193 }
194 for _, m := range in.Mach {
195 if m == "" || m == "*" || strings.ContainsAny(m, "/ \"\\\n\x00") || strings.Contains(strings.TrimSuffix(m, "*"), "*") {
196 return provider.Policy{}, provider.ErrPolicy
197 }
198 }
199 mcp, err := provider.DarwinToolMCP(in.Runner, in.Socket)
200 if err != nil {
201 return provider.Policy{}, provider.ErrPolicy
202 }
203
204 // Denied both ways: §4.2, the connection's homes, the runtime copies
205 // and the step socket's directory (a sandboxed command is the same
206 // uid as the CLI: only Seatbelt keeps it off the socket). Writes are
207 // also denied to the install dir and the pinned CLI's directory:
208 // macOS execs the CLI by path, after the launcher's last hash.
209 denyRead := sortedSet(append(slices.Clone(in.Denied), in.CredentialHome, in.ConfigDir, in.RuntimeRoot, in.ToolRoot))
210 denyWrite := sortedSet(append(slices.Clone(denyRead), in.InstallDir, in.CLIDir))
211 write := []string{in.Workspace, in.Scratch}
212 if readOnly {
213 write = []string{in.Scratch}
214 }
215 write = append(write, in.XcodeWrites...)
216 // A writable place inside a denied one would not be writable
217 // (denyWrite wins), and one holding a denied place would expose it:
218 // refuse rather than launch something that does not mean its words.
219 for _, w := range append(slices.Clone(write), in.Workspace) {
220 for _, d := range denyWrite {
221 if overlaps(w, d) {
222 return provider.Policy{}, provider.ErrPolicy
223 }
224 }
225 }
226 if readOnly {
227 denyWrite = sortedSet(append(denyWrite, in.Workspace))
228 }
229 rules, err := NativeDenyRules(denyRead)
230 if err != nil {
231 return provider.Policy{}, provider.ErrPolicy
232 }
233 // The native Write and Edit run in the CLI, unsandboxed: a place
234 // denied to writes only (the install dir, the CLI's own directory, a
235 // read-only worktree) gets native Write and Edit denies too, a
236 // second layer behind the port should a checked directory be swapped
237 // for a link to it.
238 for _, d := range denyWrite {
239 if !slices.Contains(denyRead, d) {
240 rules = append(rules, "Write(/"+d+")", "Write(/"+d+"/**)", "Edit(/"+d+")", "Edit(/"+d+"/**)")
241 }
242 }
243 ask := []string{}
244 for _, tool := range native {
245 if slices.Contains(nativeFileTools, tool) {
246 ask = append(ask, tool+"(/"+in.Workspace+"/**)")
247 }
248 }
249 mach := append([]string{}, in.Mach...)
250 settings, err := json.Marshal(map[string]any{
251 "env": map[string]string{"MCP_TOOL_TIMEOUT": "600000"},
252 "disableAllHooks": true, "enabledPlugins": map[string]any{"agents-md@builtin": false, "plugin-authoring@builtin": false}, "autoMemoryEnabled": false, "autoDreamEnabled": false,
253 "sandbox": map[string]any{
254 "enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, "autoAllowBashIfSandboxed": true, "excludedCommands": []string{},
255 "filesystem": map[string]any{"allowWrite": write, "denyRead": denyRead, "denyWrite": denyWrite},
256 "network": map[string]any{"allowedDomains": []string{}, "strictAllowlist": true, "allowUnixSockets": []string{}, "allowAllUnixSockets": false, "allowLocalBinding": false, "allowMachLookup": mach},
257 },
258 "permissions": map[string]any{"deny": rules, "allow": append([]string{}, tools...), "ask": ask},
259 })
260 if err != nil {
261 return provider.Policy{}, provider.ErrPolicy
262 }
263
264 argv := append([]string{in.CLI}, baseArgs(in.Model, strings.Join(native, ","))[1:]...)
265 for i, a := range argv {
266 switch a {
267 case provider.MCPPath:
268 argv[i] = filepath.Join(in.ConfigDir, DarwinMCPFile)
269 case provider.SettingsPath:
270 argv[i] = filepath.Join(in.ConfigDir, DarwinSettingsFile)
271 }
272 }
273 if readOnly {
274 argv = append(argv, "--include-partial-messages")
275 }
276 flag := "--session-id"
277 if in.Resume {
278 flag = "--resume"
279 }
280 argv = append(argv, flag, in.SessionID)
281
282 // The environment from scratch. CLAUDE_CODE_SUBPROCESS_ENV_SCRUB
283 // forces permission mode default and turns autoAllowBashIfSandboxed
284 // off (S5): Bash goes through the permission port, which allows it
285 // only under these sandbox settings.
286 env := map[string]string{
287 "HOME": in.Home, "CLAUDE_CONFIG_DIR": in.ConfigDir, "TMPDIR": in.Scratch,
288 "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB": "1", "DISABLE_AUTOUPDATER": "1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
289 "PATH": DarwinPath, "LANG": DarwinLang, DarwinMarkerEnv: in.Attempt,
290 darwinTokenFDEnv: strconv.Itoa(DarwinTokenFD),
291 }
292 if in.DeveloperDir != "" {
293 env["DEVELOPER_DIR"] = in.DeveloperDir
294 }
295 PinProjectDir(env)
296
297 thread, _ := json.Marshal(threadPolicy{specialist, in.Model, "session-id", "resume"})
298 m := darwinManifest{Version: DarwinPolicyVersion, NativeRoots: NativeRoots{Platform: PlatformDarwin, WorkspaceRoot: in.Workspace},
299 Action: in.Action, ProviderVersion: Version, CLI: in.CLI, CLIDigest: in.CLIDigest, Argv: argv, Env: env,
300 Workspace: in.Workspace, Scratch: in.Scratch, CredentialHome: in.CredentialHome, ConfigDir: in.ConfigDir,
301 DeniedPaths: denyRead, Tools: append(append(append([]string{}, native...), "mcp__equipo__permission"), tools...),
302 XcodeAccess: in.XcodeAccess, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: json.RawMessage(`{}`)}
303 raw, err := json.Marshal(m)
304 if err != nil || !nonsecretDarwin(settings, mcp) {
305 return provider.Policy{}, provider.ErrPolicy
306 }
307 sum := sha256.Sum256(raw)
308 hash := hex.EncodeToString(sum[:])
309 return provider.Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Env: env, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: json.RawMessage(`{}`)}, nil
310}
311
312// nonsecretDarwin: the generated JSON has no duplicate key (the CLI and
313// this check would read one differently).
314func nonsecretDarwin(raws ...json.RawMessage) bool {
315 for _, raw := range raws {
316 if !uniqueJSON(raw) {
317 return false
318 }
319 }
320 return true
321}
322
323func sortedSet(in []string) []string {
324 out := slices.Clone(in)
325 sort.Strings(out)
326 return slices.Compact(out)
327}
328
329// ValidateDarwin regenerates the policy from in and refuses p on any
330// difference, byte for byte: manifest, hashes, settings, MCP, thread and
331// turn policies, environment, and no mounts. Call it immediately before
332// a launch, with the launcher's own inputs.
333func ValidateDarwin(in DarwinInputs, p provider.Policy) error {
334 want, err := DarwinPolicy(in)
335 if err != nil {
336 return err
337 }
338 sum := sha256.Sum256(p.Manifest)
339 if hex.EncodeToString(sum[:]) != p.Hash || p.Hash != want.Hash || p.ManifestHash != want.ManifestHash || p.InstructionHash != "" || len(p.Mounts) != 0 ||
340 !bytes.Equal(p.Manifest, want.Manifest) || !bytes.Equal(p.Settings, want.Settings) || !bytes.Equal(p.MCP, want.MCP) ||
341 !bytes.Equal(p.ThreadPolicy, want.ThreadPolicy) || !bytes.Equal(p.TurnPolicy, want.TurnPolicy) || !maps.Equal(p.Env, want.Env) {
342 return provider.ErrPolicy
343 }
344 return nil
345}
346
347// DarwinArgv is a darwin policy's argv (the CLI's path first), or nil.
348func DarwinArgv(p provider.Policy) []string {
349 var m darwinManifest
350 if json.Unmarshal(p.Manifest, &m) != nil || m.Version != DarwinPolicyVersion {
351 return nil
352 }
353 return m.Argv
354}
355