| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "slices" |
| 14 | "sync" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/runner" |
| 18 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 19 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 20 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 21 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 22 | runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| 23 | "amadan.net/oficina/equipo/internal/sealbox" |
| 24 | "amadan.net/oficina/equipo/internal/wire" |
| 25 | "golang.org/x/sys/unix" |
| 26 | ) |
| 27 | |
| 28 | const connectSchema = ` |
| 29 | CREATE TABLE IF NOT EXISTS connect_attempts (id TEXT PRIMARY KEY, person TEXT NOT NULL, provider TEXT NOT NULL, same_machine INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL, home TEXT NOT NULL DEFAULT '', local_id TEXT NOT NULL DEFAULT '', cancelled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); |
| 30 | CREATE TABLE IF NOT EXISTS connect_cleanups (connection TEXT PRIMARY KEY, person TEXT NOT NULL, local_id TEXT NOT NULL, report INTEGER NOT NULL, created_at TEXT NOT NULL); |
| 31 | CREATE TABLE IF NOT EXISTS seen_seals (connection_id TEXT NOT NULL, attempt INTEGER NOT NULL, frame_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (connection_id, attempt)); |
| 32 | ` |
| 33 | |
| 34 | // ConnectLimit ends an attempt the person did not finish (spec §2.1: ten |
| 35 | // minutes with no progress; the Codex device code itself lasts fifteen). |
| 36 | const ConnectLimit = 10 * time.Minute |
| 37 | |
| 38 | // Connector adds connections from the app (spec §2): a Codex account by |
| 39 | // device code, a Claude account by the runner's own `claude setup-token` |
| 40 | // with the sign-in code relayed sealed (signin.go), or from a pasted |
| 41 | // token (token.go). |
| 42 | // The provider's own CLI signs in, in a new dedicated home; the instance |
| 43 | // only ever sees the provider's display code or sign-in page, the |
| 44 | // account's email and boxes it cannot open. |
| 45 | type Connector struct { |
| 46 | Runner runner.Config |
| 47 | State *State |
| 48 | Conns *Conns |
| 49 | // Root holds the dedicated homes (DefaultAccountsRoot). |
| 50 | Root string |
| 51 | Owners []string |
| 52 | Notify func() |
| 53 | Logger *slog.Logger |
| 54 | // Limit bounds an attempt (default ConnectLimit). |
| 55 | Limit time.Duration |
| 56 | |
| 57 | // Seal opens secrets sealed to this runner (nil: it accepts none); |
| 58 | // RunnerID is the id they must be sealed for. |
| 59 | Seal *sealbox.Keys |
| 60 | RunnerID string |
| 61 | // Manager contains a sign-in's `claude setup-token` (nil: Claude's |
| 62 | // sign-in by a link is unavailable). |
| 63 | Manager *containment.Manager |
| 64 | // Mac is a Mac worker's credential operations (maccreds.go): its |
| 65 | // guards before a token is stored or used, its darwin sign-in and |
| 66 | // auth status, nil on Linux. |
| 67 | Mac *macCreds |
| 68 | |
| 69 | // terminal starts setup-token for an attempt (contained, signin.go; |
| 70 | // tests replace it); gone proves an attempt's namespace gone at |
| 71 | // start (namespaceGone; tests replace it). |
| 72 | terminal func(ctx context.Context, attempt string) (connect.Terminal, error) |
| 73 | gone func(ctx context.Context, id string) error |
| 74 | |
| 75 | // spawn runs a cleanup in the background (a goroutine; tests replace |
| 76 | // it to stop the process between a frame and its cleanup). |
| 77 | spawn func(func()) |
| 78 | // fault, in tests, stops a secret's delivery at a boundary ("staged", |
| 79 | // "transaction", "committed"), a token attempt after its binding is |
| 80 | // saved ("bound") or after a sign-out it owes is recorded ("owed"), |
| 81 | // as if the process stopped there. |
| 82 | fault func(stage string) error |
| 83 | |
| 84 | mu sync.Mutex |
| 85 | attempts map[string]context.CancelFunc |
| 86 | ctx context.Context |
| 87 | // waits wakes a token attempt waiting for its secret; codes holds the |
| 88 | // sign-in attempts waiting for a code. |
| 89 | waits map[string]chan struct{} |
| 90 | codes map[string]*codeWait |
| 91 | // delivery serialises a secret's delivery with its attempt's end. |
| 92 | delivery sync.Mutex |
| 93 | |
| 94 | // http and origin, in tests, send an API-key provider's requests to |
| 95 | // a fake provider on 127.0.0.1 (apikey.go). |
| 96 | http *http.Client |
| 97 | origin func(provider string) string |
| 98 | } |
| 99 | |
| 100 | // cleanup is a sign-out the connector owes: recorded in the transaction |
| 101 | // that consumes its frame (or that finds a cancelled attempt saved), and |
| 102 | // done again at startup until it is done. |
| 103 | type cleanup struct { |
| 104 | connection, person, local string |
| 105 | report bool |
| 106 | // home and provider: the signed-in home the sign-out deletes, kept in |
| 107 | // the record from before the binding goes until the home is gone. |
| 108 | home, provider string |
| 109 | } |
| 110 | |
| 111 | func (c *Connector) background(f func()) { |
| 112 | if c.spawn != nil { |
| 113 | c.spawn(f) |
| 114 | return |
| 115 | } |
| 116 | go f() |
| 117 | } |
| 118 | |
| 119 | // owe records a cleanup in t. |
| 120 | func owe(t *sql.Tx, k cleanup) error { |
| 121 | report := 0 |
| 122 | if k.report { |
| 123 | report = 1 |
| 124 | } |
| 125 | _, err := t.Exec("INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) VALUES(?,?,?,?,?) ON CONFLICT(connection) DO NOTHING", k.connection, k.person, k.local, report, now()) |
| 126 | return err |
| 127 | } |
| 128 | |
| 129 | // settle does one cleanup and, once done, forgets it; an attempt it |
| 130 | // signed out is marked removed so its local id, reused later, is never |
| 131 | // signed out again. |
| 132 | func (c *Connector) settle(k cleanup) { |
| 133 | if !c.remove(k) { |
| 134 | return |
| 135 | } |
| 136 | _, err := c.State.db.Exec("DELETE FROM connect_cleanups WHERE connection=?", k.connection) |
| 137 | c.log("disconnect record", err) |
| 138 | _, err = c.State.db.Exec("UPDATE connect_attempts SET state='removed' WHERE id=? AND state='done'", k.connection) |
| 139 | c.log("disconnect record", err) |
| 140 | } |
| 141 | |
| 142 | func (c *Connector) log(msg string, err error) { |
| 143 | if c.Logger != nil && err != nil { |
| 144 | c.Logger.Warn(msg, "err", sanitize(err)) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Start reports attempts a previous process left unfinished (their sign-in |
| 149 | // process died with it) and removes their unfinished homes. |
| 150 | func (c *Connector) Start(ctx context.Context) error { |
| 151 | c.mu.Lock() |
| 152 | c.ctx, c.attempts, c.waits, c.codes = ctx, map[string]context.CancelFunc{}, map[string]chan struct{}{}, map[string]*codeWait{} |
| 153 | c.mu.Unlock() |
| 154 | if _, err := c.State.db.ExecContext(ctx, "DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)); err != nil { |
| 155 | return err |
| 156 | } |
| 157 | rows, err := c.State.db.QueryContext(ctx, "SELECT id, person, provider, home, kind, created_at, namespace FROM connect_attempts WHERE state='running'") |
| 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| 161 | type left struct{ id, person, provider, home, kind, created, namespace string } |
| 162 | var all []left |
| 163 | for rows.Next() { |
| 164 | var l left |
| 165 | if err = rows.Scan(&l.id, &l.person, &l.provider, &l.home, &l.kind, &l.created, &l.namespace); err != nil { |
| 166 | rows.Close() |
| 167 | return err |
| 168 | } |
| 169 | all = append(all, l) |
| 170 | } |
| 171 | rows.Close() |
| 172 | for _, l := range all { |
| 173 | // A token attempt lost no process: it recovers its delivery and |
| 174 | // waits on (or finishes) where it was. So does a sign-in attempt |
| 175 | // whose token was committed (it is kind token then); one that was |
| 176 | // not lost its CLI with the process, and ends below. |
| 177 | if l.kind == wire.KindToken || l.kind == wire.KindAPIKey { |
| 178 | if err = c.resumeToken(ctx, l.id, l.person, l.home, l.created, l.kind, l.provider); err != nil { |
| 179 | return err |
| 180 | } |
| 181 | continue |
| 182 | } |
| 183 | // A sign-in's contained CLI is proven gone (its namespace killed |
| 184 | // and its exit verified) before its home goes; one that cannot be |
| 185 | // is left running, home and all, for the next start. |
| 186 | if l.namespace != "" { |
| 187 | if err = c.namespaceGone(ctx, l.namespace); err != nil { |
| 188 | c.log("connect sign-in recovery", err) |
| 189 | continue |
| 190 | } |
| 191 | } |
| 192 | c.removeHome(l.home) |
| 193 | c.finish(l.id, wire.ConnectionReport{Connection: l.id, Person: l.person, Provider: l.provider, State: wire.ConnError, Reason: "runner_offline"}) |
| 194 | } |
| 195 | if c.Mac != nil { |
| 196 | // A Mac's Keychain watches its sign-ins left: settled once their |
| 197 | // CLIs are proven gone (maccreds.go). |
| 198 | c.Mac.settle(ctx, true) |
| 199 | } |
| 200 | // An attempt saved and then cancelled, stopped before it was signed |
| 201 | // out: owed now. Then every cleanup still owed. |
| 202 | if _, err = c.State.db.ExecContext(ctx, "INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) SELECT id, person, local_id, 0, ? FROM connect_attempts WHERE state='done' AND cancelled=1 AND local_id<>'' ON CONFLICT(connection) DO NOTHING", now()); err != nil { |
| 203 | return err |
| 204 | } |
| 205 | rows, err = c.State.db.QueryContext(ctx, "SELECT connection, person, local_id, report, home, provider FROM connect_cleanups ORDER BY created_at") |
| 206 | if err != nil { |
| 207 | return err |
| 208 | } |
| 209 | var owed []cleanup |
| 210 | for rows.Next() { |
| 211 | var k cleanup |
| 212 | if err = rows.Scan(&k.connection, &k.person, &k.local, &k.report, &k.home, &k.provider); err != nil { |
| 213 | rows.Close() |
| 214 | return err |
| 215 | } |
| 216 | owed = append(owed, k) |
| 217 | } |
| 218 | rows.Close() |
| 219 | for _, k := range owed { |
| 220 | c.background(func() { c.settle(k) }) |
| 221 | } |
| 222 | return nil |
| 223 | } |
| 224 | |
| 225 | // Accept records a connect command exactly once and starts the attempt. |
| 226 | func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.ConnectCommand) error { |
| 227 | fresh := false |
| 228 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 229 | var err error |
| 230 | if fresh, err = seen(t, frameID); err != nil || !fresh { |
| 231 | return err |
| 232 | } |
| 233 | same := 0 |
| 234 | if cmd.SameMachine { |
| 235 | same = 1 |
| 236 | } |
| 237 | budget := "" |
| 238 | if cmd.Budget != nil { |
| 239 | raw, _ := json.Marshal(cmd.Budget) |
| 240 | budget = string(raw) |
| 241 | } |
| 242 | _, err = t.Exec("INSERT INTO connect_attempts(id, person, provider, same_machine, state, kind, billing, budget, created_at) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", cmd.Connection, cmd.Person, cmd.Provider, same, "running", cmd.Kind, cmd.Billing, budget, now()) |
| 243 | return err |
| 244 | }) |
| 245 | if err != nil || !fresh { |
| 246 | return err |
| 247 | } |
| 248 | // A token attempt's home is made before the next frame is read, so |
| 249 | // its secret, however soon it follows, finds the attempt ready (the |
| 250 | // attempt ends if this fails). |
| 251 | _, apiKey := wire.APIKeyProviders[cmd.Provider] |
| 252 | if (cmd.Kind == wire.KindToken && cmd.Provider == wire.ProviderClaude || cmd.Kind == wire.KindAPIKey && apiKey) && slices.Contains(c.Owners, cmd.Person) && (c.Mac == nil || macTakes(cmd)) { |
| 253 | if _, herr := c.tokenHome(ctx, cmd.Connection); herr != nil { |
| 254 | c.log("connect home", herr) |
| 255 | } |
| 256 | } |
| 257 | c.mu.Lock() |
| 258 | defer c.mu.Unlock() |
| 259 | if c.ctx == nil { |
| 260 | return errors.New("connector not started") |
| 261 | } |
| 262 | limit := c.Limit |
| 263 | if limit <= 0 { |
| 264 | limit = ConnectLimit |
| 265 | } |
| 266 | actx, cancel := context.WithTimeout(c.ctx, limit) |
| 267 | c.attempts[cmd.Connection] = cancel |
| 268 | go c.run(actx, cancel, cmd) |
| 269 | return nil |
| 270 | } |
| 271 | |
| 272 | // Cancel ends an attempt the person cancelled. The cancel is recorded in |
| 273 | // the transaction that consumes the frame, so an attempt that succeeds |
| 274 | // at the same moment sees it before it saves the connection, and one |
| 275 | // already saved owes its sign-out from that same transaction. |
| 276 | func (c *Connector) Cancel(ctx context.Context, frameID string, cmd wire.CancelConnectCommand) error { |
| 277 | fresh := false |
| 278 | var owed *cleanup |
| 279 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 280 | var err error |
| 281 | if fresh, err = seen(t, frameID); err != nil || !fresh { |
| 282 | return err |
| 283 | } |
| 284 | if _, err = t.Exec("UPDATE connect_attempts SET cancelled=1 WHERE id=?", cmd.Connection); err != nil { |
| 285 | return err |
| 286 | } |
| 287 | var state, local, person string |
| 288 | err = t.QueryRow("SELECT state, local_id, person FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&state, &local, &person) |
| 289 | if errors.Is(err, sql.ErrNoRows) { |
| 290 | return nil |
| 291 | } |
| 292 | if err != nil || state != "done" || local == "" { |
| 293 | return err |
| 294 | } |
| 295 | // Ended already: a success the person cancelled does not stand |
| 296 | // (the instance dropped its report); it is signed out here. |
| 297 | owed = &cleanup{connection: cmd.Connection, person: person, local: local} |
| 298 | return owe(t, *owed) |
| 299 | }) |
| 300 | if err != nil || !fresh { |
| 301 | return err |
| 302 | } |
| 303 | c.mu.Lock() |
| 304 | cancel := c.attempts[cmd.Connection] |
| 305 | c.mu.Unlock() |
| 306 | if cancel != nil { |
| 307 | cancel() |
| 308 | } |
| 309 | if owed != nil { |
| 310 | k := *owed |
| 311 | c.background(func() { c.settle(k) }) |
| 312 | } |
| 313 | return nil |
| 314 | } |
| 315 | |
| 316 | // Check is the person's Check again, once per frame: the connection's |
| 317 | // real check runs in the background (a token's is a request that takes |
| 318 | // seconds); its outcome reaches the instance in the next hello. |
| 319 | func (c *Connector) Check(ctx context.Context, frameID string, cmd wire.CheckCommand) error { |
| 320 | fresh := false |
| 321 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 322 | var err error |
| 323 | fresh, err = seen(t, frameID) |
| 324 | return err |
| 325 | }) |
| 326 | if err != nil || !fresh { |
| 327 | return err |
| 328 | } |
| 329 | if mc, ok, err := metered.Get(ctx, c.State.db, cmd.LocalID); err != nil { |
| 330 | return err |
| 331 | } else if ok { |
| 332 | if mc.Person == cmd.Person && mc.Validated { |
| 333 | c.checkMetered(mc) |
| 334 | } |
| 335 | return nil |
| 336 | } |
| 337 | b, ok := c.Conns.Binding(cmd.LocalID) |
| 338 | if !ok || b.PersonID != cmd.Person { |
| 339 | return nil |
| 340 | } |
| 341 | c.background(func() { |
| 342 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) |
| 343 | defer cancel() |
| 344 | c.Conns.CheckAgain(ctx, b.ID) |
| 345 | if c.Notify != nil { |
| 346 | c.Notify() |
| 347 | } |
| 348 | }) |
| 349 | return nil |
| 350 | } |
| 351 | |
| 352 | // Disconnect signs a connection out (DELETE /connections/{id}). A |
| 353 | // command that names another runner (protocol 37: local ids repeat |
| 354 | // across runners) is consumed and removes nothing here. |
| 355 | func (c *Connector) Disconnect(ctx context.Context, frameID string, cmd wire.DisconnectCommand) error { |
| 356 | fresh := false |
| 357 | other := cmd.RunnerID != "" && cmd.RunnerID != c.RunnerID |
| 358 | k := cleanup{connection: cmd.Connection, person: cmd.Person, local: cmd.LocalID, report: true} |
| 359 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 360 | var err error |
| 361 | if fresh, err = seen(t, frameID); err != nil || !fresh || other { |
| 362 | return err |
| 363 | } |
| 364 | return owe(t, k) |
| 365 | }) |
| 366 | if err != nil || !fresh { |
| 367 | return err |
| 368 | } |
| 369 | if other { |
| 370 | c.log("disconnect", errors.New("a sign-out addressed to another runner; nothing removed")) |
| 371 | return nil |
| 372 | } |
| 373 | c.background(func() { c.settle(k) }) |
| 374 | return nil |
| 375 | } |
| 376 | |
| 377 | // remove signs one of the person's connections out: the home is recorded |
| 378 | // in the cleanup first; then the harness's own logout in it (tried |
| 379 | // twice), the binding dropped, the home deleted, its state forgotten; |
| 380 | // then signed_out is reported. A cleanup replayed after a stop finds the |
| 381 | // home in its record when the binding has gone already. false: something |
| 382 | // is left (the binding, or the home), and the cleanup is owed still; |
| 383 | // success is never reported while the home exists. |
| 384 | func (c *Connector) remove(k cleanup) bool { |
| 385 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 386 | defer cancel() |
| 387 | b, bound := c.Conns.Binding(k.local) |
| 388 | bound = bound && b.PersonID == k.person |
| 389 | if bound { |
| 390 | k.home, k.provider = b.ProviderHome, b.Provider |
| 391 | if _, err := c.State.db.ExecContext(ctx, "UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", k.home, k.provider, k.connection); err != nil { |
| 392 | c.log("disconnect record", err) |
| 393 | return false |
| 394 | } |
| 395 | } |
| 396 | // A metered connection has no binding: its record names its home. |
| 397 | mc, isMetered, err := metered.Get(ctx, c.State.db, k.local) |
| 398 | if err != nil { |
| 399 | c.log("disconnect metered", err) |
| 400 | return false |
| 401 | } |
| 402 | if isMetered = isMetered && mc.Person == k.person && !bound; isMetered { |
| 403 | k.home, k.provider = mc.Home, mc.Provider |
| 404 | if _, err := c.State.db.ExecContext(ctx, "UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", k.home, k.provider, k.connection); err != nil { |
| 405 | c.log("disconnect record", err) |
| 406 | return false |
| 407 | } |
| 408 | if !c.removeMetered(k) { |
| 409 | return false |
| 410 | } |
| 411 | } |
| 412 | _, apiKey := wire.APIKeyProviders[k.provider] |
| 413 | // A Mac never runs a CLI it has not pinned (spec §8.2): its token's |
| 414 | // sign-out is the home's deletion. |
| 415 | if k.home != "" && exists(k.home) && !apiKey && c.Mac == nil { |
| 416 | if lock, err := os.Open(k.home); err == nil { |
| 417 | if unix.Flock(int(lock.Fd()), unix.LOCK_EX) == nil { |
| 418 | if err := c.logout(ctx, k.provider, k.home); err != nil { |
| 419 | c.log("disconnect logout", c.logout(ctx, k.provider, k.home)) |
| 420 | } |
| 421 | } |
| 422 | lock.Close() |
| 423 | } |
| 424 | } |
| 425 | if bound { |
| 426 | if _, err := runnersetup.RemoveAccountBinding(ctx, c.Runner.AccountBindingsPath, b.ID); err != nil { |
| 427 | c.log("disconnect binding", err) |
| 428 | return false |
| 429 | } |
| 430 | c.Conns.Forget(b.ID) |
| 431 | c.Conns.forgetExpiry(b.ID) |
| 432 | c.Conns.changed() |
| 433 | } |
| 434 | if k.home != "" { |
| 435 | c.removeHome(k.home) |
| 436 | if exists(k.home) { |
| 437 | c.log("disconnect home", errors.New("the home is still there")) |
| 438 | return false |
| 439 | } |
| 440 | } |
| 441 | if k.report { |
| 442 | c.report(wire.ConnectionReport{Connection: k.connection, Person: k.person, LocalID: k.local, Provider: k.provider, State: wire.ConnSignedOut}) |
| 443 | } |
| 444 | return true |
| 445 | } |
| 446 | |
| 447 | func exists(path string) bool { |
| 448 | _, err := os.Lstat(path) |
| 449 | return err == nil |
| 450 | } |
| 451 | |
| 452 | // logout runs the provider's own sign-out in the home. |
| 453 | func (c *Connector) logout(ctx context.Context, provider_, home string) error { |
| 454 | binary, args := c.Runner.ClaudePath, []string{"auth", "logout"} |
| 455 | if provider_ == wire.ProviderCodex { |
| 456 | binary, args = c.Runner.CodexPath, []string{"logout"} |
| 457 | } |
| 458 | cmd := exec.CommandContext(ctx, binary, args...) |
| 459 | cmd.Dir, cmd.Env = home, provider.LoginEnvironment(provider_, home) |
| 460 | return cmd.Run() |
| 461 | } |
| 462 | |
| 463 | // report sends progress on an attempt (durable). |
| 464 | func (c *Connector) report(r wire.ConnectionReport) { |
| 465 | err := c.State.tx(context.Background(), func(t *sql.Tx) error { return c.State.enqueue(t, wire.FrameConnection, "", r) }) |
| 466 | c.log("connect report", err) |
| 467 | if c.Notify != nil { |
| 468 | c.Notify() |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | // finish reports an attempt's end and marks it done, in one transaction. |
| 473 | func (c *Connector) finish(id string, r wire.ConnectionReport) { |
| 474 | err := c.State.tx(context.Background(), func(t *sql.Tx) error { |
| 475 | if _, err := t.Exec("UPDATE connect_attempts SET state='done', local_id=? WHERE id=?", r.LocalID, id); err != nil { |
| 476 | return err |
| 477 | } |
| 478 | return c.State.enqueue(t, wire.FrameConnection, "", r) |
| 479 | }) |
| 480 | c.log("connect report", err) |
| 481 | if c.Notify != nil { |
| 482 | c.Notify() |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | func reasonOf(err error) string { |
| 487 | switch { |
| 488 | case errors.Is(err, connect.ErrTimedOut), errors.Is(err, context.DeadlineExceeded): |
| 489 | return "timed_out" |
| 490 | case errors.Is(err, connect.ErrCancelled), errors.Is(err, context.Canceled): |
| 491 | return "cancelled" |
| 492 | } |
| 493 | return "provider_refused" |
| 494 | } |
| 495 | |
| 496 | func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire.ConnectCommand) { |
| 497 | defer cancel() |
| 498 | defer func() { |
| 499 | c.mu.Lock() |
| 500 | delete(c.attempts, cmd.Connection) |
| 501 | c.mu.Unlock() |
| 502 | }() |
| 503 | base := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: cmd.Provider} |
| 504 | fail := func(reason string) { |
| 505 | r := base |
| 506 | r.State, r.Reason = wire.ConnError, reason |
| 507 | c.finish(cmd.Connection, r) |
| 508 | } |
| 509 | if c.Mac != nil && !macTakes(cmd) { |
| 510 | // A Mac takes Claude alone; nothing of the attempt was made. |
| 511 | fail(wire.ReasonMacClaudeOnly) |
| 512 | return |
| 513 | } |
| 514 | if cmd.Kind == wire.KindAPIKey && slices.Contains(c.Owners, cmd.Person) { |
| 515 | c.runAPIKey(ctx, cmd, base) |
| 516 | return |
| 517 | } |
| 518 | if !slices.Contains(c.Owners, cmd.Person) || cmd.Provider != wire.ProviderClaude && cmd.Provider != wire.ProviderCodex { |
| 519 | fail("provider_refused") |
| 520 | return |
| 521 | } |
| 522 | if cmd.Kind == wire.KindToken { |
| 523 | if cmd.Provider != wire.ProviderClaude { |
| 524 | fail("provider_refused") |
| 525 | return |
| 526 | } |
| 527 | c.runToken(ctx, cmd, base) |
| 528 | return |
| 529 | } |
| 530 | // Claude signs in only by the runner's own setup-token now; a frame |
| 531 | // that still says same_machine (an older instance) is the same. |
| 532 | if cmd.Provider == wire.ProviderClaude { |
| 533 | c.runSignIn(ctx, cmd, base) |
| 534 | return |
| 535 | } |
| 536 | if err := os.MkdirAll(c.Root, 0700); err != nil { |
| 537 | fail("provider_refused") |
| 538 | return |
| 539 | } |
| 540 | id, home, err := nextHome(c.Root, cmd.Provider) |
| 541 | if err == nil { |
| 542 | err = provider.CheckLoginHome(home) |
| 543 | } |
| 544 | if err != nil { |
| 545 | c.log("connect home", err) |
| 546 | if home != "" { |
| 547 | os.Remove(home) |
| 548 | } |
| 549 | fail("provider_refused") |
| 550 | return |
| 551 | } |
| 552 | _, _ = c.State.db.Exec("UPDATE connect_attempts SET home=? WHERE id=?", home, cmd.Connection) |
| 553 | lock, err := os.Open(home) |
| 554 | if err == nil { |
| 555 | err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) |
| 556 | } |
| 557 | if err != nil { |
| 558 | if lock != nil { |
| 559 | lock.Close() |
| 560 | } |
| 561 | c.removeHome(home) |
| 562 | fail("provider_refused") |
| 563 | return |
| 564 | } |
| 565 | defer lock.Close() |
| 566 | env := provider.LoginEnvironment(cmd.Provider, home) |
| 567 | acct, err := connect.CodexDeviceLogin(ctx, c.Runner.CodexPath, home, env, func(u, code string) { |
| 568 | r := base |
| 569 | r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptDeviceCode, URL: u, Code: code} |
| 570 | c.report(r) |
| 571 | }) |
| 572 | if err != nil { |
| 573 | c.log("connect sign-in", err) |
| 574 | c.removeHome(home) |
| 575 | fail(reasonOf(err)) |
| 576 | return |
| 577 | } |
| 578 | // A cancel that came while the sign-in finished wins: nothing is saved. |
| 579 | var cancelled int |
| 580 | _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&cancelled) |
| 581 | if cancelled == 1 || ctx.Err() != nil { |
| 582 | c.removeHome(home) |
| 583 | fail(reasonOf(firstErr(ctx.Err(), context.Canceled))) |
| 584 | return |
| 585 | } |
| 586 | // The same account connected twice would only split one limit. |
| 587 | observed, err := c.identify(ctx, cmd, id, home, acct.Email) |
| 588 | if err != nil { |
| 589 | c.removeHome(home) |
| 590 | if errors.Is(err, errAlreadyConnected) { |
| 591 | fail("already_connected") |
| 592 | } else { |
| 593 | c.log("connect identity", err) |
| 594 | fail("identity_mismatch") |
| 595 | } |
| 596 | return |
| 597 | } |
| 598 | if c.Conns != nil { |
| 599 | c.Conns.Forget(id) |
| 600 | if acct.Limits != nil { |
| 601 | c.Conns.Observe(id, *acct.Limits, acct.Plan) |
| 602 | } |
| 603 | c.Conns.changed() |
| 604 | } |
| 605 | r := base |
| 606 | r.State, r.LocalID, r.Label, r.Plan = wire.ConnHealthy, id, observed.AccountID, acct.Plan |
| 607 | if acct.Limits != nil { |
| 608 | r.Headroom = acct.Limits.Headroom |
| 609 | } |
| 610 | c.finish(cmd.Connection, r) |
| 611 | c.standOrGo(cmd, id, lock) |
| 612 | } |
| 613 | |
| 614 | // standOrGo ends an attempt that saved its connection: one cancelled |
| 615 | // while it was being saved does not stand. The attempt's lock on the |
| 616 | // home is let go first: the sign-out takes the same lock. |
| 617 | func (c *Connector) standOrGo(cmd wire.ConnectCommand, id string, lock *os.File) { |
| 618 | lock.Close() |
| 619 | var cancelled int |
| 620 | _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&cancelled) |
| 621 | if cancelled == 1 { |
| 622 | k := cleanup{connection: cmd.Connection, person: cmd.Person, local: id} |
| 623 | err := c.State.tx(context.Background(), func(t *sql.Tx) error { return owe(t, k) }) |
| 624 | c.log("disconnect record", err) |
| 625 | c.settle(k) |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | func firstErr(errs ...error) error { |
| 630 | for _, e := range errs { |
| 631 | if e != nil { |
| 632 | return e |
| 633 | } |
| 634 | } |
| 635 | return nil |
| 636 | } |
| 637 | |
| 638 | var errAlreadyConnected = errors.New("already connected") |
| 639 | |
| 640 | // identify records the signed-in home as a connection of the person's: |
| 641 | // the account the home holds must be the one the person just signed in |
| 642 | // (signedIn), and not one of theirs already. The home is read once; |
| 643 | // what it reported is what is saved. |
| 644 | func (c *Connector) identify(ctx context.Context, cmd wire.ConnectCommand, id, home, signedIn string) (provider.Identity, error) { |
| 645 | options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} |
| 646 | probe, ok := provider.NewLoginDriver(options).(interface { |
| 647 | Probe(context.Context, provider.Binding) (provider.Identity, error) |
| 648 | }) |
| 649 | if !ok { |
| 650 | return provider.Identity{}, provider.ErrLoginUnavailable |
| 651 | } |
| 652 | observed, err := probe.Probe(ctx, provider.Binding{ID: id, Home: home, Provider: cmd.Provider}) |
| 653 | if err != nil { |
| 654 | return observed, err |
| 655 | } |
| 656 | if signedIn == "" || observed.AccountID != signedIn { |
| 657 | return observed, provider.ErrIdentity |
| 658 | } |
| 659 | for _, b := range c.mine(cmd.Person) { |
| 660 | if b.Provider == cmd.Provider && b.AccountID == observed.AccountID { |
| 661 | return observed, errAlreadyConnected |
| 662 | } |
| 663 | } |
| 664 | return observed, saveLogin(ctx, c.Runner, cmd.Person, cmd.Provider, id, home, observed) |
| 665 | } |
| 666 | |
| 667 | func (c *Connector) mine(person string) []runner.AccountBinding { |
| 668 | bs, _ := runner.LoadBindings(c.Runner.AccountBindingsPath) |
| 669 | var out []runner.AccountBinding |
| 670 | for _, b := range bs { |
| 671 | if b.PersonID == person { |
| 672 | out = append(out, b) |
| 673 | } |
| 674 | } |
| 675 | return out |
| 676 | } |
| 677 | |
| 678 | // removeHome deletes a home this connector created that never became a |
| 679 | // connection: never one a binding names. |
| 680 | func (c *Connector) removeHome(home string) { |
| 681 | if home == "" || filepath.Dir(home) != filepath.Clean(c.Root) || c.meteredHome(home) { |
| 682 | return |
| 683 | } |
| 684 | bs, _ := runner.LoadBindings(c.Runner.AccountBindingsPath) |
| 685 | for _, b := range bs { |
| 686 | if b.ProviderHome == home { |
| 687 | return |
| 688 | } |
| 689 | } |
| 690 | c.log("connect home", os.RemoveAll(home)) |
| 691 | // The deletion (a token's file with its home) is made durable. |
| 692 | if root, err := os.Open(c.Root); err == nil { |
| 693 | c.log("connect home", root.Sync()) |
| 694 | root.Close() |
| 695 | } |
| 696 | } |
| 697 | |