package thin import ( "context" "crypto/rand" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "strings" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/oficina/equipo/internal/runnerproto" "golang.org/x/sys/unix" ) // DefaultModels are the coordinator models recorded for a new login. var DefaultModels = map[string]string{"claude": "claude-opus-5-5", "codex": "gpt-6-astra"} // LoginOptions configure `equipo-runner login `. type LoginOptions struct { // Root holds dedicated homes: /-. Root string Input io.Reader Output io.Writer // Command runs the provider's own interactive sign-in. Tests replace it. Command func(ctx context.Context, binary string, args []string, dir string, env []string) error } // DefaultAccountsRoot is ~/.local/share/equipo/accounts. func DefaultAccountsRoot() string { home, _ := os.UserHomeDir() return filepath.Join(home, ".local", "share", "equipo", "accounts") } // Login runs the official login into a new dedicated home, records the // email the CLI observed and adds the account to the bindings file for the // runner's own person. Credentials stay in the home; nothing is printed // but the provider's own sign-in prompts and the observed email. func Login(ctx context.Context, c runner.Config, name string, o LoginOptions) error { if name != "claude" && name != "codex" { return provider.ErrProvider } creds, err := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json")) if err != nil { return err } person := creds.Bearer.Person if person == "" { return provider.ErrIdentity } if o.Root == "" { o.Root = DefaultAccountsRoot() } if o.Command == nil { o.Command = func(ctx context.Context, binary string, args []string, dir string, env []string) error { cmd := exec.CommandContext(ctx, binary, args...) cmd.Dir, cmd.Env = dir, env cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Input, o.Output, o.Output return cmd.Run() } } if err = os.MkdirAll(o.Root, 0700); err != nil { return err } id, home, err := nextHome(o.Root, name) if err != nil { return err } if err = provider.CheckLoginHome(home); err != nil { os.Remove(home) return err } lock, err := os.Open(home) if err != nil { return err } defer lock.Close() if err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { return provider.ErrAccountBusy } binary, args := c.ClaudePath, []string{"auth", "login"} if name == "codex" { binary, args = c.CodexPath, []string{"login", "--device-auth"} } env := provider.LoginEnvironment(name, home) for _, key := range []string{"BROWSER", "DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"} { if v := os.Getenv(key); v != "" { env = append(env, key+"="+v) } } if err = o.Command(ctx, binary, args, home, env); err != nil { return fmt.Errorf("%w: sign-in did not finish", provider.ErrLoginRequired) } // The probe runs the CLI in the home under its lock. observed, err := finishLogin(ctx, c, person, name, id, home) if err != nil { return err } if err = unix.Flock(int(lock.Fd()), unix.LOCK_UN); err != nil { return err } _, err = fmt.Fprintf(o.Output, "Signed in as %s. Saved as %s.\n", observed.AccountID, id) // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) return err } // finishLogin records a home the provider's own CLI just signed in: the // identity the CLI reports (never its login output), the identity file, // and the binding for the person. Credentials stay in the home. func finishLogin(ctx context.Context, c runner.Config, person, name, id, home string) (provider.Identity, error) { options := provider.LoginOptions{ClaudePath: c.ClaudePath, CodexPath: c.CodexPath} probe, ok := provider.NewLoginDriver(options).(interface { Probe(context.Context, provider.Binding) (provider.Identity, error) }) if !ok { return provider.Identity{}, provider.ErrLoginUnavailable } observed, err := probe.Probe(ctx, provider.Binding{ID: id, Home: home, Provider: name}) if err != nil { return observed, err } return observed, saveLogin(ctx, c, person, name, id, home, observed) } // saveLogin records the identity the CLI reported for a home: the // identity file and the binding for the person. func saveLogin(ctx context.Context, c runner.Config, person, name, id, home string, observed provider.Identity) error { if observed.AccountID == "" || strings.ContainsAny(observed.AccountID, "\r\n\x1b") { return provider.ErrIdentity } observed.HomeID = rand.Text() raw, _ := json.Marshal(observed) if err := os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600); err != nil { return err } b := provider.Binding{ID: id, Home: home, Provider: name, AccountID: observed.AccountID, Expected: observed} return runnersetup.SaveAccountBinding(ctx, c.AccountBindingsPath, person, DefaultModels[name], runnerproto.AccountSetup{ID: id, Provider: name, Label: id}, b) } // nextHome creates the first free - directory. // uniqueHome makes a home whose name is never reused: name and a random // suffix. func uniqueHome(root, name string) (string, string, error) { for n := 0; n < 10; n++ { id := name + "-" + strings.ToLower(rand.Text()[:12]) home := filepath.Join(root, id) err := os.Mkdir(home, 0700) if err == nil { return id, home, nil } if !errors.Is(err, os.ErrExist) { return "", "", err } } return "", "", provider.ErrAccountMaintenance } func nextHome(root, name string) (string, string, error) { for n := 1; n < 1000; n++ { id := fmt.Sprintf("%s-%d", name, n) home := filepath.Join(root, id) err := os.Mkdir(home, 0700) if err == nil { return id, home, nil } if !errors.Is(err, os.ErrExist) { return "", "", err } } return "", "", provider.ErrAccountMaintenance }