package fakeclaude import ( "bufio" "crypto/rand" "encoding/hex" "fmt" "io" "net" "net/url" "os" "os/exec" "os/signal" "path/filepath" "strconv" "strings" "syscall" "time" "golang.org/x/sys/unix" ) // `claude setup-token`, as CLI 2.1.321 was seen to run it on // 2026-11-10 in a pseudo-terminal with no display: a welcome, "Opening // browser to sign in…" (it runs $BROWSER with the URL), a spinner, then // "Browser didn't open? Use the url below to sign in (c to copy)" and // the authorize URL as an OSC 8 hyperlink, redrawn several times, then // the prompt "Paste code here if prompted > ". After a code it does what // the pinned 2.1.312 does, read statically: the token, printed, then // exit; for a code it cannot read (no "#"), "OAuth error: Invalid code. // Please make sure the full code was copied" and, on Enter, the same // link again; for a code the exchange refuses, "OAuth error: // Authentication failed: Invalid authorization code" and, on Enter, a // new sign-in with a new link. // // A right code is SetupCode(email, state) for the state in the URL it // printed: a code from another run's link is wrong. The token it prints // is Token(email). It refuses to run off a terminal (as Ink does), with // a BROWSER that is not a no-op (it would open one), or with anything // in argv but setup-token. Every code it is given (and, after a right // one, the token) it writes into $HOME/.claude.json and // $TMPDIR/claude-exchange.log, as a CLI may during the exchange. A code // starting "orphan" makes it start a child that // ignores a hangup and exit, leaving the child. // // Steering, from SetupSteerFile beside the binary (absent inside a // namespace, where the binary is /opt/claude), one word a line: // "fail_start" exits before any URL; "exit_on_wrong" exits after a wrong // code; "expire_ms=" exits when no code came within n ms (the CLI's // own expiry); "orphan" starts the child once the link shows. Every run // appends its argv to SetupArgvFile and its pid to SetupPidFile beside // the binary, so a test sees what the runner passed and whether the // process is gone. const ( SetupSteerFile = "setup-token.steer" SetupArgvFile = "setup-token.argv" SetupPidFile = "setup-token.pids" ) // SetupCode is the code Anthropic's page shows for email after the // sign-in that the link with state started. func SetupCode(email, state string) string { return "fakecode-" + hex.EncodeToString([]byte(email)) + "#" + state } func setupSteer() (dir string, words map[string]string) { words = map[string]string{} self, err := os.Executable() if err != nil { return "", words } dir = filepath.Dir(self) raw, _ := os.ReadFile(filepath.Join(dir, SetupSteerFile)) for _, line := range strings.Split(string(raw), "\n") { k, v, _ := strings.Cut(strings.TrimSpace(line), "=") if k != "" { words[k] = v } } return dir, words } func setupToken(args []string, stdin io.Reader, stdout io.Writer) int { dir, steer := setupSteer() if dir != "" { if f, err := os.OpenFile(filepath.Join(dir, SetupArgvFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600); err == nil { fmt.Fprintln(f, strings.Join(args, " ")) f.Close() } if f, err := os.OpenFile(filepath.Join(dir, SetupPidFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600); err == nil { fmt.Fprintln(f, os.Getpid()) f.Close() } } if len(args) != 1 { fmt.Fprintln(stdout, "error: unknown option") return 2 } if _, err := unix.IoctlGetWinsize(0, unix.TIOCGWINSZ); err != nil { fmt.Fprintln(stdout, "Raw mode is not supported on the current process.stdin") return 6 } browser := os.Getenv("BROWSER") if filepath.Base(browser) != "true" { fmt.Fprintln(stdout, "would open a real browser") return 5 } out := func(s string) { _, _ = io.WriteString(stdout, s) } out("\x1b[1mWelcome to Claude Code\x1b[22m\r\n\r\nThis will guide you through long-lived (1-year) auth token setup for your Claude account. Claude subscription required.\r\n\r\n") if _, ok := steer["fail_start"]; ok { out("\x1b[31mError: could not start the sign-in\x1b[39m\r\n") return 1 } // prompt draws the link and the prompt, redrawn as the CLI does. prompt := func(link string) { screen := "\r\x1b[2KBrowser didn't open? Use the url below to sign in \x1b[2m(c to copy)\x1b[22m\r\n\r\n\x1b]8;;" + link + "\x1b\\\x1b[34m" + link + "\x1b[39m\x1b]8;;\x1b\\\r\n\r\n\x1b[1mPaste code here if prompted >\x1b[22m " for i := 0; i < 3; i++ { if i > 0 { out("\x1b[4A\r\x1b[J") } out(screen) time.Sleep(10 * time.Millisecond) } } var state, link string // signIn starts a sign-in: a new state, a new link, the screen. signIn := func() { state = rand.Text() link = "https://claude.com/cai/oauth/authorize?code=true&client_id=9d1c250a-fake&response_type=code&redirect_uri=" + url.QueryEscape("https://platform.claude.com/oauth/code/callback") + "&scope=user%3Ainference&code_challenge=fake-challenge&code_challenge_method=S256&state=" + state out("Opening browser to sign in…\r\n") _ = exec.Command(browser, link).Run() for _, f := range []string{"⠋", "⠙", "⠹", "⠸"} { out("\r\x1b[2K\x1b[36m" + f + "\x1b[39m Waiting for sign-in…") time.Sleep(10 * time.Millisecond) } prompt(link) } signIn() if _, ok := steer["orphan"]; ok { orphan() } lines := make(chan string) go func() { scan := bufio.NewScanner(stdin) for scan.Scan() { lines <- scan.Text() } close(lines) }() expire := 15 * time.Minute if ms, err := strconv.Atoi(steer["expire_ms"]); err == nil && ms > 0 { expire = time.Duration(ms) * time.Millisecond } for { var code string select { case l, ok := <-lines: if !ok { return 1 } code = strings.TrimSpace(l) case <-time.After(expire): out("\r\n\x1b[31mTimed out waiting for the code.\x1b[39m\r\n") return 1 } if code == "" { continue } out("\x1b[36m⠋\x1b[39m Exchanging the code…\r\n") time.Sleep(20 * time.Millisecond) if paths, ok := strings.CutPrefix(code, "probe:"); ok { // What this process can reach: the paths named, writes in // its namespace's places, a CONNECT to a host off the list. probe(out, strings.Split(paths, ",")) prompt(link) continue } if strings.HasPrefix(code, "orphan") { // A child that ignores a hangup and outlives this process. orphan() return 0 } mid, got, ok := strings.Cut(code, "#") email, err := hex.DecodeString(strings.TrimPrefix(mid, "fakecode-")) right := ok && got == state && strings.HasPrefix(mid, "fakecode-") && err == nil // What a CLI may write during the exchange, the code and (once // it has one) the token in it: its config and a scratch file. kept := code if right { kept += "\n" + Token(string(email)) } _ = os.WriteFile(filepath.Join(home(), ".claude.json"), []byte(kept), 0600) _ = os.WriteFile(filepath.Join(os.TempDir(), "claude-exchange.log"), []byte(kept), 0600) if right { out("\r\n\x1b[32m✓\x1b[39m Long-lived authentication token created successfully!\r\n\r\nYour OAuth token (valid for 1 year):\r\n\r\n\x1b[33m" + Token(string(email)) + "\x1b[39m\r\n\r\nStore this token securely. You won't be able to see it again.\r\n\r\nUse this token by setting: export CLAUDE_CODE_OAUTH_TOKEN=\r\n") return 0 } // As 2.1.312: a code it cannot read keeps the link; one the // exchange refuses starts a new sign-in. Both wait for Enter. message := "Authentication failed: Invalid authorization code" if !ok || mid == "" || got == "" { message = "Invalid code. Please make sure the full code was copied" } out("\r\n\x1b[31mOAuth error: " + message + "\x1b[39m\r\n\r\nPress \x1b[1mEnter\x1b[22m to retry.\r\n") if _, ok := steer["exit_on_wrong"]; ok { return 1 } select { case _, open := <-lines: if !open { return 1 } case <-time.After(expire): return 1 } if message == "Invalid code. Please make sure the full code was copied" { prompt(link) } else { signIn() } } } // orphan starts a child of this process that ignores a hangup and // outlives it (FAKE_SETUP_CHILD), as a CLI's helper could. func orphan() { self, err := os.Executable() if err != nil { return } ready, said, err := os.Pipe() if err != nil { return } cmd := exec.Command(self, "setup-token-child") cmd.Env = append(os.Environ(), "FAKE_SETUP_CHILD=1") cmd.ExtraFiles = []*os.File{said} if cmd.Start() == nil { // Only once it ignores a hangup: the exit sends one. said.Close() var b [1]byte _, _ = ready.Read(b[:]) } ready.Close() } // SetupChild is the orphan: it ignores SIGHUP, says so on fd 3, and // sleeps. func setupChild() int { signal.Ignore(syscall.SIGHUP) if f := os.NewFile(3, "ready"); f != nil { _, _ = f.Write([]byte{1}) f.Close() } time.Sleep(10 * time.Minute) return 0 } // probe reports, one "probe ..." line each, whether each path reads, // whether each of the namespace's places takes a write, and what the // egress proxy says to a CONNECT for a host off the sign-in's list; then // "probe done". func probe(out func(string), paths []string) { for _, p := range paths { _, err := os.ReadFile(p) word := "ok" if os.IsNotExist(err) { word = "absent" } else if err != nil { word = "denied" } out("probe read " + p + " " + word + "\r\n") } for _, p := range []string{"/home/runner/w", "/tmp/w", "/workspace/w", "/opt/w", "/etc/w", "/usr/w"} { word := "ok" if os.WriteFile(p, []byte("x"), 0600) != nil { word = "denied" } out("probe write " + p + " " + word + "\r\n") } status := "no-proxy" if proxy, err := url.Parse(os.Getenv("HTTPS_PROXY")); err == nil && proxy.Host != "" { status = "unreachable" if c, err := net.DialTimeout("tcp", proxy.Host, 5*time.Second); err == nil { _ = c.SetDeadline(time.Now().Add(10 * time.Second)) fmt.Fprintf(c, "CONNECT example.net:443 HTTP/1.1\r\nHost: example.net:443\r\n\r\n") line, _ := bufio.NewReader(c).ReadString('\n') status = strings.ReplaceAll(strings.TrimSpace(line), " ", "_") c.Close() } } out("probe connect example.net " + status + "\r\nprobe done\r\n") }