| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "database/sql" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "strings" |
| 13 | "time" |
| 14 | "unicode" |
| 15 | "unicode/utf8" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/runner" |
| 18 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 19 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 20 | "amadan.net/oficina/equipo/internal/wire" |
| 21 | ) |
| 22 | |
| 23 | // A token connection's account profile (2026-11-12). The pinned CLI's |
| 24 | // `auth status` names no account for a setup token: it reads only local |
| 25 | // config. Its own read of the account is one GET with the token, which |
| 26 | // the token check makes too, once the provider answered its turn. In |
| 27 | // Claude Code 2.1.312 (claude.ExecutableSHA256) that read is function dS |
| 28 | // in the bundled module at byte 241943890, line 44 (the function at byte |
| 29 | // 242236682): GET ${BASE_API_URL}/api/oauth/profile, BASE_API_URL |
| 30 | // "https://api.anthropic.com", with User-Agent, Authorization "Bearer |
| 31 | // <token>", Content-Type application/json and Cache-Control no-cache, no |
| 32 | // anthropic-beta, a ten second timeout; the answer's shape (kN) is |
| 33 | // {account: {uuid, email}, organization: {uuid}}. The runner sends the |
| 34 | // same request but names itself: User-Agent ProfileAgent/<version>. If |
| 35 | // the endpoint refuses that, it is the not-available path. |
| 36 | // |
| 37 | // The read is made from the runner process, as an API key's model list |
| 38 | // is (connect.SafeClient): the token from the check's lease, in memory |
| 39 | // only; to api.anthropic.com, the one host the Claude egress route |
| 40 | // already allows, on 443, resolved once to public addresses only, no |
| 41 | // ambient proxy, no redirect. No new host. Nothing of it is logged but |
| 42 | // its status and whether it named an email: never the token, the |
| 43 | // header or the answer. |
| 44 | // |
| 45 | // Once at start (readProfilesAtStart), each validated token connection |
| 46 | // with no email and no recent not-available record is read the same |
| 47 | // way, with the token from its home, so a connection made before this |
| 48 | // read existed gets named without a new check. |
| 49 | // |
| 50 | // An email is the provider's, shown as the connection's label as an |
| 51 | // email `auth status` reports is. A 401, 403 or 404 says the profile is |
| 52 | // not available for this sign-in: remembered, and asked again only |
| 53 | // after ProfileRetry or with another token. Anything else records |
| 54 | // nothing, and the next check asks again. |
| 55 | |
| 56 | const ( |
| 57 | // ProfileOrigin is BASE_API_URL in the pinned CLI. |
| 58 | ProfileOrigin = "https://api.anthropic.com" |
| 59 | profilePath = "/api/oauth/profile" |
| 60 | // profileLimit is the pinned CLI's own timeout for the read. |
| 61 | profileLimit = 10 * time.Second |
| 62 | // ProfileRetry is how long a profile read's answer stands (an email, |
| 63 | // or the profile not available) before a check asks again. |
| 64 | ProfileRetry = 7 * 24 * time.Hour |
| 65 | maxProfileBytes = 64 << 10 |
| 66 | maxProfileEmail = 254 |
| 67 | ) |
| 68 | |
| 69 | const profileSchema = ` |
| 70 | 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); |
| 71 | ` |
| 72 | |
| 73 | // ProfileReader reads token connections' account profiles. Origin is |
| 74 | // ProfileOrigin in a release; a test points it at a fake on 127.0.0.1 |
| 75 | // with an HTTP client that allows loopback. A ClaudeOptions without one |
| 76 | // reads none. |
| 77 | type ProfileReader struct { |
| 78 | Origin string |
| 79 | HTTP *http.Client |
| 80 | // Version is the runner's build version, in the User-Agent (Run |
| 81 | // sets it from Options.Version). |
| 82 | Version string |
| 83 | // now, in tests, is the clock the retry interval is measured on. |
| 84 | now func() time.Time |
| 85 | } |
| 86 | |
| 87 | // AnthropicProfile is the release's reader. |
| 88 | func AnthropicProfile() *ProfileReader { return &ProfileReader{Origin: ProfileOrigin} } |
| 89 | |
| 90 | func (p *ProfileReader) clock() time.Time { |
| 91 | if p.now != nil { |
| 92 | return p.now() |
| 93 | } |
| 94 | return time.Now() |
| 95 | } |
| 96 | |
| 97 | // ProfileAgent is the product the profile read names in its User-Agent, |
| 98 | // ProfileAgent/<version>: the runner, never the Claude CLI. |
| 99 | const ProfileAgent = "equipo-runner" |
| 100 | |
| 101 | // userAgent names the runner honestly: ProfileAgent/<version>, the |
| 102 | // version only when it is a plain token. |
| 103 | func (p *ProfileReader) userAgent() string { |
| 104 | v := p.Version |
| 105 | if v == "" || len(v) > 64 || strings.ContainsFunc(v, func(r rune) bool { |
| 106 | return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune(".-_+", r)) |
| 107 | }) { |
| 108 | v = "unknown" |
| 109 | } |
| 110 | return ProfileAgent + "/" + v |
| 111 | } |
| 112 | |
| 113 | func (p *ProfileReader) client() *http.Client { |
| 114 | if p.HTTP != nil { |
| 115 | return p.HTTP |
| 116 | } |
| 117 | return connect.SafeClient(nil, nil, nil) |
| 118 | } |
| 119 | |
| 120 | // read makes the one GET. status is the answer's (0: none came); email |
| 121 | // is the account's when a 200 named a valid one. |
| 122 | func (p *ProfileReader) read(ctx context.Context, token []byte) (int, string, error) { |
| 123 | ctx, cancel := context.WithTimeout(ctx, profileLimit) |
| 124 | defer cancel() |
| 125 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(p.Origin, "/")+profilePath, nil) |
| 126 | if err != nil { |
| 127 | return 0, "", err |
| 128 | } |
| 129 | req.Header.Set("User-Agent", p.userAgent()) |
| 130 | req.Header.Set("Authorization", "Bearer "+string(token)) |
| 131 | req.Header.Set("Content-Type", "application/json") |
| 132 | req.Header.Set("Cache-Control", "no-cache") |
| 133 | res, err := p.client().Do(req) |
| 134 | if err != nil { |
| 135 | // Never the request or its error text (the URL only, today, but |
| 136 | // the header holds the token): the caller logs the type. |
| 137 | return 0, "", errProfileUnreachable |
| 138 | } |
| 139 | defer res.Body.Close() |
| 140 | if res.StatusCode != http.StatusOK { |
| 141 | return res.StatusCode, "", nil |
| 142 | } |
| 143 | raw, err := io.ReadAll(io.LimitReader(res.Body, maxProfileBytes+1)) |
| 144 | if err != nil || len(raw) > maxProfileBytes { |
| 145 | return res.StatusCode, "", errProfileAnswer |
| 146 | } |
| 147 | var body struct { |
| 148 | Account struct { |
| 149 | Email string `json:"email"` |
| 150 | } `json:"account"` |
| 151 | } |
| 152 | if json.Unmarshal(raw, &body) != nil || !profileEmail(body.Account.Email) { |
| 153 | return res.StatusCode, "", errProfileAnswer |
| 154 | } |
| 155 | return res.StatusCode, body.Account.Email, nil |
| 156 | } |
| 157 | |
| 158 | var ( |
| 159 | errProfileUnreachable = errors.New("the profile read got no answer") |
| 160 | errProfileAnswer = errors.New("the profile answer could not be read") |
| 161 | ) |
| 162 | |
| 163 | // profileEmail: a shape the label may show. One @ with text either side, |
| 164 | // at most maxProfileEmail bytes, no space, control or format character. |
| 165 | func profileEmail(s string) bool { |
| 166 | if s == "" || len(s) > maxProfileEmail || !utf8.ValidString(s) { |
| 167 | return false |
| 168 | } |
| 169 | at := strings.IndexByte(s, '@') |
| 170 | if at <= 0 || at == len(s)-1 || strings.Count(s, "@") != 1 { |
| 171 | return false |
| 172 | } |
| 173 | return !strings.ContainsFunc(s, func(r rune) bool { |
| 174 | return unicode.IsSpace(r) || unicode.IsControl(r) || unicode.Is(unicode.Cf, r) |
| 175 | }) |
| 176 | } |
| 177 | |
| 178 | // profileMark names the token a profile answer was for, so another token |
| 179 | // on the same connection is asked about again. Not the token: a hash of |
| 180 | // it, kept only in thin.db. |
| 181 | func profileMark(token []byte) string { |
| 182 | h := sha256.New() |
| 183 | h.Write([]byte("equipo token profile\x00")) |
| 184 | h.Write(token) |
| 185 | return hex.EncodeToString(h.Sum(nil)[:16]) |
| 186 | } |
| 187 | |
| 188 | // Profile outcomes a check records. |
| 189 | const ( |
| 190 | profileFound = "found" |
| 191 | profileUnavailable = "unavailable" |
| 192 | profileFailed = "failed" |
| 193 | profileSkipped = "skipped" |
| 194 | ) |
| 195 | |
| 196 | // readProfile is the token check's profile read for b, once the provider |
| 197 | // answered the check's turn: when one is due (none recorded for this |
| 198 | // token, or the last is older than ProfileRetry), one GET, its outcome |
| 199 | // recorded. It reports whether the connection's label changed. |
| 200 | func (o ClaudeOptions) readProfile(ctx context.Context, b runner.AccountBinding, token []byte) bool { |
| 201 | return o.readProfileFor(ctx, b, token, false) |
| 202 | } |
| 203 | |
| 204 | // readProfileFor is readProfile; atStart reads none for a connection |
| 205 | // whose profile already named its account, however old the answer. |
| 206 | func (o ClaudeOptions) readProfileFor(ctx context.Context, b runner.AccountBinding, token []byte, atStart bool) bool { |
| 207 | p := o.Profile |
| 208 | if p == nil || o.State == nil || len(token) == 0 || tokenLabel(b.AccountID) != "" { |
| 209 | // No reader, or `auth status` named the account already. |
| 210 | return false |
| 211 | } |
| 212 | mark := profileMark(token) |
| 213 | was, due, err := o.State.profileDue(ctx, b.ID, mark, p.clock()) |
| 214 | if err != nil || !due || atStart && was != "" { |
| 215 | return false |
| 216 | } |
| 217 | status, email, err := p.read(ctx, token) |
| 218 | outcome := profileFailed |
| 219 | switch { |
| 220 | case err == nil && email != "": |
| 221 | outcome = profileFound |
| 222 | case status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusNotFound: |
| 223 | outcome = profileUnavailable |
| 224 | } |
| 225 | if o.Logger != nil { |
| 226 | // The status and whether an email came: nothing else. |
| 227 | args := []any{"connection", b.ID, "status", status, "email", email != "", "outcome", outcome} |
| 228 | if err != nil { |
| 229 | args = append(args, "err", sanitize(err)) |
| 230 | } |
| 231 | o.Logger.Info("token profile", args...) |
| 232 | } |
| 233 | if outcome == profileFailed { |
| 234 | return false |
| 235 | } |
| 236 | if err = o.State.recordProfile(ctx, b.ID, mark, email, p.clock()); err != nil { |
| 237 | if o.Logger != nil { |
| 238 | o.Logger.Warn("token profile record", "err", sanitize(err)) |
| 239 | } |
| 240 | return false |
| 241 | } |
| 242 | return email != was |
| 243 | } |
| 244 | |
| 245 | // profileDue reads the connection's recorded profile answer: its email |
| 246 | // ("" when none), and whether a read is due for the token marked mark. |
| 247 | func (s *State) profileDue(ctx context.Context, id, mark string, now time.Time) (string, bool, error) { |
| 248 | var email, at, was string |
| 249 | err := s.db.QueryRowContext(ctx, "SELECT email, mark, read_at FROM conn_profile WHERE id=?", id).Scan(&email, &was, &at) |
| 250 | if errors.Is(err, sql.ErrNoRows) { |
| 251 | return "", true, nil |
| 252 | } |
| 253 | if err != nil { |
| 254 | return "", false, err |
| 255 | } |
| 256 | read, perr := time.Parse(time.RFC3339Nano, at) |
| 257 | return email, was != mark || perr != nil || !now.Before(read.Add(ProfileRetry)), nil |
| 258 | } |
| 259 | |
| 260 | // recordProfile records a profile answer for the token marked mark: the |
| 261 | // email it named, or none (the profile not available for this sign-in). |
| 262 | func (s *State) recordProfile(ctx context.Context, id, mark, email string, at time.Time) error { |
| 263 | unavailable := 0 |
| 264 | if email == "" { |
| 265 | unavailable = 1 |
| 266 | } |
| 267 | _, 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)) |
| 268 | return err |
| 269 | } |
| 270 | |
| 271 | // profileEmails are the emails profile reads named, by connection. |
| 272 | func (s *State) profileEmails() map[string]string { |
| 273 | out := map[string]string{} |
| 274 | rows, err := s.db.Query("SELECT id, email FROM conn_profile WHERE email <> ''") |
| 275 | if err != nil { |
| 276 | return out |
| 277 | } |
| 278 | defer rows.Close() |
| 279 | for rows.Next() { |
| 280 | var id, email string |
| 281 | if rows.Scan(&id, &email) == nil { |
| 282 | out[id] = email |
| 283 | } |
| 284 | } |
| 285 | return out |
| 286 | } |
| 287 | |
| 288 | // profileLabel is a token connection's label: the email `auth status` |
| 289 | // reported, else the one its profile named, else nothing. |
| 290 | func profileLabel(b runner.AccountBinding, emails map[string]string) string { |
| 291 | if l := tokenLabel(b.AccountID); l != "" { |
| 292 | return l |
| 293 | } |
| 294 | return emails[b.ID] |
| 295 | } |
| 296 | |
| 297 | // readProfilesAtStart reads, once as the runner starts, the profile of |
| 298 | // each validated Claude token connection the CLI named no account for, |
| 299 | // that has no email recorded and no not-available record younger than |
| 300 | // ProfileRetry for its token. One GET each, one after another, the token |
| 301 | // read from the connection's home and cleared after; named is called |
| 302 | // when a label changed. Run starts it in its own goroutine: hello and |
| 303 | // the check loop never wait for it. |
| 304 | func (o ClaudeOptions) readProfilesAtStart(ctx context.Context, conns *Conns, named func()) { |
| 305 | if o.Profile == nil || o.State == nil || conns == nil || conns.load(ctx) != nil { |
| 306 | return |
| 307 | } |
| 308 | for _, b := range conns.bindings() { |
| 309 | if ctx.Err() != nil { |
| 310 | return |
| 311 | } |
| 312 | if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || tokenLabel(b.AccountID) != "" || conns.ValidatedAt(b.ID).IsZero() { |
| 313 | continue |
| 314 | } |
| 315 | if o.Mac != nil && o.Mac.Gate() != nil { |
| 316 | // A Mac uses a token only while its guards pass (maccreds.go). |
| 317 | return |
| 318 | } |
| 319 | token, err := provider.ReadToken(b.ProviderHome) |
| 320 | if err != nil { |
| 321 | if o.Logger != nil { |
| 322 | o.Logger.Info("token profile at start", "connection", b.ID, "err", sanitize(err)) |
| 323 | } |
| 324 | continue |
| 325 | } |
| 326 | changed := o.readProfileFor(ctx, b, token, true) |
| 327 | clear(token) |
| 328 | if changed && named != nil { |
| 329 | named() |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | |