package claude import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "maps" "path/filepath" "regexp" "slices" "sort" "strconv" "strings" "amadan.net/oficina/equipo/internal/runner/provider" ) // The darwin launch's certified shape (Mac runners spec §4.4, §8.2; // slice F task 8). A Mac has no namespace: the pinned CLI runs as the // runner user, unsandboxed, and only its Bash commands are in Seatbelt // under the settings below. So this is its own policy, not // provider.BuildPolicy with the bubblewrap fields faked: the manifest // names the exact CLI and its digest, argv, settings, MCP config, // worktree, attempt scratch, denied paths, environment and Xcode access. // Nothing in it is templated; the launcher regenerates it from the same // inputs and requires byte equality (ValidateDarwin) before it starts // anything, as validatePolicy does on Linux. // // Settings keys are those the pinned 2.1.312 reads (task 1, S2). Two // differ from the spec's first reading: an empty allowedDomains asks // rather than denies, so strictAllowlist is set as well (and the // permission port denies SandboxNetworkAccess); and // enableWeakerNestedSandbox is Linux only, so it is not set. const ( // DarwinPolicyVersion names this shape in every darwin manifest. DarwinPolicyVersion = "darwin-engineering-1" // DarwinImplement is an Engineering attempt (or a fix or rebase // round): the shell and the file tools on the worktree. DarwinImplement = "implement" // DarwinAnswer asks a step's own session about its work: Read, Glob // and Grep only, the worktree read-only. DarwinAnswer = "answer" // DarwinCheck is the token check (task 10): no native tool, no // Equipo tool, an empty read-only workspace. DarwinCheck = "check" // DarwinTokenFD is the descriptor the token arrives on. The CLI reads // /dev/fd/ named by CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR (task // 1, S4); the token is never in the environment, where a sandboxed // command could read it through KERN_PROCARGS2 (R4). DarwinTokenFD = 3 // DarwinSettingsFile and DarwinMCPFile are written into the runtime // copy (CLAUDE_CONFIG_DIR), which no sandboxed command can read or // write, just before the start. DarwinSettingsFile = "equipo-settings.json" DarwinMCPFile = "equipo-mcp.json" // DarwinPath is the CLI's PATH: only SIP-protected system // directories. The CLI, unsandboxed and holding the token, resolves // tools such as security and git through it. DarwinPath = "/usr/bin:/bin:/usr/sbin:/sbin" // DarwinLang is the locale every Mac launch uses. DarwinLang = "en_US.UTF-8" // DarwinMarkerEnv carries the attempt's marker (spec §5). Its name has // none of the words the CLI's scrub removes (task 1, S5). DarwinMarkerEnv = "EQUIPO_ATTEMPT" // darwinXcodeSandboxed is wire.XcodeAccessSandboxed (wire is not a // dependency of this package). darwinXcodeSandboxed = "sandboxed" darwinTokenFDEnv = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" ) // DarwinInputs are everything a Mac launch's policy is made from. Every // path is absolute and clean, as it will be used; the package mac // adapter (mac.EngineeringPolicy) fills them from the runner's places. type DarwinInputs struct { // Action is DarwinImplement, DarwinAnswer or DarwinCheck. The Equipo // tools are the action's own (provider.Profile); a check has none. Action, Model string // CLI is the pinned binary's path, CLIDigest the digest it must have, // CLIDir its directory, InstallDir the runner's (writes denied). CLI, CLIDigest, CLIDir, InstallDir string // Runner is the runner binary, serving MCP in its tool-proxy mode on // Socket, which lies in ToolRoot (/t). Runner, ToolRoot, Socket string // Workspace is the worktree at its real path, Scratch the attempt's // scratch (TMPDIR), Home the runner user's home (HOME). Workspace, Scratch, Home string // ConfigDir is the connection's runtime copy (CLAUDE_CONFIG_DIR), // inside RuntimeRoot; CredentialHome its dedicated home. ConfigDir, CredentialHome, RuntimeRoot string // Denied is the §4.2 list (denylist.DenyList). Denied []string // XcodeAccess is "" or "sandboxed". Only sandboxed access has // XcodeWrites (DerivedData, the user's T, SwiftPM's caches) and Mach // (the P2-recorded services). XcodeAccess string XcodeWrites, Mach []string // DeveloperDir is xcode-select -p, or "" for none. Attempt is the // marker. SessionID starts a session, or resumes it with Resume. DeveloperDir, Attempt, SessionID string Resume bool } // darwinManifest is the certified record. Its JSON names are the Linux // manifest's where they mean the same (the permission port and // ValidateInit read both), and NativeRoots marks it darwin. type darwinManifest struct { Version string NativeRoots Action, ProviderVersion string CLI, CLIDigest string Argv []string Env map[string]string Workspace, Scratch string CredentialHome, ConfigDir string DeniedPaths, Tools []string XcodeAccess string Settings, MCP json.RawMessage ThreadPolicy, TurnPolicy json.RawMessage } var ( darwinModel = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:\[\]-]{0,127}$`) darwinSession = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`) darwinMarker = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`) darwinDigest = regexp.MustCompile(`^[0-9a-f]{64}$`) ) // darwinLiteral is a path neither the sandbox nor a permission rule can // read as a pattern: absolute, clean, not /, no glob or control bytes. func darwinLiteral(p string) bool { return p != "" && filepath.IsAbs(p) && filepath.Clean(p) == p && p != "/" && !strings.ContainsAny(p, "*?[]{}()\\\n\r\t\x00") } // overlaps: either path is the other or below it, compared as APFS // compares names (foldedWithin), so it refuses every spelling. func overlaps(a, b string) bool { return foldedWithin(a, b) || foldedWithin(b, a) } // darwinProfile is the native tools and Equipo tools of an action, and // whether its workspace is read-only. func darwinProfile(action string) (specialist string, tools []string, readOnly bool, err error) { switch action { case DarwinImplement, DarwinAnswer: p, e := provider.Profile(action) if e != nil { return "", nil, false, e } return p.Specialist, p.MCPTools(), p.ReadOnly, nil case DarwinCheck: return "Coordinator", []string{}, true, nil } return "", nil, false, provider.ErrPolicy } // DarwinPolicy is the certified policy of one Mac launch, or // provider.ErrPolicy when the inputs would not mean what they say: a // path that is relative, unclean or a pattern; a writable place inside a // denied one or holding one; a worktree and scratch that overlap; Xcode // services or writes without sandboxed access. func DarwinPolicy(in DarwinInputs) (provider.Policy, error) { specialist, tools, readOnly, err := darwinProfile(in.Action) if err != nil { return provider.Policy{}, provider.ErrPolicy } native, err := nativeTools(specialist) if err != nil || !darwinModel.MatchString(in.Model) || !darwinSession.MatchString(in.SessionID) || !darwinMarker.MatchString(in.Attempt) || !darwinDigest.MatchString(in.CLIDigest) { return provider.Policy{}, provider.ErrPolicy } 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} if in.DeveloperDir != "" { paths = append(paths, in.DeveloperDir) } for _, p := range append(append(paths, in.Denied...), in.XcodeWrites...) { if !darwinLiteral(p) { return provider.Policy{}, provider.ErrPolicy } } 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) { return provider.Policy{}, provider.ErrPolicy } switch in.XcodeAccess { case "": if len(in.XcodeWrites) != 0 || len(in.Mach) != 0 { return provider.Policy{}, provider.ErrPolicy } case darwinXcodeSandboxed: if in.Action != DarwinImplement || len(in.XcodeWrites) == 0 { return provider.Policy{}, provider.ErrPolicy } default: return provider.Policy{}, provider.ErrPolicy } for _, m := range in.Mach { if m == "" || m == "*" || strings.ContainsAny(m, "/ \"\\\n\x00") || strings.Contains(strings.TrimSuffix(m, "*"), "*") { return provider.Policy{}, provider.ErrPolicy } } mcp, err := provider.DarwinToolMCP(in.Runner, in.Socket) if err != nil { return provider.Policy{}, provider.ErrPolicy } // Denied both ways: §4.2, the connection's homes, the runtime copies // and the step socket's directory (a sandboxed command is the same // uid as the CLI: only Seatbelt keeps it off the socket). Writes are // also denied to the install dir and the pinned CLI's directory: // macOS execs the CLI by path, after the launcher's last hash. denyRead := sortedSet(append(slices.Clone(in.Denied), in.CredentialHome, in.ConfigDir, in.RuntimeRoot, in.ToolRoot)) denyWrite := sortedSet(append(slices.Clone(denyRead), in.InstallDir, in.CLIDir)) write := []string{in.Workspace, in.Scratch} if readOnly { write = []string{in.Scratch} } write = append(write, in.XcodeWrites...) // A writable place inside a denied one would not be writable // (denyWrite wins), and one holding a denied place would expose it: // refuse rather than launch something that does not mean its words. for _, w := range append(slices.Clone(write), in.Workspace) { for _, d := range denyWrite { if overlaps(w, d) { return provider.Policy{}, provider.ErrPolicy } } } if readOnly { denyWrite = sortedSet(append(denyWrite, in.Workspace)) } rules, err := NativeDenyRules(denyRead) if err != nil { return provider.Policy{}, provider.ErrPolicy } // The native Write and Edit run in the CLI, unsandboxed: a place // denied to writes only (the install dir, the CLI's own directory, a // read-only worktree) gets native Write and Edit denies too, a // second layer behind the port should a checked directory be swapped // for a link to it. for _, d := range denyWrite { if !slices.Contains(denyRead, d) { rules = append(rules, "Write(/"+d+")", "Write(/"+d+"/**)", "Edit(/"+d+")", "Edit(/"+d+"/**)") } } ask := []string{} for _, tool := range native { if slices.Contains(nativeFileTools, tool) { ask = append(ask, tool+"(/"+in.Workspace+"/**)") } } mach := append([]string{}, in.Mach...) settings, err := json.Marshal(map[string]any{ "env": map[string]string{"MCP_TOOL_TIMEOUT": "600000"}, "disableAllHooks": true, "enabledPlugins": map[string]any{"agents-md@builtin": false, "plugin-authoring@builtin": false}, "autoMemoryEnabled": false, "autoDreamEnabled": false, "sandbox": map[string]any{ "enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, "autoAllowBashIfSandboxed": true, "excludedCommands": []string{}, "filesystem": map[string]any{"allowWrite": write, "denyRead": denyRead, "denyWrite": denyWrite}, "network": map[string]any{"allowedDomains": []string{}, "strictAllowlist": true, "allowUnixSockets": []string{}, "allowAllUnixSockets": false, "allowLocalBinding": false, "allowMachLookup": mach}, }, "permissions": map[string]any{"deny": rules, "allow": append([]string{}, tools...), "ask": ask}, }) if err != nil { return provider.Policy{}, provider.ErrPolicy } argv := append([]string{in.CLI}, baseArgs(in.Model, strings.Join(native, ","))[1:]...) for i, a := range argv { switch a { case provider.MCPPath: argv[i] = filepath.Join(in.ConfigDir, DarwinMCPFile) case provider.SettingsPath: argv[i] = filepath.Join(in.ConfigDir, DarwinSettingsFile) } } if readOnly { argv = append(argv, "--include-partial-messages") } flag := "--session-id" if in.Resume { flag = "--resume" } argv = append(argv, flag, in.SessionID) // The environment from scratch. CLAUDE_CODE_SUBPROCESS_ENV_SCRUB // forces permission mode default and turns autoAllowBashIfSandboxed // off (S5): Bash goes through the permission port, which allows it // only under these sandbox settings. env := map[string]string{ "HOME": in.Home, "CLAUDE_CONFIG_DIR": in.ConfigDir, "TMPDIR": in.Scratch, "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB": "1", "DISABLE_AUTOUPDATER": "1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "PATH": DarwinPath, "LANG": DarwinLang, DarwinMarkerEnv: in.Attempt, darwinTokenFDEnv: strconv.Itoa(DarwinTokenFD), } if in.DeveloperDir != "" { env["DEVELOPER_DIR"] = in.DeveloperDir } PinProjectDir(env) thread, _ := json.Marshal(threadPolicy{specialist, in.Model, "session-id", "resume"}) m := darwinManifest{Version: DarwinPolicyVersion, NativeRoots: NativeRoots{Platform: PlatformDarwin, WorkspaceRoot: in.Workspace}, Action: in.Action, ProviderVersion: Version, CLI: in.CLI, CLIDigest: in.CLIDigest, Argv: argv, Env: env, Workspace: in.Workspace, Scratch: in.Scratch, CredentialHome: in.CredentialHome, ConfigDir: in.ConfigDir, DeniedPaths: denyRead, Tools: append(append(append([]string{}, native...), "mcp__equipo__permission"), tools...), XcodeAccess: in.XcodeAccess, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: json.RawMessage(`{}`)} raw, err := json.Marshal(m) if err != nil || !nonsecretDarwin(settings, mcp) { return provider.Policy{}, provider.ErrPolicy } sum := sha256.Sum256(raw) hash := hex.EncodeToString(sum[:]) return provider.Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Env: env, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: json.RawMessage(`{}`)}, nil } // nonsecretDarwin: the generated JSON has no duplicate key (the CLI and // this check would read one differently). func nonsecretDarwin(raws ...json.RawMessage) bool { for _, raw := range raws { if !uniqueJSON(raw) { return false } } return true } func sortedSet(in []string) []string { out := slices.Clone(in) sort.Strings(out) return slices.Compact(out) } // ValidateDarwin regenerates the policy from in and refuses p on any // difference, byte for byte: manifest, hashes, settings, MCP, thread and // turn policies, environment, and no mounts. Call it immediately before // a launch, with the launcher's own inputs. func ValidateDarwin(in DarwinInputs, p provider.Policy) error { want, err := DarwinPolicy(in) if err != nil { return err } sum := sha256.Sum256(p.Manifest) if hex.EncodeToString(sum[:]) != p.Hash || p.Hash != want.Hash || p.ManifestHash != want.ManifestHash || p.InstructionHash != "" || len(p.Mounts) != 0 || !bytes.Equal(p.Manifest, want.Manifest) || !bytes.Equal(p.Settings, want.Settings) || !bytes.Equal(p.MCP, want.MCP) || !bytes.Equal(p.ThreadPolicy, want.ThreadPolicy) || !bytes.Equal(p.TurnPolicy, want.TurnPolicy) || !maps.Equal(p.Env, want.Env) { return provider.ErrPolicy } return nil } // DarwinArgv is a darwin policy's argv (the CLI's path first), or nil. func DarwinArgv(p provider.Policy) []string { var m darwinManifest if json.Unmarshal(p.Manifest, &m) != nil || m.Version != DarwinPolicyVersion { return nil } return m.Argv }