| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "io" |
| 9 | "os/exec" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | type limitedLoginOutput struct{ bytes.Buffer } |
| 16 | |
| 17 | func (b *limitedLoginOutput) Write(p []byte) (int, error) { |
| 18 | if b.Len()+len(p) > 65536 { |
| 19 | return 0, ErrIdentity |
| 20 | } |
| 21 | return b.Buffer.Write(p) |
| 22 | } |
| 23 | |
| 24 | // Probe uses the Plan 2b identity readback contracts, never login output. |
| 25 | // Unconfined CLI probes run only in source homes, under the caller's lock. |
| 26 | func (d *terminalLoginDriver) Probe(ctx context.Context, b Binding) (Identity, error) { |
| 27 | return d.probe(ctx, b, false) |
| 28 | } |
| 29 | |
| 30 | // RefreshLogin uses only CLI account metadata. Tokens remain private to the CLI. |
| 31 | func RefreshLogin(ctx context.Context, b Binding, options LoginOptions) (Identity, error) { |
| 32 | return (&terminalLoginDriver{options: options}).probe(ctx, b, true) |
| 33 | } |
| 34 | |
| 35 | func (d *terminalLoginDriver) probe(ctx context.Context, b Binding, refresh bool) (Identity, error) { |
| 36 | return d.probeReading(ctx, b, refresh, nil, nil) |
| 37 | } |
| 38 | |
| 39 | // ReadCodexLimits is the reading probe for a Codex home (connectors spec |
| 40 | // rev 3.2 §6, the controller's ruling #7): the same unconfined app-server |
| 41 | // in the source home, under the caller's lock, with the same environment |
| 42 | // and egress as the hourly refresh, asked account/read and then |
| 43 | // account/rateLimits/read. It starts no thread and no turn. It returns |
| 44 | // the account's identity and the rateLimits object as the app-server |
| 45 | // sent it. |
| 46 | func ReadCodexLimits(ctx context.Context, b Binding, options LoginOptions) (Identity, json.RawMessage, error) { |
| 47 | if b.Provider != "codex" { |
| 48 | return Identity{}, nil, ErrLoginUnavailable |
| 49 | } |
| 50 | var limits json.RawMessage |
| 51 | id, err := (&terminalLoginDriver{options: options}).probeReading(ctx, b, false, &limits, nil) |
| 52 | if err != nil { |
| 53 | return Identity{}, nil, err |
| 54 | } |
| 55 | return id, limits, nil |
| 56 | } |
| 57 | |
| 58 | // probeReading is probe, and for a Codex home with limits set, the |
| 59 | // account's rate limits read after its identity. |
| 60 | func (d *terminalLoginDriver) probeReading(ctx context.Context, b Binding, refresh bool, limits *json.RawMessage, plan *string) (Identity, error) { |
| 61 | if b.provenance != nil { |
| 62 | return Identity{}, ErrPolicy |
| 63 | } |
| 64 | if ctx.Err() != nil { |
| 65 | return Identity{}, ctx.Err() |
| 66 | } |
| 67 | if !d.Supported(b.Provider) { |
| 68 | return Identity{}, ErrLoginUnavailable |
| 69 | } |
| 70 | ctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 71 | defer cancel() |
| 72 | if b.Provider == "claude" { |
| 73 | cmd := exec.CommandContext(ctx, d.binary(b.Provider), "auth", "status", "--json") |
| 74 | // A token home's token goes in the environment, never in argv. |
| 75 | env, err := tokenEnvironment(b) |
| 76 | if err != nil { |
| 77 | return Identity{}, ErrLoginRequired |
| 78 | } |
| 79 | cmd.Env = env |
| 80 | cmd.Dir = b.Home |
| 81 | out := &limitedLoginOutput{} |
| 82 | cmd.Stdout = out |
| 83 | err = cmd.Run() |
| 84 | if ctx.Err() != nil { |
| 85 | return Identity{}, ctx.Err() |
| 86 | } |
| 87 | if b.Token { |
| 88 | id, _, perr := ClaudeTokenIdentity(out.Bytes(), b.ID) |
| 89 | if perr != nil || err != nil { |
| 90 | return Identity{}, ErrLoginRequired |
| 91 | } |
| 92 | return id, nil |
| 93 | } |
| 94 | var status struct { |
| 95 | LoggedIn *bool `json:"loggedIn"` |
| 96 | } |
| 97 | if refresh && json.Unmarshal(out.Bytes(), &status) == nil && status.LoggedIn != nil && !*status.LoggedIn { |
| 98 | return Identity{}, ErrLoginRequired |
| 99 | } |
| 100 | if err != nil { |
| 101 | if !refresh { |
| 102 | return Identity{}, ErrIdentity |
| 103 | } |
| 104 | return Identity{}, ErrLoginUnavailable |
| 105 | } |
| 106 | id, err := ClaudeLoginIdentity(out.Bytes()) |
| 107 | if err == nil && plan != nil { |
| 108 | var status struct { |
| 109 | SubscriptionType string `json:"subscriptionType"` |
| 110 | } |
| 111 | if json.Unmarshal(out.Bytes(), &status) == nil { |
| 112 | *plan = status.SubscriptionType |
| 113 | } |
| 114 | } |
| 115 | return id, err |
| 116 | } |
| 117 | if b.Provider != "codex" { |
| 118 | return Identity{}, ErrIdentity |
| 119 | } |
| 120 | cmd := exec.CommandContext(ctx, d.binary(b.Provider), "app-server", "--strict-config", "--listen", "stdio://") |
| 121 | cmd.Env = LoginEnvironment(b.Provider, b.Home) |
| 122 | cmd.Dir = b.Home |
| 123 | in, err := cmd.StdinPipe() |
| 124 | if err != nil { |
| 125 | return Identity{}, ErrIdentity |
| 126 | } |
| 127 | defer in.Close() |
| 128 | out, err := cmd.StdoutPipe() |
| 129 | if err != nil { |
| 130 | return Identity{}, ErrIdentity |
| 131 | } |
| 132 | if err = cmd.Start(); err != nil { |
| 133 | return Identity{}, ErrIdentity |
| 134 | } |
| 135 | stopPipes := context.AfterFunc(ctx, func() { _ = in.Close(); _ = out.Close() }) |
| 136 | defer stopPipes() |
| 137 | defer func() { cancel(); _ = cmd.Wait() }() |
| 138 | scan := bufio.NewScanner(out) |
| 139 | scan.Buffer(make([]byte, 4096), 65536) |
| 140 | startupNoticeSeen := false |
| 141 | call := func(id, method string, params any) (json.RawMessage, error) { |
| 142 | if json.NewEncoder(in).Encode(map[string]any{"id": id, "method": method, "params": params}) != nil { |
| 143 | return nil, ErrIdentity |
| 144 | } |
| 145 | for frames := 0; frames < 64; frames++ { |
| 146 | if !scan.Scan() { |
| 147 | return nil, ErrIdentity |
| 148 | } |
| 149 | raw, err := canonical(scan.Bytes()) |
| 150 | if err != nil { |
| 151 | return nil, ErrIdentity |
| 152 | } |
| 153 | var r struct { |
| 154 | Method string |
| 155 | ID, Params, Result, Error json.RawMessage |
| 156 | } |
| 157 | if json.Unmarshal(raw, &r) != nil { |
| 158 | return nil, ErrIdentity |
| 159 | } |
| 160 | // A notification about anything but the account (the recorded |
| 161 | // 0.165.0 remoteControl/status/changed, rate limits) says |
| 162 | // nothing about who is signed in: passed over, as the |
| 163 | // rate-limit read below does. account/updated is the account |
| 164 | // itself, and only its one startup notice is allowed. |
| 165 | if len(r.ID) == 0 && r.Method != "" && r.Method != "account/updated" && len(r.Error) == 0 && len(r.Result) == 0 { |
| 166 | continue |
| 167 | } |
| 168 | if !startupNoticeSeen && len(r.Error) == 0 && len(r.Result) == 0 && CodexStartupNotice(r.ID, r.Method, r.Params) { |
| 169 | startupNoticeSeen = true |
| 170 | continue |
| 171 | } |
| 172 | if refresh && method == "account/read" && string(r.ID) == strconv.Quote(id) && r.Method == "" && refreshRevoked(r.Error) { |
| 173 | return nil, ErrLoginRequired |
| 174 | } |
| 175 | if string(r.ID) != strconv.Quote(id) || r.Method != "" || len(r.Error) != 0 { |
| 176 | return nil, ErrIdentity |
| 177 | } |
| 178 | return r.Result, nil |
| 179 | } |
| 180 | return nil, ErrIdentity |
| 181 | } |
| 182 | raw, err := call("1", "initialize", map[string]any{"clientInfo": map[string]string{"name": "equipo", "version": "2"}, "capabilities": map[string]bool{"experimentalApi": true}}) |
| 183 | var init struct{ UserAgent, CodexHome string } |
| 184 | if err != nil || json.Unmarshal(raw, &init) != nil || !strings.HasPrefix(init.UserAgent, "equipo/"+LoginVersion("codex")+" ") || init.CodexHome != b.Home { |
| 185 | return Identity{}, ErrIdentity |
| 186 | } |
| 187 | if _, err = io.WriteString(in, "{\"method\":\"initialized\",\"params\":{}}\n"); err != nil { |
| 188 | return Identity{}, ErrIdentity |
| 189 | } |
| 190 | raw, err = call("2", "account/read", map[string]bool{"refreshToken": refresh}) |
| 191 | if err != nil { |
| 192 | return Identity{}, err |
| 193 | } |
| 194 | if refresh { |
| 195 | var status struct { |
| 196 | Account json.RawMessage `json:"account"` |
| 197 | } |
| 198 | if json.Unmarshal(raw, &status) == nil && string(status.Account) == "null" { |
| 199 | return Identity{}, ErrLoginRequired |
| 200 | } |
| 201 | } |
| 202 | id, err := CodexLoginIdentity(raw) |
| 203 | if err != nil || limits == nil { |
| 204 | return id, err |
| 205 | } |
| 206 | // The rate limits: one request, its answer; notifications the |
| 207 | // app-server sends meanwhile (a rate-limit update among them) are |
| 208 | // passed over, a request it makes of us ends the read. |
| 209 | if json.NewEncoder(in).Encode(map[string]any{"id": "3", "method": "account/rateLimits/read", "params": nil}) != nil { |
| 210 | return Identity{}, ErrIdentity |
| 211 | } |
| 212 | for frames := 0; frames < 64; frames++ { |
| 213 | if !scan.Scan() { |
| 214 | return Identity{}, ErrIdentity |
| 215 | } |
| 216 | var r struct { |
| 217 | Method string |
| 218 | ID, Params, Result, Error json.RawMessage |
| 219 | } |
| 220 | if json.Unmarshal(scan.Bytes(), &r) != nil { |
| 221 | return Identity{}, ErrIdentity |
| 222 | } |
| 223 | if len(r.ID) == 0 && r.Method != "" { |
| 224 | continue |
| 225 | } |
| 226 | if string(r.ID) != `"3"` || r.Method != "" || len(r.Error) != 0 { |
| 227 | return Identity{}, ErrIdentity |
| 228 | } |
| 229 | var v struct { |
| 230 | RateLimits json.RawMessage `json:"rateLimits"` |
| 231 | } |
| 232 | if json.Unmarshal(r.Result, &v) != nil || len(v.RateLimits) == 0 || string(v.RateLimits) == "null" { |
| 233 | return Identity{}, ErrIdentity |
| 234 | } |
| 235 | *limits = v.RateLimits |
| 236 | return id, nil |
| 237 | } |
| 238 | return Identity{}, ErrIdentity |
| 239 | } |
| 240 | |
| 241 | func ClaudeLoginIdentity(raw []byte) (Identity, error) { |
| 242 | raw, err := canonical(raw) |
| 243 | var status struct { |
| 244 | LoggedIn bool |
| 245 | AuthMethod, Email string |
| 246 | } |
| 247 | if err != nil || json.Unmarshal(raw, &status) != nil || !status.LoggedIn || status.AuthMethod != "claude.ai" || status.Email == "" { |
| 248 | return Identity{}, ErrIdentity |
| 249 | } |
| 250 | return Identity{AccountID: status.Email, ProviderVersion: LoginVersion("claude")}, nil |
| 251 | } |
| 252 | func CodexLoginIdentity(raw []byte) (Identity, error) { |
| 253 | raw, err := canonical(raw) |
| 254 | var v struct{ Account *struct{ Type, Email string } } |
| 255 | if err != nil || json.Unmarshal(raw, &v) != nil || v.Account == nil || v.Account.Type != "chatgpt" || v.Account.Email == "" { |
| 256 | return Identity{}, ErrIdentity |
| 257 | } |
| 258 | return Identity{AccountID: v.Account.Email, ProviderVersion: LoginVersion("codex")}, nil |
| 259 | } |
| 260 | |
| 261 | func refreshRevoked(raw []byte) bool { |
| 262 | var reply struct{ Message string } |
| 263 | if json.Unmarshal(raw, &reply) != nil { |
| 264 | return false |
| 265 | } |
| 266 | for _, reason := range []string{"refresh_token_expired", "refresh_token_reused", "refresh_token_invalidated", "invalid_grant", "your refresh token has expired", "your refresh token was already used", "your refresh token was revoked"} { |
| 267 | if strings.Contains(reply.Message, reason) { |
| 268 | return true |
| 269 | } |
| 270 | } |
| 271 | return false |
| 272 | } |
| 273 | |
| 274 | // ReadClaudeStatus returns the subscription reported by auth status separately |
| 275 | // from identity: a plan change must never invalidate a connection's identity. |
| 276 | func ReadClaudeStatus(ctx context.Context, b Binding, options LoginOptions) (Identity, string, error) { |
| 277 | if b.Provider != "claude" || b.Token { |
| 278 | return Identity{}, "", ErrPolicy |
| 279 | } |
| 280 | var plan string |
| 281 | id, err := (&terminalLoginDriver{options: options}).probeReading(ctx, b, true, nil, &plan) |
| 282 | return id, plan, err |
| 283 | } |
| 284 | |