| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net/url" |
| 10 | "os/exec" |
| 11 | "syscall" |
| 12 | "time" |
| 13 | |
| 14 | "golang.org/x/sys/unix" |
| 15 | ) |
| 16 | |
| 17 | // Sign-in outcomes a connection attempt reports (wire.ConnectReasons). |
| 18 | var ( |
| 19 | ErrRefused = errors.New("provider_refused") |
| 20 | ErrTimedOut = errors.New("timed_out") |
| 21 | ErrCancelled = errors.New("cancelled") |
| 22 | ) |
| 23 | |
| 24 | // Account is who a sign-in signed in, as the provider's CLI reports it. |
| 25 | type Account struct { |
| 26 | Email, Plan string |
| 27 | Limits *Limit |
| 28 | } |
| 29 | |
| 30 | // CodexDeviceLogin signs a new Codex home in by device code (spec §2.2): |
| 31 | // the pinned app-server in that home asks OpenAI for a code |
| 32 | // (account/login/start, chatgptDeviceCode), prompt shows the person the |
| 33 | // verification URL and the code, and the app-server polls OpenAI until |
| 34 | // the person approves (account/login/completed). Nothing is typed back |
| 35 | // into Equipo; the tokens stay in the home's auth.json. |
| 36 | func CodexDeviceLogin(ctx context.Context, binary, home string, env []string, prompt func(verifyURL, code string)) (Account, error) { |
| 37 | cmd := exec.Command(binary, "app-server", "--strict-config", "--listen", "stdio://") |
| 38 | cmd.Dir, cmd.Env = home, env |
| 39 | cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| 40 | in, err := cmd.StdinPipe() |
| 41 | if err != nil { |
| 42 | return Account{}, err |
| 43 | } |
| 44 | out, err := cmd.StdoutPipe() |
| 45 | if err != nil { |
| 46 | return Account{}, err |
| 47 | } |
| 48 | cmd.Stderr = io.Discard |
| 49 | if err = cmd.Start(); err != nil { |
| 50 | return Account{}, err |
| 51 | } |
| 52 | defer func() { |
| 53 | in.Close() |
| 54 | done := make(chan struct{}) |
| 55 | go func() { _ = cmd.Wait(); close(done) }() |
| 56 | select { |
| 57 | case <-done: |
| 58 | case <-time.After(5 * time.Second): |
| 59 | _ = unix.Kill(-cmd.Process.Pid, unix.SIGKILL) |
| 60 | <-done |
| 61 | } |
| 62 | }() |
| 63 | rpc := NewAppServer(out, in) |
| 64 | call := func(method string, params any) (json.RawMessage, error) { |
| 65 | cctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 66 | defer cancel() |
| 67 | raw, _, err := rpc.Call(cctx, method, params) |
| 68 | return raw, err |
| 69 | } |
| 70 | raw, err := call("initialize", map[string]any{"clientInfo": map[string]any{"name": "equipo", "version": "2"}, "capabilities": map[string]any{"experimentalApi": true}}) |
| 71 | var init struct{ CodexHome string } |
| 72 | if err != nil || json.Unmarshal(raw, &init) != nil || init.CodexHome != home { |
| 73 | return Account{}, fmt.Errorf("codex app-server did not start in the new home") |
| 74 | } |
| 75 | _ = rpc.Notify("initialized", map[string]any{}) |
| 76 | raw, err = call("account/login/start", map[string]string{"type": "chatgptDeviceCode"}) |
| 77 | var start struct { |
| 78 | Type, LoginID, VerificationURL, UserCode string |
| 79 | } |
| 80 | if err != nil || json.Unmarshal(raw, &start) != nil || start.Type != "chatgptDeviceCode" || start.LoginID == "" || start.UserCode == "" { |
| 81 | return Account{}, ErrRefused |
| 82 | } |
| 83 | u, err := url.Parse(start.VerificationURL) |
| 84 | if err != nil || u.Scheme != "https" || len(start.UserCode) > 32 { |
| 85 | return Account{}, ErrRefused |
| 86 | } |
| 87 | prompt(start.VerificationURL, start.UserCode) |
| 88 | for { |
| 89 | select { |
| 90 | case <-ctx.Done(): |
| 91 | cctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 92 | _, _, _ = rpc.Call(cctx, "account/login/cancel", map[string]string{"loginId": start.LoginID}) |
| 93 | cancel() |
| 94 | if errors.Is(ctx.Err(), context.DeadlineExceeded) { |
| 95 | return Account{}, ErrTimedOut |
| 96 | } |
| 97 | return Account{}, ErrCancelled |
| 98 | case m, ok := <-rpc.Messages: |
| 99 | if !ok { |
| 100 | return Account{}, ErrRefused |
| 101 | } |
| 102 | if len(m.ID) > 0 { |
| 103 | _ = rpc.Refuse(m.ID) |
| 104 | continue |
| 105 | } |
| 106 | if m.Method != "account/login/completed" { |
| 107 | continue |
| 108 | } |
| 109 | var done struct { |
| 110 | LoginID *string `json:"loginId"` |
| 111 | Success bool `json:"success"` |
| 112 | } |
| 113 | if json.Unmarshal(m.Params, &done) != nil || done.LoginID != nil && *done.LoginID != start.LoginID { |
| 114 | continue |
| 115 | } |
| 116 | if !done.Success { |
| 117 | return Account{}, ErrRefused |
| 118 | } |
| 119 | raw, err = call("account/read", map[string]bool{"refreshToken": false}) |
| 120 | var acct struct { |
| 121 | Account *struct{ Type, Email, PlanType string } |
| 122 | } |
| 123 | if err != nil || json.Unmarshal(raw, &acct) != nil || acct.Account == nil || acct.Account.Type != "chatgpt" || acct.Account.Email == "" { |
| 124 | return Account{}, ErrRefused |
| 125 | } |
| 126 | a := Account{Email: acct.Account.Email, Plan: acct.Account.PlanType} |
| 127 | if raw, err = call("account/rateLimits/read", nil); err == nil { |
| 128 | var v struct { |
| 129 | RateLimits json.RawMessage `json:"rateLimits"` |
| 130 | } |
| 131 | if json.Unmarshal(raw, &v) == nil { |
| 132 | if l, plan, ok := CodexRateLimits(v.RateLimits); ok { |
| 133 | a.Limits = &l |
| 134 | if a.Plan == "" { |
| 135 | a.Plan = plan |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | return a, nil |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |