package thin import ( "context" "crypto/rand" "database/sql" "encoding/json" "errors" "os" "path/filepath" "strings" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" ) // Token connections (Connections spec §2.4, Paul 2026-11-09): the person // runs `claude setup-token`, pastes the token into the app, which seals // it to this runner's seal key; the instance relays the opaque box in a // durable secret frame. The runner opens it, keeps the token only in the // connection's dedicated home (provider.TokenFile, 0600), and the CLI // reads it from CLAUDE_CODE_OAUTH_TOKEN. The token is never logged, put // in an error, a report, argv or a frame. // sealMemory is how long a delivered (connection, attempt) is remembered. const sealMemory = 24 * time.Hour // credentialPresent marks an attempt whose secret is committed. const credentialPresent = "credential_present" // errStopped is a test fault: the process stops at a delivery boundary. var errStopped = errors.New("stopped") // tokenAttempt is a token or sign-in attempt's row. type tokenAttempt struct { id, person, home, state, kind, secret, provider string cancelled bool } func (a tokenAttempt) waiting() bool { return a.state == "running" && (a.kind == wire.KindToken || a.kind == wire.KindAPIKey) && !a.cancelled && a.secret == "" && a.home != "" } // sealedFor is the provider and endpoint a box for the attempt must be // bound to: Claude's API for a token, the provider's own origin for an // API key (connectors spec §2.2). func (a tokenAttempt) sealedFor() (string, string, bool) { if a.kind == wire.KindAPIKey { kp, ok := wire.APIKeyProviders[a.provider] return a.provider, kp.Endpoint, ok } return wire.ProviderClaude, wire.EndpointAnthropic, a.provider == wire.ProviderClaude } // signIn says the attempt is Claude's sign-in by the runner's own // `claude setup-token` (signin.go): Claude, not a token. Once its token // is committed it is a token attempt. func (a tokenAttempt) signIn() bool { return a.provider == wire.ProviderClaude && a.kind != wire.KindToken } func (c *Connector) attempt(ctx context.Context, id string) (tokenAttempt, bool, error) { a := tokenAttempt{id: id} var cancelled int err := c.State.db.QueryRowContext(ctx, "SELECT person, home, state, kind, secret, provider, cancelled FROM connect_attempts WHERE id=?", id).Scan(&a.person, &a.home, &a.state, &a.kind, &a.secret, &a.provider, &cancelled) if errors.Is(err, sql.ErrNoRows) { return a, false, nil } a.cancelled = cancelled == 1 return a, err == nil, err } // waitFor registers the attempt's wake channel. func (c *Connector) waitFor(id string) chan struct{} { c.mu.Lock() defer c.mu.Unlock() ch := make(chan struct{}, 1) c.waits[id] = ch return ch } func (c *Connector) stopWaiting(id string) { c.mu.Lock() defer c.mu.Unlock() delete(c.waits, id) } func (c *Connector) wake(id string) { c.mu.Lock() ch := c.waits[id] c.mu.Unlock() if ch != nil { select { case ch <- struct{}{}: default: } } } // tokenHome is the attempt's dedicated home: the one it recorded, or a // new one under the accounts root. func (c *Connector) tokenHome(ctx context.Context, id string) (string, error) { a, ok, err := c.attempt(ctx, id) if err != nil || !ok { return "", firstErr(err, provider.ErrIdentity) } if a.home != "" { return a.home, provider.CheckLoginHome(a.home) } if err = os.MkdirAll(c.Root, 0700); err != nil { return "", err } name := wire.ProviderClaude if a.kind == wire.KindAPIKey { if _, ok := wire.APIKeyProviders[a.provider]; !ok { return "", provider.ErrIdentity } name = a.provider } next := nextHome if a.kind == wire.KindAPIKey { // Never reused: a frame for an earlier connection can never name // a later one (security round, finding 4). next = uniqueHome } _, home, err := next(c.Root, name) if err == nil { err = provider.CheckLoginHome(home) } if err == nil { _, err = c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET home=? WHERE id=?", home, id) } if err != nil && home != "" { os.Remove(home) } return home, err } // failToken ends an attempt not yet saved in error and removes its home, // never while a secret is being delivered to it. A home that could not // be deleted (still bound) goes through the durable sign-out. func (c *Connector) failToken(cmd wire.ConnectCommand, base wire.ConnectionReport, home, reason string) { r := base r.State, r.Reason = wire.ConnError, reason c.delivery.Lock() defer c.delivery.Unlock() c.removeHome(home) if home != "" && exists(home) { go c.endToken(cmd.Connection, cmd.Person, home, r.Reason) return } c.finish(cmd.Connection, r) } // runToken is a token attempt: a dedicated home, the card asking for the // token, then the wait for its sealed secret (Secret); once committed, // the status probe, the binding and the healthy report (madeToken). func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { failed := func(home, reason string) { c.failToken(cmd, base, home, reason) } wake := c.waitFor(cmd.Connection) defer c.stopWaiting(cmd.Connection) home, err := c.tokenHome(ctx, cmd.Connection) if err != nil { c.log("connect home", err) failed(home, "provider_refused") return } a, _, err := c.attempt(ctx, cmd.Connection) if err == nil && a.secret == "" { r := base r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"} c.report(r) } for err == nil && a.secret == "" && a.state == "running" { select { case <-ctx.Done(): failed(home, reasonOf(ctx.Err())) return case <-wake: } a, _, err = c.attempt(ctx, cmd.Connection) } if err != nil || a.state != "running" { // Ended while it waited (a refused box), or unreadable. if err != nil { c.log("connect token", err) failed(home, "provider_refused") } return } c.madeToken(ctx, cmd, base, home, a) } // madeToken carries on an attempt whose token is committed in its home // (pasted, or printed by the runner's own sign-in): the status probe, // the binding, the real check and the healthy report. func (c *Connector) madeToken(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, home string, a tokenAttempt) { failed := func(home, reason string) { c.failToken(cmd, base, home, reason) } id := filepath.Base(home) lock, err := os.Open(home) if err == nil { err = unix.Flock(int(lock.Fd()), unix.LOCK_EX) } if err != nil { if lock != nil { lock.Close() } failed(home, "provider_refused") return } defer lock.Close() // A binding this attempt saved before a stop (its home and id, the // person's): a restart carries on from it, never calling it a second // connection of the same account. saved, bound := c.savedToken(cmd.Person, id, home) if a.cancelled || ctx.Err() != nil { reason := reasonOf(firstErr(ctx.Err(), context.Canceled)) if bound { c.undoToken(cmd, id, lock, reason) } else { failed(home, reason) } return } if !bound { // `auth status --json`, the token in the CLI's environment: the // email, if it names one. It proves nothing about the token. options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} refresh := func(ctx context.Context, b provider.Binding) (provider.Identity, error) { return provider.RefreshLogin(ctx, b, options) } if c.Mac != nil { // A Mac's: the token by descriptor, in its turn. refresh = c.Mac.authStatus } observed, err := refresh(ctx, provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true}) if ctx.Err() != nil { failed(home, reasonOf(ctx.Err())) return } if err != nil { c.log("connect token probe", err) failed(home, "provider_refused") return } for _, b := range c.mine(cmd.Person) { if b.Provider == wire.ProviderClaude && b.AccountID == observed.AccountID { failed(home, "already_connected") return } } if c.Conns != nil { c.Conns.Forget(id) if err = c.Conns.setExpiry(id, time.Now().Add(wire.TokenLifetime)); err != nil { c.log("connect token", err) failed(home, "provider_refused") return } } if err = saveToken(ctx, c.Runner.AccountBindingsPath, cmd.Person, id, home, observed); err != nil { c.log("connect token binding", err) failed(home, "provider_refused") return } if c.stop("bound") != nil { return } if saved, bound = c.savedToken(cmd.Person, id, home); !bound { failed(home, "provider_refused") return } } // The real check (it takes the home's lock, as every launch does). // Only an answer makes the connection. A refusal, or a check that // cannot finish, ends the attempt provider_refused (the app's "This // token was rejected"; an attempt never ends sign_in_again). _ = unix.Flock(int(lock.Fd()), unix.LOCK_UN) if err = c.verifyToken(ctx, saved); err != nil { c.log("connect token check", err) reason := "provider_refused" if ctx.Err() != nil { reason = reasonOf(ctx.Err()) } c.undoToken(cmd, id, lock, reason) return } if c.Conns != nil { c.Conns.Validated(id) c.Conns.changed() } r := base r.State, r.LocalID, r.Label = wire.ConnHealthy, id, profileLabel(saved, c.State.profileEmails()) c.finish(cmd.Connection, r) c.standOrGo(cmd, id, lock) } // savedToken is the binding a token attempt saved for its home. func (c *Connector) savedToken(person, id, home string) (runner.AccountBinding, bool) { for _, b := range c.mine(person) { if b.ID == id && b.ProviderHome == home && b.Kind == wire.KindToken { return b, true } } return runner.AccountBinding{}, false } // verifyToken is a saved token's real check (Conns.Verify). An unfinished // attempt always runs it, whatever the connection's health says: only a // real request answered by the provider makes the token a connection. func (c *Connector) verifyToken(ctx context.Context, b runner.AccountBinding) error { if c.Conns == nil || c.Conns.Verify == nil { return provider.ErrLoginUnavailable } return c.Conns.Verify(ctx, b) } // undoToken ends an attempt whose saved token must not stand: its end // and the sign-out it owes go in one transaction, so even after a stop // the home and the token are deleted; then the sign-out runs. func (c *Connector) undoToken(cmd wire.ConnectCommand, id string, lock *os.File, reason string) { lock.Close() k := cleanup{connection: cmd.Connection, person: cmd.Person, local: id} r := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason} err := c.State.tx(context.Background(), func(t *sql.Tx) error { if _, err := t.Exec("UPDATE connect_attempts SET state='done', local_id=? WHERE id=?", id, cmd.Connection); err != nil { return err } if err := c.State.enqueue(t, wire.FrameConnection, "", r); err != nil { return err } return owe(t, k) }) c.log("connect token", err) if c.Notify != nil { c.Notify() } if err == nil && c.stop("owed") == nil { c.settle(k) } } // endToken ends a token attempt found after a restart that cannot go on // (its time is up). A home with a saved binding, or one that could not be // deleted, goes through the durable sign-out: the attempt's end records // its local id and the cleanup in one transaction, so the binding, the // home and the token are deleted even across another stop; an attempt is // never recorded ended with no local id while its home survives. A // recorded cancel ends it cancelled. func (c *Connector) endToken(id, person, home, reason string) { var cancelled int kind, prov := "", wire.ProviderClaude _ = c.State.db.QueryRow("SELECT cancelled, kind, provider FROM connect_attempts WHERE id=?", id).Scan(&cancelled, &kind, &prov) if cancelled == 1 { reason = "cancelled" } if kind == wire.KindAPIKey { c.endAPIKey(id, person, prov, home, reason) return } r := wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason} // The connection's local id is its home's name. local := filepath.Base(home) _, bound := c.savedToken(person, local, home) if !bound { c.removeHome(home) if home == "" || !exists(home) { c.finish(id, r) return } } k := cleanup{connection: id, person: person, local: local, home: home, provider: wire.ProviderClaude} err := c.State.tx(context.Background(), func(t *sql.Tx) error { if _, err := t.Exec("UPDATE connect_attempts SET state='done', local_id=? WHERE id=?", local, id); err != nil { return err } if err := c.State.enqueue(t, wire.FrameConnection, "", r); err != nil { return err } if err := owe(t, k); err != nil { return err } _, err := t.Exec("UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", home, wire.ProviderClaude, id) return err }) c.log("connect token", err) if c.Notify != nil { c.Notify() } if err == nil { c.background(func() { c.settle(k) }) } } // tokenLabel is what a token connection is called: the account's email // when the CLI reported one, else nothing (the app names it). func tokenLabel(account string) string { if strings.HasPrefix(account, "token:") { return "" } return account } // saveToken records a token home as the person's connection: the // identity file and the binding (kind token). The token stays in the home. func saveToken(ctx context.Context, bindings, person, id, home string, observed provider.Identity) error { observed.HomeID = rand.Text() raw, _ := json.Marshal(observed) if err := os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600); err != nil { return err } b := provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true, AccountID: observed.AccountID, Expected: observed} return runnersetup.SaveAccountBinding(ctx, bindings, person, DefaultModels[wire.ProviderClaude], runnerproto.AccountSetup{ID: id, Provider: wire.ProviderClaude, Label: id}, b) } // resumeToken picks a token attempt up after a restart. Recovery (spec // §2.4): a staged file with no seen_seals row is deleted (the resend is // processed from received); with the row, the secret is committed and // the final file must be there (a rename the stop interrupted is // finished); a row with neither file cannot happen and ends the attempt // in error. Then the attempt waits on for the rest of its time. func (c *Connector) resumeToken(ctx context.Context, id, person, home, created, kind, prov string) error { var rows int if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&rows); err != nil { return err } if home != "" { dir, err := os.Open(home) if err != nil { c.endToken(id, person, home, "runner_offline") return nil } defer dir.Close() fd := int(dir.Fd()) if rows == 0 { for _, name := range []string{provider.TokenStaging, provider.TokenFile} { if err = unix.Unlinkat(fd, name, 0); err != nil && err != unix.ENOENT { return err } } if _, err = c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET secret='' WHERE id=?", id); err != nil { return err } } else { var st unix.Stat_t if unix.Fstatat(fd, provider.TokenFile, &st, unix.AT_SYMLINK_NOFOLLOW) == unix.ENOENT { if err = unix.Renameat(fd, provider.TokenStaging, fd, provider.TokenFile); err != nil { dir.Close() c.endToken(id, person, home, "provider_refused") return nil } } } if err = dir.Sync(); err != nil { return err } } at, _ := time.Parse(time.RFC3339Nano, created) limit := c.Limit if limit <= 0 { limit = ConnectLimit } if !time.Now().Before(at.Add(limit)) { c.endToken(id, person, home, "timed_out") return nil } actx, cancel := context.WithDeadline(c.ctx, at.Add(limit)) c.mu.Lock() c.attempts[id] = cancel c.mu.Unlock() cmd := wire.ConnectCommand{Connection: id, Person: person, Provider: wire.ProviderClaude, Kind: wire.KindToken} if kind == wire.KindAPIKey { cmd.Provider, cmd.Kind = prov, wire.KindAPIKey } go c.run(actx, cancel, cmd) return nil } // Secret delivers a sealed secret to the token attempt it names (spec // §2.4), one durable step at a time: (i) received, nothing written; // (ii) staged: the box opened and checked, the token in the home's // staging file, synced with the directory, the buffer zeroed; (iii) // committed: one transaction records (connection, attempt, frame) in // seen_seals and the attempt's credential_present, and the staging file // is renamed to the token file, the directory synced; (iv) acked by the // link once this returns nil. A resend of a delivered pair is acked and // nothing else. A refused box ends a waiting attempt with a reason; one // for no waiting attempt is acked and dropped. A box for a sign-in // attempt is a code (code, signin.go). Nothing secret reaches a log, an // error or a report. func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretCommand) error { c.delivery.Lock() defer c.delivery.Unlock() s := cmd.Sealed var n int if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=? AND attempt=?", s.ConnectionID, s.Attempt).Scan(&n); err != nil { return err } if n > 0 { return nil } a, found, err := c.attempt(ctx, cmd.Connection) if err != nil { return err } if found && a.signIn() { return c.code(ctx, frameID, cmd, a) } if !found || !a.waiting() { c.refused("no_attempt") return nil } refuse := func(reason string) error { c.refused(reason) r := wire.ConnectionReport{Connection: a.id, Person: a.person, Provider: a.provider, State: wire.ConnError, Reason: reason} c.removeHome(a.home) c.finish(a.id, r) c.wake(a.id) 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) prov, endpoint, known := a.sealedFor() if !known || p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != prov || p.Endpoint != endpoint || p.Attempt < 1 || !provider.ValidToken(secret) { return refuse("provider_refused") } dir, err := pinHome(a.home) if err != nil { return err } defer dir.Close() err = c.keep(ctx, a.id, a.kind, dir, secret, func(t *sql.Tx) error { 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) { // A cancel that won the race is acked. c.refused("not_waiting") return nil } if errors.Is(err, errMacRefused) { // The Mac's guards refused it: nothing was written. c.log("connect token", err) return refuse("provider_refused") } if err != nil { // Anything else is retried on the resend. return err } c.wake(a.id) return nil } // keep makes secret the attempt's token in its home dir, one durable // step at a time: (ii) staged: the home's staging file written, synced // with the directory, the buffer zeroed; (iii) committed: one // transaction marks the attempt credential_present and kind token (with // record, the rest of that transaction), and the staging file is renamed // to the token file, the directory synced. Not committed, nothing of it // stays. errNotWaiting: the attempt was not waiting for it (a cancel won). func (c *Connector) keep(ctx context.Context, id, kind string, dir *os.File, secret []byte, record func(*sql.Tx) error) error { if c.Mac != nil { // A Mac keeps a token in its turn, and only while its guards pass. give, err := c.Mac.store(ctx) if err != nil { clear(secret) return err } defer give() } err := stage(dir, secret) clear(secret) if err != nil { return err } if err = c.stop("staged"); err != nil { return err } err = c.State.tx(ctx, func(t *sql.Tx) error { res, err := t.Exec("UPDATE connect_attempts SET secret=?, kind=? WHERE id=? AND state='running' AND cancelled=0 AND secret=''", credentialPresent, kind, id) if err != nil { return err } if n, err := res.RowsAffected(); err != nil || n != 1 { return firstErr(err, errNotWaiting) } if err = record(t); err != nil { return err } if err = unix.Renameat(int(dir.Fd()), provider.TokenStaging, int(dir.Fd()), provider.TokenFile); err != nil { return err } if err = dir.Sync(); err != nil { return err } // A stop here leaves the token file with no committed row: the // restart deletes it. return c.stop("transaction") }) if err != nil { if !errors.Is(err, errStopped) { _ = unix.Unlinkat(int(dir.Fd()), provider.TokenStaging, 0) _ = unix.Unlinkat(int(dir.Fd()), provider.TokenFile, 0) _ = dir.Sync() } return err } return c.stop("committed") } var errNotWaiting = errors.New("the attempt is not waiting for its secret") // refused logs a refused or dropped box: the category only. func (c *Connector) refused(reason string) { if c.Logger != nil { c.Logger.Info("sealed secret refused", "reason", reason) } } // stop is the test fault at a delivery boundary. func (c *Connector) stop(stage string) error { if c.fault != nil { return c.fault(stage) } return nil } // pinHome opens a home directory without following links. func pinHome(home string) (*os.File, error) { fd, err := unix.Open(home, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) if err != nil { return nil, err } return os.NewFile(uintptr(fd), home), nil } // stage writes the secret to the home's staging file (0600, new) and // syncs it and the directory. func stage(dir *os.File, secret []byte) error { dfd := int(dir.Fd()) if err := unix.Unlinkat(dfd, provider.TokenStaging, 0); err != nil && err != unix.ENOENT { return err } fd, err := unix.Openat(dfd, provider.TokenStaging, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) if err != nil { return err } f := os.NewFile(uintptr(fd), provider.TokenStaging) _, err = f.Write(secret) if err == nil { err = f.Sync() } if cerr := f.Close(); err == nil { err = cerr } if err == nil { err = dir.Sync() } if err != nil { _ = unix.Unlinkat(dfd, provider.TokenStaging, 0) } return err }