package thin import ( "context" "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "errors" "io" "net/http" "strings" "time" "unicode" "unicode/utf8" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) // A token connection's account profile (2026-11-12). The pinned CLI's // `auth status` names no account for a setup token: it reads only local // config. Its own read of the account is one GET with the token, which // the token check makes too, once the provider answered its turn. In // Claude Code 2.1.312 (claude.ExecutableSHA256) that read is function dS // in the bundled module at byte 241943890, line 44 (the function at byte // 242236682): GET ${BASE_API_URL}/api/oauth/profile, BASE_API_URL // "https://api.anthropic.com", with User-Agent, Authorization "Bearer // ", Content-Type application/json and Cache-Control no-cache, no // anthropic-beta, a ten second timeout; the answer's shape (kN) is // {account: {uuid, email}, organization: {uuid}}. The runner sends the // same request but names itself: User-Agent ProfileAgent/. If // the endpoint refuses that, it is the not-available path. // // The read is made from the runner process, as an API key's model list // is (connect.SafeClient): the token from the check's lease, in memory // only; to api.anthropic.com, the one host the Claude egress route // already allows, on 443, resolved once to public addresses only, no // ambient proxy, no redirect. No new host. Nothing of it is logged but // its status and whether it named an email: never the token, the // header or the answer. // // Once at start (readProfilesAtStart), each validated token connection // with no email and no recent not-available record is read the same // way, with the token from its home, so a connection made before this // read existed gets named without a new check. // // An email is the provider's, shown as the connection's label as an // email `auth status` reports is. A 401, 403 or 404 says the profile is // not available for this sign-in: remembered, and asked again only // after ProfileRetry or with another token. Anything else records // nothing, and the next check asks again. const ( // ProfileOrigin is BASE_API_URL in the pinned CLI. ProfileOrigin = "https://api.anthropic.com" profilePath = "/api/oauth/profile" // profileLimit is the pinned CLI's own timeout for the read. profileLimit = 10 * time.Second // ProfileRetry is how long a profile read's answer stands (an email, // or the profile not available) before a check asks again. ProfileRetry = 7 * 24 * time.Hour maxProfileBytes = 64 << 10 maxProfileEmail = 254 ) const profileSchema = ` CREATE TABLE IF NOT EXISTS conn_profile (id TEXT PRIMARY KEY, email TEXT NOT NULL DEFAULT '', unavailable INTEGER NOT NULL DEFAULT 0, mark TEXT NOT NULL, read_at TEXT NOT NULL); ` // ProfileReader reads token connections' account profiles. Origin is // ProfileOrigin in a release; a test points it at a fake on 127.0.0.1 // with an HTTP client that allows loopback. A ClaudeOptions without one // reads none. type ProfileReader struct { Origin string HTTP *http.Client // Version is the runner's build version, in the User-Agent (Run // sets it from Options.Version). Version string // now, in tests, is the clock the retry interval is measured on. now func() time.Time } // AnthropicProfile is the release's reader. func AnthropicProfile() *ProfileReader { return &ProfileReader{Origin: ProfileOrigin} } func (p *ProfileReader) clock() time.Time { if p.now != nil { return p.now() } return time.Now() } // ProfileAgent is the product the profile read names in its User-Agent, // ProfileAgent/: the runner, never the Claude CLI. const ProfileAgent = "equipo-runner" // userAgent names the runner honestly: ProfileAgent/, the // version only when it is a plain token. func (p *ProfileReader) userAgent() string { v := p.Version if v == "" || len(v) > 64 || strings.ContainsFunc(v, func(r rune) bool { return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune(".-_+", r)) }) { v = "unknown" } return ProfileAgent + "/" + v } func (p *ProfileReader) client() *http.Client { if p.HTTP != nil { return p.HTTP } return connect.SafeClient(nil, nil, nil) } // read makes the one GET. status is the answer's (0: none came); email // is the account's when a 200 named a valid one. func (p *ProfileReader) read(ctx context.Context, token []byte) (int, string, error) { ctx, cancel := context.WithTimeout(ctx, profileLimit) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(p.Origin, "/")+profilePath, nil) if err != nil { return 0, "", err } req.Header.Set("User-Agent", p.userAgent()) req.Header.Set("Authorization", "Bearer "+string(token)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Cache-Control", "no-cache") res, err := p.client().Do(req) if err != nil { // Never the request or its error text (the URL only, today, but // the header holds the token): the caller logs the type. return 0, "", errProfileUnreachable } defer res.Body.Close() if res.StatusCode != http.StatusOK { return res.StatusCode, "", nil } raw, err := io.ReadAll(io.LimitReader(res.Body, maxProfileBytes+1)) if err != nil || len(raw) > maxProfileBytes { return res.StatusCode, "", errProfileAnswer } var body struct { Account struct { Email string `json:"email"` } `json:"account"` } if json.Unmarshal(raw, &body) != nil || !profileEmail(body.Account.Email) { return res.StatusCode, "", errProfileAnswer } return res.StatusCode, body.Account.Email, nil } var ( errProfileUnreachable = errors.New("the profile read got no answer") errProfileAnswer = errors.New("the profile answer could not be read") ) // profileEmail: a shape the label may show. One @ with text either side, // at most maxProfileEmail bytes, no space, control or format character. func profileEmail(s string) bool { if s == "" || len(s) > maxProfileEmail || !utf8.ValidString(s) { return false } at := strings.IndexByte(s, '@') if at <= 0 || at == len(s)-1 || strings.Count(s, "@") != 1 { return false } return !strings.ContainsFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) || unicode.Is(unicode.Cf, r) }) } // profileMark names the token a profile answer was for, so another token // on the same connection is asked about again. Not the token: a hash of // it, kept only in thin.db. func profileMark(token []byte) string { h := sha256.New() h.Write([]byte("equipo token profile\x00")) h.Write(token) return hex.EncodeToString(h.Sum(nil)[:16]) } // Profile outcomes a check records. const ( profileFound = "found" profileUnavailable = "unavailable" profileFailed = "failed" profileSkipped = "skipped" ) // readProfile is the token check's profile read for b, once the provider // answered the check's turn: when one is due (none recorded for this // token, or the last is older than ProfileRetry), one GET, its outcome // recorded. It reports whether the connection's label changed. func (o ClaudeOptions) readProfile(ctx context.Context, b runner.AccountBinding, token []byte) bool { return o.readProfileFor(ctx, b, token, false) } // readProfileFor is readProfile; atStart reads none for a connection // whose profile already named its account, however old the answer. func (o ClaudeOptions) readProfileFor(ctx context.Context, b runner.AccountBinding, token []byte, atStart bool) bool { p := o.Profile if p == nil || o.State == nil || len(token) == 0 || tokenLabel(b.AccountID) != "" { // No reader, or `auth status` named the account already. return false } mark := profileMark(token) was, due, err := o.State.profileDue(ctx, b.ID, mark, p.clock()) if err != nil || !due || atStart && was != "" { return false } status, email, err := p.read(ctx, token) outcome := profileFailed switch { case err == nil && email != "": outcome = profileFound case status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusNotFound: outcome = profileUnavailable } if o.Logger != nil { // The status and whether an email came: nothing else. args := []any{"connection", b.ID, "status", status, "email", email != "", "outcome", outcome} if err != nil { args = append(args, "err", sanitize(err)) } o.Logger.Info("token profile", args...) } if outcome == profileFailed { return false } if err = o.State.recordProfile(ctx, b.ID, mark, email, p.clock()); err != nil { if o.Logger != nil { o.Logger.Warn("token profile record", "err", sanitize(err)) } return false } return email != was } // profileDue reads the connection's recorded profile answer: its email // ("" when none), and whether a read is due for the token marked mark. func (s *State) profileDue(ctx context.Context, id, mark string, now time.Time) (string, bool, error) { var email, at, was string err := s.db.QueryRowContext(ctx, "SELECT email, mark, read_at FROM conn_profile WHERE id=?", id).Scan(&email, &was, &at) if errors.Is(err, sql.ErrNoRows) { return "", true, nil } if err != nil { return "", false, err } read, perr := time.Parse(time.RFC3339Nano, at) return email, was != mark || perr != nil || !now.Before(read.Add(ProfileRetry)), nil } // recordProfile records a profile answer for the token marked mark: the // email it named, or none (the profile not available for this sign-in). func (s *State) recordProfile(ctx context.Context, id, mark, email string, at time.Time) error { unavailable := 0 if email == "" { unavailable = 1 } _, err := s.db.ExecContext(ctx, "INSERT INTO conn_profile(id, email, unavailable, mark, read_at) VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email, unavailable=excluded.unavailable, mark=excluded.mark, read_at=excluded.read_at", id, email, unavailable, mark, at.UTC().Format(time.RFC3339Nano)) return err } // profileEmails are the emails profile reads named, by connection. func (s *State) profileEmails() map[string]string { out := map[string]string{} rows, err := s.db.Query("SELECT id, email FROM conn_profile WHERE email <> ''") if err != nil { return out } defer rows.Close() for rows.Next() { var id, email string if rows.Scan(&id, &email) == nil { out[id] = email } } return out } // profileLabel is a token connection's label: the email `auth status` // reported, else the one its profile named, else nothing. func profileLabel(b runner.AccountBinding, emails map[string]string) string { if l := tokenLabel(b.AccountID); l != "" { return l } return emails[b.ID] } // readProfilesAtStart reads, once as the runner starts, the profile of // each validated Claude token connection the CLI named no account for, // that has no email recorded and no not-available record younger than // ProfileRetry for its token. One GET each, one after another, the token // read from the connection's home and cleared after; named is called // when a label changed. Run starts it in its own goroutine: hello and // the check loop never wait for it. func (o ClaudeOptions) readProfilesAtStart(ctx context.Context, conns *Conns, named func()) { if o.Profile == nil || o.State == nil || conns == nil || conns.load(ctx) != nil { return } for _, b := range conns.bindings() { if ctx.Err() != nil { return } if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || tokenLabel(b.AccountID) != "" || conns.ValidatedAt(b.ID).IsZero() { continue } if o.Mac != nil && o.Mac.Gate() != nil { // A Mac uses a token only while its guards pass (maccreds.go). return } token, err := provider.ReadToken(b.ProviderHome) if err != nil { if o.Logger != nil { o.Logger.Info("token profile at start", "connection", b.ID, "err", sanitize(err)) } continue } changed := o.readProfileFor(ctx, b, token, true) clear(token) if changed && named != nil { named() } } }