package connect import ( "bytes" "context" "io" "net/url" "regexp" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/wire" ) // Claude's sign-in with no terminal (Paul, 2026-11-10: "Can you not run // this on the server and get a link to give to the browser?"). The // runner runs the unmodified `claude setup-token` on a pseudo-terminal in // the connection's new home, reads the authorize URL it prints, and // later types the one-time code Anthropic showed the person into it. The // CLI prints the long-lived token, which the caller keeps as a pasted // token is kept. The CLI's output is read only for the URL, the prompt, // the token and a failure; it is never logged or returned, and it is // zeroed when the run ends (it echoes the code and shows the token). // Outcomes of a typed code (SetupToken.Result). const ( // CodeToken: the CLI printed a token. CodeToken = "token" // CodeAgain: the CLI said the code failed and asks for another. CodeAgain = "again" // CodeEnded: the CLI exited, or said the code failed and stopped // asking, with no token. CodeEnded = "ended" ) // setupOutput bounds the output kept: the last of it, enough for the // screen the CLI redraws. const setupOutput = 256 << 10 // promptText is the CLI's line asking for the code. const promptText = "Paste code here" // giveUp is how long a failure may stand with no new prompt before the // CLI is taken to have stopped asking. const giveUp = 5 * time.Second var ( linkPattern = regexp.MustCompile(`https://[^\s"'<>\x60]+`) tokenPattern = regexp.MustCompile(`sk-ant-oat[0-9A-Za-z_-]+`) failPattern = regexp.MustCompile(`(?i)\b(error|invalid|failed|failure|expired|wrong|try again)\b`) ) // AuthorizeURL checks a URL the CLI printed: Anthropic's own authorize // page on claude.com or claude.ai, over https, whose redirect is the code // page (wire.EndpointClaudeCode) that shows the person a code to paste. func AuthorizeURL(raw string) (string, bool) { u, err := url.Parse(strings.TrimSpace(raw)) if err != nil || u.Scheme != "https" || u.User != nil || u.Host != "claude.com" && u.Host != "claude.ai" || !strings.HasSuffix(u.Path, "/oauth/authorize") || u.Fragment != "" { return "", false } q, err := url.ParseQuery(u.RawQuery) if err != nil { return "", false } for _, k := range []string{"redirect_uri", "response_type", "state", "client_id"} { if len(q[k]) != 1 { return "", false } } if q.Get("redirect_uri") != wire.EndpointClaudeCode || q.Get("response_type") != "code" || q.Get("state") == "" || q.Get("client_id") == "" { return "", false } return u.String(), true } // visible is what a terminal shows of raw, line by line: escape // sequences dropped (CSI, OSC, DCS and the rest), carriage returns as // line ends, other controls dropped. links are the targets of OSC 8 // hyperlinks, in order. func visible(raw []byte) (text []byte, links []string) { text = make([]byte, 0, len(raw)) for i := 0; i < len(raw); i++ { c := raw[i] switch { case c == 0x1b && i+1 < len(raw): i++ switch raw[i] { case '[': // CSI: parameters, then one final byte. for i+1 < len(raw) && (raw[i+1] < 0x40 || raw[i+1] > 0x7e) { i++ } i++ case ']', 'P', '_', '^', 'X': // OSC, DCS, APC, PM, SOS: to BEL or ST (ESC \). start := i + 1 end := len(raw) for j := start; j < len(raw); j++ { if raw[j] == 0x07 { end, i = j, j break } if raw[j] == 0x1b && j+1 < len(raw) && raw[j+1] == '\\' { end, i = j, j+1 break } } if end == len(raw) { i = len(raw) } // An OSC not yet terminated is not yet a link: its target // may still be arriving. if raw[start-1] == ']' && end < len(raw) { // OSC 8 ; params ; URI if body := string(raw[start:end]); strings.HasPrefix(body, "8;") { if _, target, ok := strings.Cut(body[2:], ";"); ok && target != "" { links = append(links, target) } } } } case c == 0x1b: case c == '\r' || c == '\n': text = append(text, '\n') case c == '\t': text = append(text, ' ') case c < 0x20 || c == 0x7f: default: text = append(text, c) } } return text, links } // authorizeIn finds the first valid authorize URL in raw: an OSC 8 // target first, else the visible text; only whole ones (TestAuthorize // NeverTruncated). func authorizeIn(raw []byte) (string, bool) { text, links := visible(raw) defer clear(text) for _, l := range links { if u, ok := AuthorizeURL(l); ok { return u, true } } // A visible link counts once something follows it: the rest of it // may still be arriving. for _, loc := range linkPattern.FindAllIndex(text, -1) { if loc[1] == len(text) { continue } if u, ok := AuthorizeURL(string(text[loc[0]:loc[1]])); ok { return u, true } } return "", false } // tokenIn finds a whole token in text: one with something printed after // it, or at the very end once the CLI has exited. func tokenIn(text []byte, ended bool) []byte { for _, loc := range tokenPattern.FindAllIndex(text, -1) { if loc[1] < len(text) || ended { return bytes.Clone(text[loc[0]:loc[1]]) } } return nil } // failedAt is where the first failure the CLI printed in text starts // (-1: none). The prompt's own line, which echoes the code, never counts. func failedAt(text []byte) int { at := 0 for _, line := range bytes.SplitAfter(text, []byte("\n")) { if !bytes.Contains(line, []byte(promptText)) { if loc := failPattern.FindIndex(line); loc != nil { return at + loc[0] } } at += len(line) } return -1 } // Terminal is one run of the CLI on a pseudo-terminal, started by its // host inside the launch's containment: reads and writes go to the // terminal; Done is closed once the CLI has exited; Stop ends the whole // launch boundary (every process the CLI started, whether or not it is // still running itself) and returns only once that is proven, or with // an error when it cannot be. type Terminal interface { io.ReadWriter Done() <-chan struct{} Stop() error } // SetupToken is one run of `claude setup-token`. type SetupToken struct { term Terminal exited <-chan struct{} read chan struct{} more chan struct{} mu sync.Mutex // raw is the last of what the CLI printed; mark is where in raw the // output after the last typed code starts; asked says the CLI asked // again for a code before mark; link is the latest whole link. raw []byte mark int asked bool link string } // NewSetupToken reads the CLI's output on term from now on. The host // started it as `claude setup-token` with BROWSER a program that opens // nothing (provider.BuildSignInPolicy). func NewSetupToken(term Terminal) *SetupToken { s := &SetupToken{term: term, exited: term.Done(), read: make(chan struct{}), more: make(chan struct{}, 1)} go func() { defer close(s.read) buf := make([]byte, 8192) defer clear(buf) for { n, err := term.Read(buf) if n > 0 { s.mu.Lock() s.raw = append(s.raw, buf[:n]...) if over := len(s.raw) - setupOutput; over > 0 { kept := bytes.Clone(s.raw[over:]) clear(s.raw) s.raw, s.mark = kept, max(0, s.mark-over) } s.mu.Unlock() s.poke() } if err != nil { return } } }() go func() { <-s.exited s.poke() }() return s } func (s *SetupToken) poke() { select { case s.more <- struct{}{}: default: } } // done reports whether the CLI has exited. func (s *SetupToken) done() bool { select { case <-s.exited: return true default: return false } } // settled waits, briefly, for the output of a CLI that exited. func (s *SetupToken) settled() { select { case <-s.read: case <-time.After(time.Second): } } // wait blocks until there is more output, the CLI exits, ctx ends or a // short tick passes. func (s *SetupToken) wait(ctx context.Context) error { select { case <-ctx.Done(): return ctx.Err() case <-s.more: case <-time.After(100 * time.Millisecond): } return nil } // URL waits for the authorize URL the CLI prints. ErrRefused: the CLI // exited before printing one. func (s *SetupToken) URL(ctx context.Context) (string, error) { for { ended := s.done() if ended { s.settled() } s.mu.Lock() u, ok := authorizeIn(s.raw) if ok { s.link = u } s.mu.Unlock() if ok { return u, nil } if ended { return "", ErrRefused } if err := s.wait(ctx); err != nil { return "", err } } } // Submit types code into the CLI and presses Enter, once its prompt // shows (or after ten seconds). The caller clears code. func (s *SetupToken) Submit(ctx context.Context, code []byte) error { deadline := time.Now().Add(10 * time.Second) for time.Now().Before(deadline) { s.mu.Lock() text, _ := visible(s.raw[s.mark:]) shown := s.asked || bytes.Contains(text, []byte(promptText)) clear(text) s.mu.Unlock() if shown || s.done() { break } if err := s.wait(ctx); err != nil { return err } } if s.done() { return ErrRefused } s.mu.Lock() s.mark, s.asked = len(s.raw), false s.mu.Unlock() if _, err := s.term.Write(code); err != nil { return err } // Enter apart from the text, so it is a key press and not part of a // paste. select { case <-ctx.Done(): return ctx.Err() case <-time.After(150 * time.Millisecond): } _, err := s.term.Write([]byte{'\r'}) return err } // Result waits for what the CLI does with the code: a token (returned; // the caller clears it), a failure after which the CLI asks again while // it runs (CodeAgain; Link is then the link to show), or nothing more // (CodeEnded: it exited, or said the code failed and asked for no other // within giveUp). The pinned CLI (2.1.312, read statically) shows a // failed code as "OAuth error: ..." and waits for Enter to retry: for a // code it could not read, at the same link; for one the exchange // refused, in a new sign-in with a new link. Result presses Enter once // for it. func (s *SetupToken) Result(ctx context.Context) (string, []byte, error) { var failed time.Time pressed := false for { ended := s.done() if ended { s.settled() } s.mu.Lock() text, _ := visible(s.raw[s.mark:]) s.mu.Unlock() token := tokenIn(text, ended) at := failedAt(text) again := at >= 0 && bytes.Contains(text[at:], []byte(promptText)) clear(text) switch { case token != nil: return CodeToken, token, nil case ended: return CodeEnded, nil, nil case at >= 0 && failed.IsZero(): failed = time.Now() } if again { // Asked again: let the screen settle, then hand the prompt // back with the link it shows now. if time.Since(failed) >= 500*time.Millisecond { s.mu.Lock() s.mark, s.asked = len(s.raw), true if u, ok := lastAuthorize(s.raw); ok { s.link = u } s.mu.Unlock() return CodeAgain, nil, nil } } else if !failed.IsZero() && !pressed && time.Since(failed) >= time.Second { // The error screen waits for Enter to retry. pressed = true if _, err := s.term.Write([]byte{'\r'}); err != nil { return CodeEnded, nil, nil } } else if !failed.IsZero() && time.Since(failed) > giveUp { return CodeEnded, nil, nil } if err := s.wait(ctx); err != nil { return "", nil, err } } } // Link is the latest whole link the CLI printed. func (s *SetupToken) Link() string { s.mu.Lock() defer s.mu.Unlock() return s.link } // lastAuthorize finds the last valid authorize URL in raw, as // authorizeIn finds the first. func lastAuthorize(raw []byte) (string, bool) { text, links := visible(raw) defer clear(text) for i := len(links) - 1; i >= 0; i-- { if u, ok := AuthorizeURL(links[i]); ok { return u, true } } locs := linkPattern.FindAllIndex(text, -1) for i := len(locs) - 1; i >= 0; i-- { if locs[i][1] == len(text) { continue } if u, ok := AuthorizeURL(string(text[locs[i][0]:locs[i][1]])); ok { return u, true } } return "", false } // Done is closed once the CLI has exited, on its own or stopped. func (s *SetupToken) Done() <-chan struct{} { return s.exited } // Close stops the CLI and everything it started (Terminal.Stop: the // whole launch boundary, proven gone) and zeroes everything it printed. // An error says the boundary could not be proven gone: the caller keeps // what it would delete until recovery proves it. func (s *SetupToken) Close() error { err := s.term.Stop() select { case <-s.read: case <-time.After(2 * time.Second): } s.mu.Lock() clear(s.raw) s.raw, s.mark = nil, 0 s.mu.Unlock() return err }