package provider import ( "bufio" "bytes" "context" "encoding/json" "io" "os/exec" "strconv" "strings" "time" ) type limitedLoginOutput struct{ bytes.Buffer } func (b *limitedLoginOutput) Write(p []byte) (int, error) { if b.Len()+len(p) > 65536 { return 0, ErrIdentity } return b.Buffer.Write(p) } // Probe uses the Plan 2b identity readback contracts, never login output. // Unconfined CLI probes run only in source homes, under the caller's lock. func (d *terminalLoginDriver) Probe(ctx context.Context, b Binding) (Identity, error) { return d.probe(ctx, b, false) } // RefreshLogin uses only CLI account metadata. Tokens remain private to the CLI. func RefreshLogin(ctx context.Context, b Binding, options LoginOptions) (Identity, error) { return (&terminalLoginDriver{options: options}).probe(ctx, b, true) } func (d *terminalLoginDriver) probe(ctx context.Context, b Binding, refresh bool) (Identity, error) { return d.probeReading(ctx, b, refresh, nil, nil) } // ReadCodexLimits is the reading probe for a Codex home (connectors spec // rev 3.2 ยง6, the controller's ruling #7): the same unconfined app-server // in the source home, under the caller's lock, with the same environment // and egress as the hourly refresh, asked account/read and then // account/rateLimits/read. It starts no thread and no turn. It returns // the account's identity and the rateLimits object as the app-server // sent it. func ReadCodexLimits(ctx context.Context, b Binding, options LoginOptions) (Identity, json.RawMessage, error) { if b.Provider != "codex" { return Identity{}, nil, ErrLoginUnavailable } var limits json.RawMessage id, err := (&terminalLoginDriver{options: options}).probeReading(ctx, b, false, &limits, nil) if err != nil { return Identity{}, nil, err } return id, limits, nil } // probeReading is probe, and for a Codex home with limits set, the // account's rate limits read after its identity. func (d *terminalLoginDriver) probeReading(ctx context.Context, b Binding, refresh bool, limits *json.RawMessage, plan *string) (Identity, error) { if b.provenance != nil { return Identity{}, ErrPolicy } if ctx.Err() != nil { return Identity{}, ctx.Err() } if !d.Supported(b.Provider) { return Identity{}, ErrLoginUnavailable } ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() if b.Provider == "claude" { cmd := exec.CommandContext(ctx, d.binary(b.Provider), "auth", "status", "--json") // A token home's token goes in the environment, never in argv. env, err := tokenEnvironment(b) if err != nil { return Identity{}, ErrLoginRequired } cmd.Env = env cmd.Dir = b.Home out := &limitedLoginOutput{} cmd.Stdout = out err = cmd.Run() if ctx.Err() != nil { return Identity{}, ctx.Err() } if b.Token { id, _, perr := ClaudeTokenIdentity(out.Bytes(), b.ID) if perr != nil || err != nil { return Identity{}, ErrLoginRequired } return id, nil } var status struct { LoggedIn *bool `json:"loggedIn"` } if refresh && json.Unmarshal(out.Bytes(), &status) == nil && status.LoggedIn != nil && !*status.LoggedIn { return Identity{}, ErrLoginRequired } if err != nil { if !refresh { return Identity{}, ErrIdentity } return Identity{}, ErrLoginUnavailable } id, err := ClaudeLoginIdentity(out.Bytes()) if err == nil && plan != nil { var status struct { SubscriptionType string `json:"subscriptionType"` } if json.Unmarshal(out.Bytes(), &status) == nil { *plan = status.SubscriptionType } } return id, err } if b.Provider != "codex" { return Identity{}, ErrIdentity } cmd := exec.CommandContext(ctx, d.binary(b.Provider), "app-server", "--strict-config", "--listen", "stdio://") cmd.Env = LoginEnvironment(b.Provider, b.Home) cmd.Dir = b.Home in, err := cmd.StdinPipe() if err != nil { return Identity{}, ErrIdentity } defer in.Close() out, err := cmd.StdoutPipe() if err != nil { return Identity{}, ErrIdentity } if err = cmd.Start(); err != nil { return Identity{}, ErrIdentity } stopPipes := context.AfterFunc(ctx, func() { _ = in.Close(); _ = out.Close() }) defer stopPipes() defer func() { cancel(); _ = cmd.Wait() }() scan := bufio.NewScanner(out) scan.Buffer(make([]byte, 4096), 65536) startupNoticeSeen := false call := func(id, method string, params any) (json.RawMessage, error) { if json.NewEncoder(in).Encode(map[string]any{"id": id, "method": method, "params": params}) != nil { return nil, ErrIdentity } for frames := 0; frames < 64; frames++ { if !scan.Scan() { return nil, ErrIdentity } raw, err := canonical(scan.Bytes()) if err != nil { return nil, ErrIdentity } var r struct { Method string ID, Params, Result, Error json.RawMessage } if json.Unmarshal(raw, &r) != nil { return nil, ErrIdentity } // A notification about anything but the account (the recorded // 0.165.0 remoteControl/status/changed, rate limits) says // nothing about who is signed in: passed over, as the // rate-limit read below does. account/updated is the account // itself, and only its one startup notice is allowed. if len(r.ID) == 0 && r.Method != "" && r.Method != "account/updated" && len(r.Error) == 0 && len(r.Result) == 0 { continue } if !startupNoticeSeen && len(r.Error) == 0 && len(r.Result) == 0 && CodexStartupNotice(r.ID, r.Method, r.Params) { startupNoticeSeen = true continue } if refresh && method == "account/read" && string(r.ID) == strconv.Quote(id) && r.Method == "" && refreshRevoked(r.Error) { return nil, ErrLoginRequired } if string(r.ID) != strconv.Quote(id) || r.Method != "" || len(r.Error) != 0 { return nil, ErrIdentity } return r.Result, nil } return nil, ErrIdentity } raw, err := call("1", "initialize", map[string]any{"clientInfo": map[string]string{"name": "equipo", "version": "2"}, "capabilities": map[string]bool{"experimentalApi": true}}) var init struct{ UserAgent, CodexHome string } if err != nil || json.Unmarshal(raw, &init) != nil || !strings.HasPrefix(init.UserAgent, "equipo/"+LoginVersion("codex")+" ") || init.CodexHome != b.Home { return Identity{}, ErrIdentity } if _, err = io.WriteString(in, "{\"method\":\"initialized\",\"params\":{}}\n"); err != nil { return Identity{}, ErrIdentity } raw, err = call("2", "account/read", map[string]bool{"refreshToken": refresh}) if err != nil { return Identity{}, err } if refresh { var status struct { Account json.RawMessage `json:"account"` } if json.Unmarshal(raw, &status) == nil && string(status.Account) == "null" { return Identity{}, ErrLoginRequired } } id, err := CodexLoginIdentity(raw) if err != nil || limits == nil { return id, err } // The rate limits: one request, its answer; notifications the // app-server sends meanwhile (a rate-limit update among them) are // passed over, a request it makes of us ends the read. if json.NewEncoder(in).Encode(map[string]any{"id": "3", "method": "account/rateLimits/read", "params": nil}) != nil { return Identity{}, ErrIdentity } for frames := 0; frames < 64; frames++ { if !scan.Scan() { return Identity{}, ErrIdentity } var r struct { Method string ID, Params, Result, Error json.RawMessage } if json.Unmarshal(scan.Bytes(), &r) != nil { return Identity{}, ErrIdentity } if len(r.ID) == 0 && r.Method != "" { continue } if string(r.ID) != `"3"` || r.Method != "" || len(r.Error) != 0 { return Identity{}, ErrIdentity } var v struct { RateLimits json.RawMessage `json:"rateLimits"` } if json.Unmarshal(r.Result, &v) != nil || len(v.RateLimits) == 0 || string(v.RateLimits) == "null" { return Identity{}, ErrIdentity } *limits = v.RateLimits return id, nil } return Identity{}, ErrIdentity } func ClaudeLoginIdentity(raw []byte) (Identity, error) { raw, err := canonical(raw) var status struct { LoggedIn bool AuthMethod, Email string } if err != nil || json.Unmarshal(raw, &status) != nil || !status.LoggedIn || status.AuthMethod != "claude.ai" || status.Email == "" { return Identity{}, ErrIdentity } return Identity{AccountID: status.Email, ProviderVersion: LoginVersion("claude")}, nil } func CodexLoginIdentity(raw []byte) (Identity, error) { raw, err := canonical(raw) var v struct{ Account *struct{ Type, Email string } } if err != nil || json.Unmarshal(raw, &v) != nil || v.Account == nil || v.Account.Type != "chatgpt" || v.Account.Email == "" { return Identity{}, ErrIdentity } return Identity{AccountID: v.Account.Email, ProviderVersion: LoginVersion("codex")}, nil } func refreshRevoked(raw []byte) bool { var reply struct{ Message string } if json.Unmarshal(raw, &reply) != nil { return false } 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"} { if strings.Contains(reply.Message, reason) { return true } } return false } // ReadClaudeStatus returns the subscription reported by auth status separately // from identity: a plan change must never invalidate a connection's identity. func ReadClaudeStatus(ctx context.Context, b Binding, options LoginOptions) (Identity, string, error) { if b.Provider != "claude" || b.Token { return Identity{}, "", ErrPolicy } var plan string id, err := (&terminalLoginDriver{options: options}).probeReading(ctx, b, true, nil, &plan) return id, plan, err }