package connect import ( "context" "encoding/json" "errors" "fmt" "io" "net/url" "os/exec" "syscall" "time" "golang.org/x/sys/unix" ) // Sign-in outcomes a connection attempt reports (wire.ConnectReasons). var ( ErrRefused = errors.New("provider_refused") ErrTimedOut = errors.New("timed_out") ErrCancelled = errors.New("cancelled") ) // Account is who a sign-in signed in, as the provider's CLI reports it. type Account struct { Email, Plan string Limits *Limit } // CodexDeviceLogin signs a new Codex home in by device code (spec ยง2.2): // the pinned app-server in that home asks OpenAI for a code // (account/login/start, chatgptDeviceCode), prompt shows the person the // verification URL and the code, and the app-server polls OpenAI until // the person approves (account/login/completed). Nothing is typed back // into Equipo; the tokens stay in the home's auth.json. func CodexDeviceLogin(ctx context.Context, binary, home string, env []string, prompt func(verifyURL, code string)) (Account, error) { cmd := exec.Command(binary, "app-server", "--strict-config", "--listen", "stdio://") cmd.Dir, cmd.Env = home, env cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} in, err := cmd.StdinPipe() if err != nil { return Account{}, err } out, err := cmd.StdoutPipe() if err != nil { return Account{}, err } cmd.Stderr = io.Discard if err = cmd.Start(); err != nil { return Account{}, err } defer func() { in.Close() done := make(chan struct{}) go func() { _ = cmd.Wait(); close(done) }() select { case <-done: case <-time.After(5 * time.Second): _ = unix.Kill(-cmd.Process.Pid, unix.SIGKILL) <-done } }() rpc := NewAppServer(out, in) call := func(method string, params any) (json.RawMessage, error) { cctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() raw, _, err := rpc.Call(cctx, method, params) return raw, err } raw, err := call("initialize", map[string]any{"clientInfo": map[string]any{"name": "equipo", "version": "2"}, "capabilities": map[string]any{"experimentalApi": true}}) var init struct{ CodexHome string } if err != nil || json.Unmarshal(raw, &init) != nil || init.CodexHome != home { return Account{}, fmt.Errorf("codex app-server did not start in the new home") } _ = rpc.Notify("initialized", map[string]any{}) raw, err = call("account/login/start", map[string]string{"type": "chatgptDeviceCode"}) var start struct { Type, LoginID, VerificationURL, UserCode string } if err != nil || json.Unmarshal(raw, &start) != nil || start.Type != "chatgptDeviceCode" || start.LoginID == "" || start.UserCode == "" { return Account{}, ErrRefused } u, err := url.Parse(start.VerificationURL) if err != nil || u.Scheme != "https" || len(start.UserCode) > 32 { return Account{}, ErrRefused } prompt(start.VerificationURL, start.UserCode) for { select { case <-ctx.Done(): cctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) _, _, _ = rpc.Call(cctx, "account/login/cancel", map[string]string{"loginId": start.LoginID}) cancel() if errors.Is(ctx.Err(), context.DeadlineExceeded) { return Account{}, ErrTimedOut } return Account{}, ErrCancelled case m, ok := <-rpc.Messages: if !ok { return Account{}, ErrRefused } if len(m.ID) > 0 { _ = rpc.Refuse(m.ID) continue } if m.Method != "account/login/completed" { continue } var done struct { LoginID *string `json:"loginId"` Success bool `json:"success"` } if json.Unmarshal(m.Params, &done) != nil || done.LoginID != nil && *done.LoginID != start.LoginID { continue } if !done.Success { return Account{}, ErrRefused } raw, err = call("account/read", map[string]bool{"refreshToken": false}) var acct struct { Account *struct{ Type, Email, PlanType string } } if err != nil || json.Unmarshal(raw, &acct) != nil || acct.Account == nil || acct.Account.Type != "chatgpt" || acct.Account.Email == "" { return Account{}, ErrRefused } a := Account{Email: acct.Account.Email, Plan: acct.Account.PlanType} if raw, err = call("account/rateLimits/read", nil); err == nil { var v struct { RateLimits json.RawMessage `json:"rateLimits"` } if json.Unmarshal(raw, &v) == nil { if l, plan, ok := CodexRateLimits(v.RateLimits); ok { a.Limits = &l if a.Plan == "" { a.Plan = plan } } } } return a, nil } } }