package thin import ( "context" "database/sql" "errors" "os" "time" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" ) // Claude with no terminal (Paul, 2026-11-10: "Can you not run this on // the server and get a link to give to the browser? We're trying to // avoid the round-trip over SSH here."). The runner runs the unmodified // `claude setup-token` itself, on a pseudo-terminal, contained like // every provider launch (provider.BuildSignInPolicy: its own scratch // home the only writable home, the connection's dedicated home and the // runner's state not mounted, egress to Claude's sign-in and API hosts // only), and shows the authorize URL it prints (wire.PromptAuthorize). The person signs in at Anthropic // and pastes the one-time code it shows; the page seals the code to this // runner (wire.EndpointClaudeCode, the prompt's attempt) and the instance // relays the box as it relays a token. The runner opens it, records the // box as seen, and types the code into the waiting CLI, which prints the // long-lived token. The token is kept as a pasted one is (keep: the 0600 // token file, committed with the attempt turned kind token), then // madeToken probes it, binds it and checks it with one real request; the // connection is healthy only then. The code and the token are never // written to a log, an error, a report, a frame or argv, and the code is // never written to disk. // // A wrong code is said on the card: the CLI is asked again when it asks // again (the same link), else it is started again and the card shows the // new link. The CLI exiting on its own before a code starts it again too. // Cancel, the attempt's time limit and a refused box stop the CLI and its // process group and remove the home as every unfinished attempt does. // maxLaunches bounds the CLI's runs in one attempt. const maxLaunches = 4 // codeWait is a sign-in attempt waiting for the code of its attempt // number; a box that cannot be taken ends it with refuse. type codeWait struct { attempt int64 ch chan codeIn } type codeIn struct { code []byte refuse string } // expectCode registers the attempt as waiting for attempt's code. func (c *Connector) expectCode(id string, attempt int64) chan codeIn { c.mu.Lock() defer c.mu.Unlock() w := &codeWait{attempt: attempt, ch: make(chan codeIn, 1)} c.codes[id] = w return w.ch } // stopCode ends the wait; a code handed over and not taken is zeroed. func (c *Connector) stopCode(id string, ch chan codeIn) { c.mu.Lock() if w := c.codes[id]; w != nil && w.ch == ch { delete(c.codes, id) } c.mu.Unlock() select { case in := <-ch: clear(in.code) default: } } // codeWaiting reports whether the attempt waits for attempt's code. func (c *Connector) codeWaiting(id string, attempt int64) bool { c.mu.Lock() defer c.mu.Unlock() w := c.codes[id] return w != nil && w.attempt == attempt } // handCode gives the waiting attempt its code (or its refusal): false // when it is no longer waiting for that attempt's. func (c *Connector) handCode(id string, attempt int64, in codeIn) bool { c.mu.Lock() defer c.mu.Unlock() w := c.codes[id] if w == nil || w.attempt != attempt { return false } delete(c.codes, id) w.ch <- in return true } // runSignIn is a sign-in attempt: the home, the CLI and its link, the // code, then the token kept and carried on as a token attempt. func (c *Connector) runSignIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { home, err := c.tokenHome(ctx, cmd.Connection) if err != nil { c.log("connect home", err) c.failToken(cmd, base, home, "provider_refused") return } lock, err := os.Open(home) if err == nil { err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) } if err != nil { if lock != nil { lock.Close() } c.failToken(cmd, base, home, "provider_refused") return } token, reason, err := c.signIn(ctx, cmd, base, home) lock.Close() if errors.Is(err, errKeychain) { // A Mac's sign-in left a Keychain item: refused, and the Mac holds // a credential until it is gone (maccreds.go). c.log("connect sign-in", err) c.failToken(cmd, base, home, firstNonEmpty(reason, "provider_refused")) return } if err != nil { // Its CLI could not be proven gone: the home stays, and the // attempt runs on until the next start's recovery proves it. c.log("connect sign-in", err) return } if token == nil { // "": a test fault stopped it; "ended" is the test's stop of a // process whose CLI died with it, before anything is cleaned. if reason != "" && c.stop("ended") == nil { c.failToken(cmd, base, home, reason) } return } cmd.Kind = wire.KindToken c.delivery.Lock() dir, err := pinHome(home) if err == nil { err = c.keep(ctx, cmd.Connection, wire.KindToken, dir, token, func(*sql.Tx) error { return nil }) dir.Close() } c.delivery.Unlock() clear(token) if errors.Is(err, errStopped) { return } if err != nil { reason = "provider_refused" if errors.Is(err, errNotWaiting) || ctx.Err() != nil { reason = reasonOf(firstErr(ctx.Err(), context.Canceled)) } c.log("connect sign-in", err) c.failToken(cmd, base, home, reason) return } a, _, err := c.attempt(ctx, cmd.Connection) if err != nil { c.failToken(cmd, base, home, "provider_refused") return } c.madeToken(ctx, cmd, base, home, a) } // errUnproven: the CLI's launch boundary could not be proven gone. var errUnproven = errors.New("the sign-in's namespace could not be proven gone") // signIn runs the CLI until it prints a token: the token (the caller // clears it), or nil and the reason the attempt ends ("" when a test // fault stopped it as if the process had). Every run of the CLI is // stopped, its whole launch boundary proven gone, before this returns; // errUnproven when it cannot be (the attempt is then left for the next // start's recovery, home and all). func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, home string) ([]byte, string, error) { var attempt int64 wrong, reason := false, "provider_refused" start := c.terminal switch { case start != nil: case c.Mac != nil: start = c.macSetupToken default: start = c.containedSetupToken } for launch := 0; launch < maxLaunches; launch++ { term, err := start(ctx, cmd.Connection) if err != nil { c.log("connect sign-in", err) if ctx.Err() != nil { return nil, reasonOf(ctx.Err()), nil } return nil, "provider_refused", nil } cli := connect.NewSetupToken(term) stop := func() error { if err := cli.Close(); err != nil { c.log("connect sign-in stop", err) if errors.Is(err, errKeychain) { return errKeychain } return errUnproven } return nil } link, err := cli.URL(ctx) if err != nil { if serr := stop(); serr != nil { return nil, "", serr } if ctx.Err() != nil { return nil, reasonOf(ctx.Err()), nil } // Exited before a link: nothing to show, nothing to retry. return nil, "provider_refused", nil } for cli != nil { if attempt++; attempt > wire.MaxCodeAttempts { return nil, "provider_refused", stop() } codes := c.expectCode(cmd.Connection, attempt) r := base r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: link, Attempt: attempt, WrongCode: wrong} c.report(r) var in codeIn select { case <-ctx.Done(): c.stopCode(cmd.Connection, codes) return nil, reasonOf(ctx.Err()), stop() case <-term.Done(): // It stopped waiting on its own (its own time limit): a new // run, a new link. c.stopCode(cmd.Connection, codes) if err := stop(); err != nil { return nil, "", err } cli, wrong, reason = nil, false, "timed_out" continue case in = <-codes: } c.stopCode(cmd.Connection, codes) if in.refuse != "" { return nil, in.refuse, stop() } err = cli.Submit(ctx, in.code) clear(in.code) if err == nil && c.stop("code_typed") != nil { // As if the process stopped here: the CLI dies with it. _ = stop() return nil, "", nil } outcome, token := connect.CodeEnded, []byte(nil) if err == nil { outcome, token, err = cli.Result(ctx) } if ctx.Err() != nil { clear(token) return nil, reasonOf(ctx.Err()), stop() } switch { case err == nil && outcome == connect.CodeToken: if serr := stop(); serr != nil { clear(token) return nil, "", serr } if !provider.ValidToken(token) { clear(token) return nil, "provider_refused", nil } return token, "", nil case err == nil && outcome == connect.CodeAgain: // It asks again: the link it shows now (the same, or a new // sign-in's), a new code. wrong, link = true, cli.Link() default: // It stopped: a new run, a new link. The code was wrong // unless it never took it. if serr := stop(); serr != nil { return nil, "", serr } cli, wrong, reason = nil, err == nil, "provider_refused" } } } return nil, reason, nil } // containedSetupToken starts the attempt's setup-token in its own // namespace (provider.BuildSignInPolicy) on a terminal. The namespace's // record is kept in the attempt before anything is forked, so a start // after a crash finds it (namespaceGone). func (c *Connector) containedSetupToken(ctx context.Context, attempt string) (connect.Terminal, error) { if c.Manager == nil { return nil, provider.ErrLoginUnavailable } policy, err := provider.BuildSignInPolicy(provider.SignInPolicyInputs{Binary: c.Runner.ClaudePath, Bwrap: c.Runner.Bwrap()}) if err != nil { return nil, err } launch := provider.Launch{AttemptKey: "signin/" + attempt + "/" + uuid(), Selection: provider.Selection{Provider: wire.ProviderClaude}, Policy: policy} record := func(ctx context.Context, r containment.Record) error { _, err := c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET namespace=? WHERE id=?", r.ID, attempt) return err } // The namespace lives until Stop, whatever ctx does. pctx, kill := context.WithCancel(context.Background()) proc, err := c.Manager.StartTerminal(pctx, launch, append([]string(nil), provider.SignInArgv...), record) if err != nil { kill() return nil, err } t := &contained{proc: proc, kill: kill, done: make(chan struct{}), c: c} go func() { _, _ = proc.Wait(context.Background()) close(t.done) }() return t, nil } // contained is a sign-in's terminal in its namespace. type contained struct { proc provider.Process kill context.CancelFunc done chan struct{} c *Connector } func (t *contained) Read(p []byte) (int, error) { return t.proc.Stdout().Read(p) } func (t *contained) Write(p []byte) (int, error) { return t.proc.Stdin().Write(p) } func (t *contained) Done() <-chan struct{} { return t.done } // Stop kills the namespace (every process in it, the CLI's children // whether or not the CLI is still running) and waits for its exit to be // proven; then its record and scratch go. func (t *contained) Stop() error { t.kill() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() var err error if p, ok := t.proc.(interface{ Contain(context.Context) error }); ok { err = p.Contain(ctx) } else { _, err = t.proc.Wait(ctx) } t.proc.Stdin().Close() t.proc.Stdout().Close() if err != nil { return err } return t.c.namespaceGone(ctx, t.proc.ID()) } // namespaceGone proves a sign-in's namespace gone: its record, when the // manager still holds one, is recovered (the namespace killed if it // survived, its exit verified) and forgotten. nil: gone. func (c *Connector) namespaceGone(ctx context.Context, id string) error { if c.gone != nil { return c.gone(ctx, id) } if c.Mac != nil { // A Mac's: its run's end proven (mac.Executor.Verify). if c.Mac.exec.Verify(id) { return nil } return errUnproven } if c.Manager == nil { return errUnproven } records, err := c.Manager.Records(ctx) if err != nil { return err } for _, r := range records { if r.ID == id { return c.Manager.Forget(ctx, r) } } return nil } // code takes a sealed sign-in code for a sign-in attempt (Secret, spec // ยง2.4's steps for a secret that is never stored): (i) received; (ii) // opened and checked: this runner, this connection and person, Claude, // the code endpoint, the attempt number the CLI waits for, the shape of // a code; (iii) committed: one transaction records (connection, attempt, // frame) in seen_seals while the attempt is running and not cancelled; // (iv) handed to the attempt, which types it; acked once this returns // nil. A box for an attempt number the CLI no longer waits for (a new // link came first) is dropped; a box that does not open or is expired // ends the attempt with a reason, as a token's does. func (c *Connector) code(ctx context.Context, frameID string, cmd wire.SecretCommand, a tokenAttempt) error { s := cmd.Sealed if a.state != "running" || a.cancelled || !c.codeWaiting(a.id, s.Attempt) { c.refused("not_waiting") return nil } refuse := func(reason string) error { c.refused(reason) if !c.handCode(a.id, s.Attempt, codeIn{refuse: reason}) { c.refused("not_waiting") } return nil } if c.Seal == nil { return refuse("provider_refused") } p, err := c.Seal.Open(s, time.Now()) if errors.Is(err, sealbox.ErrExpired) { return refuse("timed_out") } if err != nil { return refuse("provider_refused") } secret := []byte(p.Secret) p.Secret = "" defer clear(secret) 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) { return refuse("provider_refused") } if err = c.stop("code_opened"); err != nil { return err } err = c.State.tx(ctx, func(t *sql.Tx) error { res, err := t.Exec("UPDATE connect_attempts SET state=state WHERE id=? AND state='running' AND cancelled=0", a.id) if err != nil { return err } if n, err := res.RowsAffected(); err != nil || n != 1 { return firstErr(err, errNotWaiting) } if _, err = t.Exec("INSERT INTO seen_seals(connection_id, attempt, frame_id, created_at) VALUES(?,?,?,?)", s.ConnectionID, s.Attempt, frameID, now()); err != nil { return err } _, err = t.Exec("DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)) return err }) if errors.Is(err, errNotWaiting) { c.refused("not_waiting") return nil } if err != nil { return err } if err = c.stop("code_committed"); err != nil { return err } given := append([]byte(nil), secret...) if !c.handCode(a.id, s.Attempt, codeIn{code: given}) { clear(given) c.refused("not_waiting") } return nil }