package main import ( "context" "crypto/sha256" "errors" "flag" "fmt" "io" "net/http" "os" "os/exec" "path/filepath" "slices" "sort" "strconv" "strings" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/rastrillo/rastrillo" ) // macInstallHost is what installing on a Mac touches; tests stand in. type macInstallHost struct { goos, goarch, users, self string exec mac.Exec exposed func(string) bool // tools are what srt needs on macOS (mac.SRTTools: Node first, then // ripgrep), fetched with fetch and checked against their pins; npmCI // installs the pinned srt into prefix with the npm beside Node. tools []mac.Tool fetch func(ctx context.Context, url string, limit int64) ([]byte, error) npmCI func(ctx context.Context, npm, prefix, home string) error // verify checks what was installed under lib against the pins // compiled into this binary (mac.VerifyTools). scannerPin string verify func(lib string) error enrol func(ctx context.Context, cfg runner.Config, out io.Writer) error // launchctl runs launchctl; firstLaunch runs xcodebuild -runFirstLaunch // as the user whose home is home. launchctl func(ctx context.Context, args ...string) error // stopWait bounds the wait for a runner to stop (a minute). stopWait time.Duration firstLaunch func(ctx context.Context, home string) // chdir moves the installer into the user's home before it runs // anything there (os.Chdir). chdir func(dir string) error } // userEnv is environ for a program run as the user whose home is home and // name is name: under su or sudo, HOME, USER and LOGNAME can be the // caller's, and npm or xcodebuild would write into the caller's home. func userEnv(environ []string, home, name string, extra ...string) []string { var env []string for _, kv := range environ { k, _, _ := strings.Cut(kv, "=") switch k { case "HOME", "USER", "LOGNAME": continue } if !slices.ContainsFunc(extra, func(e string) bool { return strings.HasPrefix(e, k+"=") }) { env = append(env, kv) } } return append(append(env, "HOME="+home, "USER="+name, "LOGNAME="+name), extra...) } // Every program the installer runs is given its own working directory: // started from a folder this user cannot read (su without a dash), npm // and xcodebuild fail on the inherited one (2026-11-28). // systemCommand runs a system tool (id, dscl, scutil, launchctl) from /. func systemCommand(ctx context.Context, name string, args ...string) *exec.Cmd { cmd := exec.CommandContext(ctx, name, args...) cmd.Dir = "/" return cmd } // npmCICommand installs the pinned srt into prefix, run there, as the // user whose home is home. func npmCICommand(ctx context.Context, npm, prefix, home string) *exec.Cmd { cmd := exec.CommandContext(ctx, npm, "ci", "--prefix", prefix, "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund") cmd.Dir = prefix cmd.Env = userEnv(os.Environ(), home, filepath.Base(home), "PATH="+filepath.Dir(npm)+":/usr/bin:/bin") return cmd } // firstLaunchCommand is xcodebuild -runFirstLaunch, run in home as the // user whose home it is. func firstLaunchCommand(ctx context.Context, home string) *exec.Cmd { cmd := exec.CommandContext(ctx, "/usr/bin/xcodebuild", "-runFirstLaunch") cmd.Dir = home cmd.Env = userEnv(os.Environ(), home, filepath.Base(home)) return cmd } func realMacInstallHost() macInstallHost { self, _ := os.Executable() return macInstallHost{goos: goos(), goarch: goarch(), users: "/Users", self: self, scannerPin: release.GitleaksSHA256(), exec: func(ctx context.Context, name string, args ...string) (string, error) { out, err := systemCommand(ctx, name, args...).Output() return string(out), err }, exposed: mac.Exposed, tools: mac.SRTTools, fetch: fetchTool, verify: func(lib string) error { return mac.VerifyTools(lib, mac.PinnedTools(lib)) }, npmCI: func(ctx context.Context, npm, prefix, home string) error { return npmCICommand(ctx, npm, prefix, home).Run() }, enrol: runner.Enrol, launchctl: func(ctx context.Context, args ...string) error { return systemCommand(ctx, "/bin/launchctl", args...).Run() }, firstLaunch: func(ctx context.Context, home string) { c, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() _ = firstLaunchCommand(c, home).Run() }, chdir: os.Chdir, } } // installMac installs a Mac worker for the user running it (Mac runners // spec ยง3.2): refuses root, administrators, users without equipo in their name // and a readable foreign home; refuses, changing nothing, a user whose // runner is enrolled with another Equipo; copies the verified runner into // ~/.local/lib/equipo-runner; installs the pinned srt; writes the // environment file; enrols (the link Paul taps); then loads the launchd // agent, whose runner probes the Mac by itself. What a runner installed // before ran on is kept aside until the enrolment is done, and put back // and started again if anything stops the install before then. func installMac(ctx context.Context, args []string, h macInstallHost, out, errout io.Writer) int { say := func(key string, a ...any) { fmt.Fprintf(errout, equipo.RunnerSetupCopy(key)+"\n", a...) } fail := func(key string, a ...any) int { say(key, a...); return 1 } flags := flag.NewFlagSet("install", flag.ContinueOnError) flags.SetOutput(io.Discard) instance := flags.String("instance", "", "") version := flags.String("release", "", "") origin := flags.String("origin", "", "") if flags.Parse(args) != nil || flags.NArg() != 0 || *instance == "" || *version != rastrillo.BuildVersion || !release.InstallOrigin(*origin) || !release.ValidInstallVersion(*version) { return fail("runner.install.release") } if h.goos != "darwin" || h.goarch != "arm64" { return fail("runner.mac.platform") } account, err := mac.ReadAccount(ctx, h.exec) if err != nil { return fail("runner.install.unavailable") } if key := mac.RefuseAccount(account); key != "" { return fail(key) } // The user's own home, from the user directory: under su or sudo the // environment's HOME can be the caller's. home, err := mac.ReadHome(ctx, h.exec, account.Name) if err != nil || filepath.Base(home) != account.Name { return fail("runner.install.destination") } // The installer and everything it runs work from this home, never // the folder it was started from (which this user may not read). if h.chdir(home) != nil { return fail("runner.install.destination") } others, err := mac.OtherHomes(h.users, home) if err != nil { return fail("runner.mac.homes_unknown") } if exposed := mac.ExposedHomes(others, h.exposed); len(exposed) > 0 { return fail("runner.mac.home", strings.Join(exposed, " "), account.Name) } // The agent runs in the user's login session: without one (su or // sudo -iu from another user's session, with this user logged out) // there is nowhere to load it. domain := "gui/" + strconv.Itoa(account.UID) if h.launchctl(ctx, "print", domain) != nil { return fail("runner.mac.not_logged_in", account.Name) } lib := filepath.Join(home, ".local", "lib", "equipo-runner") share := filepath.Join(home, ".local", "share", "equipo-runner") conf := filepath.Join(home, ".config", "equipo-runner") logs := filepath.Join(home, "Library", "Logs", "equipo-runner") agents := filepath.Join(home, "Library", "LaunchAgents") // Paths are this user's, whichever Equipo it works for: a runner // enrolled with another one is said so before anything is stopped or // rewritten (the Studio's staging runner, 2026-11-28, was left down). // One install at a time, from this check until it is enrolled or put // back: a second one is refused, not let put back over the first. lock, err := installLock(filepath.Join(share, "state")) if err != nil { return fail(lockKey(err)) } defer lock.Close() if key, a := enrolledElsewhere(filepath.Join(share, "state"), *origin, *instance, "runner.mac.other_instance"); key != "" { return fail(key, a...) } // A runner installed before is stopped first: nothing it uses is // replaced under it, and its state lock is free for the enrolment // check below (an existing, valid enrolment is kept as it is). If it // does not stop, nothing at all is changed. plist := filepath.Join(agents, mac.AgentLabel+".plist") stopped, tookDown := stopRunner(ctx, h, domain+"/"+mac.AgentLabel, filepath.Join(share, "state")) if !stopped { if tookDown { // Taken out of launchd but still holding its lock: launchd // gets it back as it was, or the person is told it is not. back, cancel := detached(ctx) defer cancel() if h.launchctl(back, "bootstrap", domain, plist) != nil { say("runner.mac.still_running") return fail("runner.mac.not_restored") } } return fail("runner.mac.still_running") } binary := filepath.Join(lib, "equipo-runner") scannerPath := filepath.Join(lib, "gitleaks") envFile := filepath.Join(conf, "runner.env") // From here until the enrolment is done, a failure puts back what the // runner installed before ran on and starts it again if it was // running. Its launchd agent is not touched before then. The context // may be the one the person ended (Ctrl-C while waiting for the // link): putting back still happens. var backup *installBackup abort := func(key string, a ...any) int { if key != "" { say(key, a...) } kept := backup != nil && backup.kept() restored := backup == nil || backup.restore() if restored && tookDown { back, cancel := detached(ctx) defer cancel() restored = h.launchctl(back, "bootstrap", domain, plist) == nil } switch { case !restored: say("runner.mac.not_restored") case tookDown || kept: say("runner.mac.restored") } return 1 } for _, d := range []string{lib, filepath.Join(share, "state"), filepath.Join(share, "work"), filepath.Join(share, "scratch"), conf, logs} { if err := os.MkdirAll(d, 0700); err != nil { return abort("runner.install.destination") } } if err := os.MkdirAll(agents, 0755); err != nil { return abort("runner.install.destination") } backup, err = newInstallBackup(share) if err != nil { return abort("runner.install.destination") } // Run from the runner installed here (its own install command), the // new copy comes from where that binary was moved aside. source := h.self fromInstalled := sameFile(h.self, binary) if err := backup.keep(binary, scannerPath, filepath.Join(lib, "srt"), envFile); err != nil { return abort("runner.install.destination") } if fromInstalled { source = backup.asideOf(binary) } if err := copyPrivate(source, binary, 0700); err != nil { return abort("runner.install.destination") } scanner, err := h.fetch(ctx, *origin+"/releases/"+*version+"/darwin-arm64/gitleaks", 128<<20) if err != nil { return abort("runner.install.release") } if h.scannerPin == "" || fmt.Sprintf("%x", sha256.Sum256(scanner)) != h.scannerPin { return abort("runner.install.checksum") } if err := os.WriteFile(scannerPath, scanner, 0700); err != nil { return abort("runner.install.destination") } if !release.VerifyGitleaks(scannerPath, h.scannerPin) { return abort("runner.install.checksum") } values := map[string]string{"EQUIPO_ORIGIN": *origin, "EQUIPO_INSTANCE_ID": *instance, "EQUIPO_RUNNER_STATE_DIR": filepath.Join(share, "state"), "EQUIPO_WORKSPACE_ROOT": filepath.Join(share, "work"), "EQUIPO_SCRATCH_ROOT": filepath.Join(share, "scratch"), "EQUIPO_GIT_PATH": "/usr/bin/git"} // srt and what it needs on macOS, all in the runner's own directory: // a Standard user cannot install them with Homebrew. Each archive is // checked against its pinned digest before it is unpacked. fetched := map[string]string{} for _, t := range h.tools { path, err := mac.Fetch(ctx, t, filepath.Join(lib, "tools"), h.fetch) if err != nil { break } fetched[t.Name] = path } if fetched[mac.Node.Name] == "" || fetched[mac.Ripgrep.Name] == "" { say("runner.mac.no_srt") } else { values["EQUIPO_NODE_PATH"], values["EQUIPO_RG_PATH"] = fetched[mac.Node.Name], fetched[mac.Ripgrep.Name] prefix := filepath.Join(lib, "srt") pkg, lock := mac.SRTPackage() if os.MkdirAll(prefix, 0700) != nil || os.WriteFile(filepath.Join(prefix, "package.json"), pkg, 0600) != nil || os.WriteFile(filepath.Join(prefix, "package-lock.json"), lock, 0600) != nil { return abort("runner.install.destination") } if err := h.npmCI(ctx, filepath.Join(filepath.Dir(fetched[mac.Node.Name]), "npm"), prefix, home); err != nil || h.verify(lib) != nil { // Not installed, or not exactly the pinned srt, Node and // ripgrep: the runner would never trust them anyway. say("runner.mac.no_srt") } else { values["EQUIPO_SRT_PATH"] = filepath.Join(prefix, "node_modules", ".bin", "srt") } } h.firstLaunch(ctx, home) label := mac.ComputerName(ctx, h.exec) if label == "" || len(label) > 80 || strings.ContainsAny(label, "\r\n\x00") { label = "Mac" } values["EQUIPO_MACHINE_LABEL"] = label if err := writeEnvFile(envFile, values); err != nil { return abort("runner.install.config") } cfg := runner.Config{Origin: *origin, InstanceID: *instance, StateDir: values["EQUIPO_RUNNER_STATE_DIR"], WorkspaceRoot: values["EQUIPO_WORKSPACE_ROOT"], ScratchRoot: values["EQUIPO_SCRATCH_ROOT"], GitPath: values["EQUIPO_GIT_PATH"], MachineLabel: label, Executable: binary, WorkerOnly: true} // The line to open the link comes right before the link, and only // when there is one: a valid enrolment is kept and said so instead. report := macEnrolReport(errout, filepath.Join(logs, "install.log")) cfg.EnrolNotify = report.notify // An error after the credential was published (its directory sync) // is still an enrolment: what was kept aside is not put back beside it. before := credentialBefore(cfg.StateDir) if err := h.enrol(ctx, cfg, out); err != nil { enrolled, unknown := enrolOutcome(cfg.StateDir, *origin, *instance, before) switch { case unknown: // Whether it was published cannot be read: nothing is put back // beside what may be a new credential, and what was kept aside // stays where it is. report.failed(err) return fail("runner.mac.not_restored") case enrolled: case errors.Is(err, runner.ErrEnrolledAsPrimary): return abort("runner.needs_primary") default: report.failed(err) return abort("") } } // Enrolled: the state now holds the credential this configuration // goes with, so the earlier one is not put back any more. backup.drop() if err := os.WriteFile(plist, mac.LaunchAgent(binary, envFile, logs), 0644); err != nil { return fail("runner.install.service") } if err := h.launchctl(ctx, "bootstrap", domain, plist); err != nil { return fail("runner.install.service") } say("runner.mac.installed") return 0 } // fetchTool downloads a pinned tool archive over HTTPS, following // redirects (GitHub's release downloads redirect to its object store) only // to HTTPS. The pinned digest, checked by mac.Fetch, is what is trusted. func fetchTool(ctx context.Context, url string, limit int64) ([]byte, error) { c := http.Client{Timeout: 10 * time.Minute, CheckRedirect: func(r *http.Request, via []*http.Request) error { if r.URL.Scheme != "https" || len(via) > 5 { return errors.New("refused redirect") } return nil }} req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil || req.URL.Scheme != "https" { return nil, errors.New("refused tool URL") } resp, err := c.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, errors.New("tool download: " + resp.Status) } b, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) if err != nil || int64(len(b)) > limit { return nil, errors.New("tool download too large") } return b, nil } func writeEnvFile(path string, values map[string]string) error { keys := make([]string, 0, len(values)) for k := range values { keys = append(keys, k) } sort.Strings(keys) var b strings.Builder for _, k := range keys { fmt.Fprintf(&b, "%s=%s\n", k, strconv.Quote(values[k])) } tmp := path + ".new" if err := os.WriteFile(tmp, []byte(b.String()), 0600); err != nil { return err } if err := os.Chmod(tmp, 0600); err != nil { return err } if err := os.Rename(tmp, path); err != nil { return err } // Read it back the way the agent will. _, err := runnersetup.ReadEnvFile(path) return err } func copyPrivate(src, dst string, mode os.FileMode) error { if src == "" { return errors.New("no source") } raw, err := os.ReadFile(src) if err != nil { return err } tmp, err := os.CreateTemp(filepath.Dir(dst), ".equipo-runner-") if err != nil { return err } defer os.Remove(tmp.Name()) if _, err = tmp.Write(raw); err == nil { err = tmp.Chmod(mode) } if cerr := tmp.Close(); err == nil { err = cerr } if err != nil { return err } return os.Rename(tmp.Name(), dst) } // stopRunner stops a runner installed before and confirms it stopped: // launchd no longer has the agent, and the runner's state lock is free. // It changes nothing itself; not stopped means do not change anything. // tookDown is whether it took the agent out of launchd (which loads it // again if the install does not go ahead); a refused bootout did not. func stopRunner(ctx context.Context, h macInstallHost, service, state string) (stopped, tookDown bool) { if h.launchctl(ctx, "print", service) != nil { // Not loaded. Its lock must still be free: a runner started by // hand holds it too. return lockFree(state), false } // The bootout is not cut short by Ctrl-C: launchd may have taken the // agent out before it answers, and whether it did is checked below. stop, cancel := detached(ctx) defer cancel() refused := h.launchctl(stop, "bootout", service) != nil check, cancelCheck := detached(ctx) defer cancelCheck() if refused && h.launchctl(check, "print", service) == nil { // Refused, and the agent is still there: nothing was taken down. return false, false } return waitStopped(ctx, h, service, state), true } // sameFile reports whether a and b are the same existing file. func sameFile(a, b string) bool { ai, err := os.Stat(a) if err != nil { return false } bi, err := os.Stat(b) return err == nil && os.SameFile(ai, bi) } // waitStopped waits for a booted-out runner to be gone and its lock free. func waitStopped(ctx context.Context, h macInstallHost, service, state string) bool { wait := h.stopWait if wait <= 0 { wait = time.Minute } deadline := time.Now().Add(wait) for { if h.launchctl(ctx, "print", service) != nil && lockFree(state) { return true } if time.Now().After(deadline) { return false } select { case <-ctx.Done(): return false case <-time.After(250 * time.Millisecond): } } } // lockFree reports whether no runner holds the state lock (a state dir // not made yet is free). func lockFree(state string) bool { if _, err := os.Stat(state); os.IsNotExist(err) { return true } lock, err := runner.LockState(state) if err != nil { return false } return lock.Close() == nil }