| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 11 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 12 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 13 | "amadan.net/oficina/equipo/internal/sealbox" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "golang.org/x/sys/unix" |
| 16 | ) |
| 17 | |
| 18 | // Claude with no terminal (Paul, 2026-11-10: "Can you not run this on |
| 19 | // the server and get a link to give to the browser? We're trying to |
| 20 | // avoid the round-trip over SSH here."). The runner runs the unmodified |
| 21 | // `claude setup-token` itself, on a pseudo-terminal, contained like |
| 22 | // every provider launch (provider.BuildSignInPolicy: its own scratch |
| 23 | // home the only writable home, the connection's dedicated home and the |
| 24 | // runner's state not mounted, egress to Claude's sign-in and API hosts |
| 25 | // only), and shows the authorize URL it prints (wire.PromptAuthorize). The person signs in at Anthropic |
| 26 | // and pastes the one-time code it shows; the page seals the code to this |
| 27 | // runner (wire.EndpointClaudeCode, the prompt's attempt) and the instance |
| 28 | // relays the box as it relays a token. The runner opens it, records the |
| 29 | // box as seen, and types the code into the waiting CLI, which prints the |
| 30 | // long-lived token. The token is kept as a pasted one is (keep: the 0600 |
| 31 | // token file, committed with the attempt turned kind token), then |
| 32 | // madeToken probes it, binds it and checks it with one real request; the |
| 33 | // connection is healthy only then. The code and the token are never |
| 34 | // written to a log, an error, a report, a frame or argv, and the code is |
| 35 | // never written to disk. |
| 36 | // |
| 37 | // A wrong code is said on the card: the CLI is asked again when it asks |
| 38 | // again (the same link), else it is started again and the card shows the |
| 39 | // new link. The CLI exiting on its own before a code starts it again too. |
| 40 | // Cancel, the attempt's time limit and a refused box stop the CLI and its |
| 41 | // process group and remove the home as every unfinished attempt does. |
| 42 | |
| 43 | // maxLaunches bounds the CLI's runs in one attempt. |
| 44 | const maxLaunches = 4 |
| 45 | |
| 46 | // codeWait is a sign-in attempt waiting for the code of its attempt |
| 47 | // number; a box that cannot be taken ends it with refuse. |
| 48 | type codeWait struct { |
| 49 | attempt int64 |
| 50 | ch chan codeIn |
| 51 | } |
| 52 | |
| 53 | type codeIn struct { |
| 54 | code []byte |
| 55 | refuse string |
| 56 | } |
| 57 | |
| 58 | // expectCode registers the attempt as waiting for attempt's code. |
| 59 | func (c *Connector) expectCode(id string, attempt int64) chan codeIn { |
| 60 | c.mu.Lock() |
| 61 | defer c.mu.Unlock() |
| 62 | w := &codeWait{attempt: attempt, ch: make(chan codeIn, 1)} |
| 63 | c.codes[id] = w |
| 64 | return w.ch |
| 65 | } |
| 66 | |
| 67 | // stopCode ends the wait; a code handed over and not taken is zeroed. |
| 68 | func (c *Connector) stopCode(id string, ch chan codeIn) { |
| 69 | c.mu.Lock() |
| 70 | if w := c.codes[id]; w != nil && w.ch == ch { |
| 71 | delete(c.codes, id) |
| 72 | } |
| 73 | c.mu.Unlock() |
| 74 | select { |
| 75 | case in := <-ch: |
| 76 | clear(in.code) |
| 77 | default: |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // codeWaiting reports whether the attempt waits for attempt's code. |
| 82 | func (c *Connector) codeWaiting(id string, attempt int64) bool { |
| 83 | c.mu.Lock() |
| 84 | defer c.mu.Unlock() |
| 85 | w := c.codes[id] |
| 86 | return w != nil && w.attempt == attempt |
| 87 | } |
| 88 | |
| 89 | // handCode gives the waiting attempt its code (or its refusal): false |
| 90 | // when it is no longer waiting for that attempt's. |
| 91 | func (c *Connector) handCode(id string, attempt int64, in codeIn) bool { |
| 92 | c.mu.Lock() |
| 93 | defer c.mu.Unlock() |
| 94 | w := c.codes[id] |
| 95 | if w == nil || w.attempt != attempt { |
| 96 | return false |
| 97 | } |
| 98 | delete(c.codes, id) |
| 99 | w.ch <- in |
| 100 | return true |
| 101 | } |
| 102 | |
| 103 | // runSignIn is a sign-in attempt: the home, the CLI and its link, the |
| 104 | // code, then the token kept and carried on as a token attempt. |
| 105 | func (c *Connector) runSignIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { |
| 106 | home, err := c.tokenHome(ctx, cmd.Connection) |
| 107 | if err != nil { |
| 108 | c.log("connect home", err) |
| 109 | c.failToken(cmd, base, home, "provider_refused") |
| 110 | return |
| 111 | } |
| 112 | lock, err := os.Open(home) |
| 113 | if err == nil { |
| 114 | err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) |
| 115 | } |
| 116 | if err != nil { |
| 117 | if lock != nil { |
| 118 | lock.Close() |
| 119 | } |
| 120 | c.failToken(cmd, base, home, "provider_refused") |
| 121 | return |
| 122 | } |
| 123 | token, reason, err := c.signIn(ctx, cmd, base, home) |
| 124 | lock.Close() |
| 125 | if errors.Is(err, errKeychain) { |
| 126 | // A Mac's sign-in left a Keychain item: refused, and the Mac holds |
| 127 | // a credential until it is gone (maccreds.go). |
| 128 | c.log("connect sign-in", err) |
| 129 | c.failToken(cmd, base, home, firstNonEmpty(reason, "provider_refused")) |
| 130 | return |
| 131 | } |
| 132 | if err != nil { |
| 133 | // Its CLI could not be proven gone: the home stays, and the |
| 134 | // attempt runs on until the next start's recovery proves it. |
| 135 | c.log("connect sign-in", err) |
| 136 | return |
| 137 | } |
| 138 | if token == nil { |
| 139 | // "": a test fault stopped it; "ended" is the test's stop of a |
| 140 | // process whose CLI died with it, before anything is cleaned. |
| 141 | if reason != "" && c.stop("ended") == nil { |
| 142 | c.failToken(cmd, base, home, reason) |
| 143 | } |
| 144 | return |
| 145 | } |
| 146 | cmd.Kind = wire.KindToken |
| 147 | c.delivery.Lock() |
| 148 | dir, err := pinHome(home) |
| 149 | if err == nil { |
| 150 | err = c.keep(ctx, cmd.Connection, wire.KindToken, dir, token, func(*sql.Tx) error { return nil }) |
| 151 | dir.Close() |
| 152 | } |
| 153 | c.delivery.Unlock() |
| 154 | clear(token) |
| 155 | if errors.Is(err, errStopped) { |
| 156 | return |
| 157 | } |
| 158 | if err != nil { |
| 159 | reason = "provider_refused" |
| 160 | if errors.Is(err, errNotWaiting) || ctx.Err() != nil { |
| 161 | reason = reasonOf(firstErr(ctx.Err(), context.Canceled)) |
| 162 | } |
| 163 | c.log("connect sign-in", err) |
| 164 | c.failToken(cmd, base, home, reason) |
| 165 | return |
| 166 | } |
| 167 | a, _, err := c.attempt(ctx, cmd.Connection) |
| 168 | if err != nil { |
| 169 | c.failToken(cmd, base, home, "provider_refused") |
| 170 | return |
| 171 | } |
| 172 | c.madeToken(ctx, cmd, base, home, a) |
| 173 | } |
| 174 | |
| 175 | // errUnproven: the CLI's launch boundary could not be proven gone. |
| 176 | var errUnproven = errors.New("the sign-in's namespace could not be proven gone") |
| 177 | |
| 178 | // signIn runs the CLI until it prints a token: the token (the caller |
| 179 | // clears it), or nil and the reason the attempt ends ("" when a test |
| 180 | // fault stopped it as if the process had). Every run of the CLI is |
| 181 | // stopped, its whole launch boundary proven gone, before this returns; |
| 182 | // errUnproven when it cannot be (the attempt is then left for the next |
| 183 | // start's recovery, home and all). |
| 184 | func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, home string) ([]byte, string, error) { |
| 185 | var attempt int64 |
| 186 | wrong, reason := false, "provider_refused" |
| 187 | start := c.terminal |
| 188 | switch { |
| 189 | case start != nil: |
| 190 | case c.Mac != nil: |
| 191 | start = c.macSetupToken |
| 192 | default: |
| 193 | start = c.containedSetupToken |
| 194 | } |
| 195 | for launch := 0; launch < maxLaunches; launch++ { |
| 196 | term, err := start(ctx, cmd.Connection) |
| 197 | if err != nil { |
| 198 | c.log("connect sign-in", err) |
| 199 | if ctx.Err() != nil { |
| 200 | return nil, reasonOf(ctx.Err()), nil |
| 201 | } |
| 202 | return nil, "provider_refused", nil |
| 203 | } |
| 204 | cli := connect.NewSetupToken(term) |
| 205 | stop := func() error { |
| 206 | if err := cli.Close(); err != nil { |
| 207 | c.log("connect sign-in stop", err) |
| 208 | if errors.Is(err, errKeychain) { |
| 209 | return errKeychain |
| 210 | } |
| 211 | return errUnproven |
| 212 | } |
| 213 | return nil |
| 214 | } |
| 215 | link, err := cli.URL(ctx) |
| 216 | if err != nil { |
| 217 | if serr := stop(); serr != nil { |
| 218 | return nil, "", serr |
| 219 | } |
| 220 | if ctx.Err() != nil { |
| 221 | return nil, reasonOf(ctx.Err()), nil |
| 222 | } |
| 223 | // Exited before a link: nothing to show, nothing to retry. |
| 224 | return nil, "provider_refused", nil |
| 225 | } |
| 226 | for cli != nil { |
| 227 | if attempt++; attempt > wire.MaxCodeAttempts { |
| 228 | return nil, "provider_refused", stop() |
| 229 | } |
| 230 | codes := c.expectCode(cmd.Connection, attempt) |
| 231 | r := base |
| 232 | r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: link, Attempt: attempt, WrongCode: wrong} |
| 233 | c.report(r) |
| 234 | var in codeIn |
| 235 | select { |
| 236 | case <-ctx.Done(): |
| 237 | c.stopCode(cmd.Connection, codes) |
| 238 | return nil, reasonOf(ctx.Err()), stop() |
| 239 | case <-term.Done(): |
| 240 | // It stopped waiting on its own (its own time limit): a new |
| 241 | // run, a new link. |
| 242 | c.stopCode(cmd.Connection, codes) |
| 243 | if err := stop(); err != nil { |
| 244 | return nil, "", err |
| 245 | } |
| 246 | cli, wrong, reason = nil, false, "timed_out" |
| 247 | continue |
| 248 | case in = <-codes: |
| 249 | } |
| 250 | c.stopCode(cmd.Connection, codes) |
| 251 | if in.refuse != "" { |
| 252 | return nil, in.refuse, stop() |
| 253 | } |
| 254 | err = cli.Submit(ctx, in.code) |
| 255 | clear(in.code) |
| 256 | if err == nil && c.stop("code_typed") != nil { |
| 257 | // As if the process stopped here: the CLI dies with it. |
| 258 | _ = stop() |
| 259 | return nil, "", nil |
| 260 | } |
| 261 | outcome, token := connect.CodeEnded, []byte(nil) |
| 262 | if err == nil { |
| 263 | outcome, token, err = cli.Result(ctx) |
| 264 | } |
| 265 | if ctx.Err() != nil { |
| 266 | clear(token) |
| 267 | return nil, reasonOf(ctx.Err()), stop() |
| 268 | } |
| 269 | switch { |
| 270 | case err == nil && outcome == connect.CodeToken: |
| 271 | if serr := stop(); serr != nil { |
| 272 | clear(token) |
| 273 | return nil, "", serr |
| 274 | } |
| 275 | if !provider.ValidToken(token) { |
| 276 | clear(token) |
| 277 | return nil, "provider_refused", nil |
| 278 | } |
| 279 | return token, "", nil |
| 280 | case err == nil && outcome == connect.CodeAgain: |
| 281 | // It asks again: the link it shows now (the same, or a new |
| 282 | // sign-in's), a new code. |
| 283 | wrong, link = true, cli.Link() |
| 284 | default: |
| 285 | // It stopped: a new run, a new link. The code was wrong |
| 286 | // unless it never took it. |
| 287 | if serr := stop(); serr != nil { |
| 288 | return nil, "", serr |
| 289 | } |
| 290 | cli, wrong, reason = nil, err == nil, "provider_refused" |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | return nil, reason, nil |
| 295 | } |
| 296 | |
| 297 | // containedSetupToken starts the attempt's setup-token in its own |
| 298 | // namespace (provider.BuildSignInPolicy) on a terminal. The namespace's |
| 299 | // record is kept in the attempt before anything is forked, so a start |
| 300 | // after a crash finds it (namespaceGone). |
| 301 | func (c *Connector) containedSetupToken(ctx context.Context, attempt string) (connect.Terminal, error) { |
| 302 | if c.Manager == nil { |
| 303 | return nil, provider.ErrLoginUnavailable |
| 304 | } |
| 305 | policy, err := provider.BuildSignInPolicy(provider.SignInPolicyInputs{Binary: c.Runner.ClaudePath, Bwrap: c.Runner.Bwrap()}) |
| 306 | if err != nil { |
| 307 | return nil, err |
| 308 | } |
| 309 | launch := provider.Launch{AttemptKey: "signin/" + attempt + "/" + uuid(), Selection: provider.Selection{Provider: wire.ProviderClaude}, Policy: policy} |
| 310 | record := func(ctx context.Context, r containment.Record) error { |
| 311 | _, err := c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET namespace=? WHERE id=?", r.ID, attempt) |
| 312 | return err |
| 313 | } |
| 314 | // The namespace lives until Stop, whatever ctx does. |
| 315 | pctx, kill := context.WithCancel(context.Background()) |
| 316 | proc, err := c.Manager.StartTerminal(pctx, launch, append([]string(nil), provider.SignInArgv...), record) |
| 317 | if err != nil { |
| 318 | kill() |
| 319 | return nil, err |
| 320 | } |
| 321 | t := &contained{proc: proc, kill: kill, done: make(chan struct{}), c: c} |
| 322 | go func() { |
| 323 | _, _ = proc.Wait(context.Background()) |
| 324 | close(t.done) |
| 325 | }() |
| 326 | return t, nil |
| 327 | } |
| 328 | |
| 329 | // contained is a sign-in's terminal in its namespace. |
| 330 | type contained struct { |
| 331 | proc provider.Process |
| 332 | kill context.CancelFunc |
| 333 | done chan struct{} |
| 334 | c *Connector |
| 335 | } |
| 336 | |
| 337 | func (t *contained) Read(p []byte) (int, error) { return t.proc.Stdout().Read(p) } |
| 338 | func (t *contained) Write(p []byte) (int, error) { return t.proc.Stdin().Write(p) } |
| 339 | func (t *contained) Done() <-chan struct{} { return t.done } |
| 340 | |
| 341 | // Stop kills the namespace (every process in it, the CLI's children |
| 342 | // whether or not the CLI is still running) and waits for its exit to be |
| 343 | // proven; then its record and scratch go. |
| 344 | func (t *contained) Stop() error { |
| 345 | t.kill() |
| 346 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 347 | defer cancel() |
| 348 | var err error |
| 349 | if p, ok := t.proc.(interface{ Contain(context.Context) error }); ok { |
| 350 | err = p.Contain(ctx) |
| 351 | } else { |
| 352 | _, err = t.proc.Wait(ctx) |
| 353 | } |
| 354 | t.proc.Stdin().Close() |
| 355 | t.proc.Stdout().Close() |
| 356 | if err != nil { |
| 357 | return err |
| 358 | } |
| 359 | return t.c.namespaceGone(ctx, t.proc.ID()) |
| 360 | } |
| 361 | |
| 362 | // namespaceGone proves a sign-in's namespace gone: its record, when the |
| 363 | // manager still holds one, is recovered (the namespace killed if it |
| 364 | // survived, its exit verified) and forgotten. nil: gone. |
| 365 | func (c *Connector) namespaceGone(ctx context.Context, id string) error { |
| 366 | if c.gone != nil { |
| 367 | return c.gone(ctx, id) |
| 368 | } |
| 369 | if c.Mac != nil { |
| 370 | // A Mac's: its run's end proven (mac.Executor.Verify). |
| 371 | if c.Mac.exec.Verify(id) { |
| 372 | return nil |
| 373 | } |
| 374 | return errUnproven |
| 375 | } |
| 376 | if c.Manager == nil { |
| 377 | return errUnproven |
| 378 | } |
| 379 | records, err := c.Manager.Records(ctx) |
| 380 | if err != nil { |
| 381 | return err |
| 382 | } |
| 383 | for _, r := range records { |
| 384 | if r.ID == id { |
| 385 | return c.Manager.Forget(ctx, r) |
| 386 | } |
| 387 | } |
| 388 | return nil |
| 389 | } |
| 390 | |
| 391 | // code takes a sealed sign-in code for a sign-in attempt (Secret, spec |
| 392 | // §2.4's steps for a secret that is never stored): (i) received; (ii) |
| 393 | // opened and checked: this runner, this connection and person, Claude, |
| 394 | // the code endpoint, the attempt number the CLI waits for, the shape of |
| 395 | // a code; (iii) committed: one transaction records (connection, attempt, |
| 396 | // frame) in seen_seals while the attempt is running and not cancelled; |
| 397 | // (iv) handed to the attempt, which types it; acked once this returns |
| 398 | // nil. A box for an attempt number the CLI no longer waits for (a new |
| 399 | // link came first) is dropped; a box that does not open or is expired |
| 400 | // ends the attempt with a reason, as a token's does. |
| 401 | func (c *Connector) code(ctx context.Context, frameID string, cmd wire.SecretCommand, a tokenAttempt) error { |
| 402 | s := cmd.Sealed |
| 403 | if a.state != "running" || a.cancelled || !c.codeWaiting(a.id, s.Attempt) { |
| 404 | c.refused("not_waiting") |
| 405 | return nil |
| 406 | } |
| 407 | refuse := func(reason string) error { |
| 408 | c.refused(reason) |
| 409 | if !c.handCode(a.id, s.Attempt, codeIn{refuse: reason}) { |
| 410 | c.refused("not_waiting") |
| 411 | } |
| 412 | return nil |
| 413 | } |
| 414 | if c.Seal == nil { |
| 415 | return refuse("provider_refused") |
| 416 | } |
| 417 | p, err := c.Seal.Open(s, time.Now()) |
| 418 | if errors.Is(err, sealbox.ErrExpired) { |
| 419 | return refuse("timed_out") |
| 420 | } |
| 421 | if err != nil { |
| 422 | return refuse("provider_refused") |
| 423 | } |
| 424 | secret := []byte(p.Secret) |
| 425 | p.Secret = "" |
| 426 | defer clear(secret) |
| 427 | if p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != wire.ProviderClaude || p.Endpoint != wire.EndpointClaudeCode || p.Attempt != s.Attempt || !provider.ValidCode(secret) { |
| 428 | return refuse("provider_refused") |
| 429 | } |
| 430 | if err = c.stop("code_opened"); err != nil { |
| 431 | return err |
| 432 | } |
| 433 | err = c.State.tx(ctx, func(t *sql.Tx) error { |
| 434 | res, err := t.Exec("UPDATE connect_attempts SET state=state WHERE id=? AND state='running' AND cancelled=0", a.id) |
| 435 | if err != nil { |
| 436 | return err |
| 437 | } |
| 438 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 439 | return firstErr(err, errNotWaiting) |
| 440 | } |
| 441 | if _, err = t.Exec("INSERT INTO seen_seals(connection_id, attempt, frame_id, created_at) VALUES(?,?,?,?)", s.ConnectionID, s.Attempt, frameID, now()); err != nil { |
| 442 | return err |
| 443 | } |
| 444 | _, err = t.Exec("DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)) |
| 445 | return err |
| 446 | }) |
| 447 | if errors.Is(err, errNotWaiting) { |
| 448 | c.refused("not_waiting") |
| 449 | return nil |
| 450 | } |
| 451 | if err != nil { |
| 452 | return err |
| 453 | } |
| 454 | if err = c.stop("code_committed"); err != nil { |
| 455 | return err |
| 456 | } |
| 457 | given := append([]byte(nil), secret...) |
| 458 | if !c.handCode(a.id, s.Attempt, codeIn{code: given}) { |
| 459 | clear(given) |
| 460 | c.refused("not_waiting") |
| 461 | } |
| 462 | return nil |
| 463 | } |
| 464 | |