oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package fakeclaude
2
3import (
4 "bufio"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "io"
9 "net"
10 "net/url"
11 "os"
12 "os/exec"
13 "os/signal"
14 "path/filepath"
15 "strconv"
16 "strings"
17 "syscall"
18 "time"
19
20 "golang.org/x/sys/unix"
21)
22
23// `claude setup-token`, as CLI 2.1.321 was seen to run it on
24// 2026-11-10 in a pseudo-terminal with no display: a welcome, "Opening
25// browser to sign in…" (it runs $BROWSER with the URL), a spinner, then
26// "Browser didn't open? Use the url below to sign in (c to copy)" and
27// the authorize URL as an OSC 8 hyperlink, redrawn several times, then
28// the prompt "Paste code here if prompted > ". After a code it does what
29// the pinned 2.1.312 does, read statically: the token, printed, then
30// exit; for a code it cannot read (no "#"), "OAuth error: Invalid code.
31// Please make sure the full code was copied" and, on Enter, the same
32// link again; for a code the exchange refuses, "OAuth error:
33// Authentication failed: Invalid authorization code" and, on Enter, a
34// new sign-in with a new link.
35//
36// A right code is SetupCode(email, state) for the state in the URL it
37// printed: a code from another run's link is wrong. The token it prints
38// is Token(email). It refuses to run off a terminal (as Ink does), with
39// a BROWSER that is not a no-op (it would open one), or with anything
40// in argv but setup-token. Every code it is given (and, after a right
41// one, the token) it writes into $HOME/.claude.json and
42// $TMPDIR/claude-exchange.log, as a CLI may during the exchange. A code
43// starting "orphan" makes it start a child that
44// ignores a hangup and exit, leaving the child.
45//
46// Steering, from SetupSteerFile beside the binary (absent inside a
47// namespace, where the binary is /opt/claude), one word a line:
48// "fail_start" exits before any URL; "exit_on_wrong" exits after a wrong
49// code; "expire_ms=<n>" exits when no code came within n ms (the CLI's
50// own expiry); "orphan" starts the child once the link shows. Every run
51// appends its argv to SetupArgvFile and its pid to SetupPidFile beside
52// the binary, so a test sees what the runner passed and whether the
53// process is gone.
54const (
55 SetupSteerFile = "setup-token.steer"
56 SetupArgvFile = "setup-token.argv"
57 SetupPidFile = "setup-token.pids"
58)
59
60// SetupCode is the code Anthropic's page shows for email after the
61// sign-in that the link with state started.
62func SetupCode(email, state string) string {
63 return "fakecode-" + hex.EncodeToString([]byte(email)) + "#" + state
64}
65
66func setupSteer() (dir string, words map[string]string) {
67 words = map[string]string{}
68 self, err := os.Executable()
69 if err != nil {
70 return "", words
71 }
72 dir = filepath.Dir(self)
73 raw, _ := os.ReadFile(filepath.Join(dir, SetupSteerFile))
74 for _, line := range strings.Split(string(raw), "\n") {
75 k, v, _ := strings.Cut(strings.TrimSpace(line), "=")
76 if k != "" {
77 words[k] = v
78 }
79 }
80 return dir, words
81}
82
83func setupToken(args []string, stdin io.Reader, stdout io.Writer) int {
84 dir, steer := setupSteer()
85 if dir != "" {
86 if f, err := os.OpenFile(filepath.Join(dir, SetupArgvFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600); err == nil {
87 fmt.Fprintln(f, strings.Join(args, " "))
88 f.Close()
89 }
90 if f, err := os.OpenFile(filepath.Join(dir, SetupPidFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600); err == nil {
91 fmt.Fprintln(f, os.Getpid())
92 f.Close()
93 }
94 }
95 if len(args) != 1 {
96 fmt.Fprintln(stdout, "error: unknown option")
97 return 2
98 }
99 if _, err := unix.IoctlGetWinsize(0, unix.TIOCGWINSZ); err != nil {
100 fmt.Fprintln(stdout, "Raw mode is not supported on the current process.stdin")
101 return 6
102 }
103 browser := os.Getenv("BROWSER")
104 if filepath.Base(browser) != "true" {
105 fmt.Fprintln(stdout, "would open a real browser")
106 return 5
107 }
108 out := func(s string) { _, _ = io.WriteString(stdout, s) }
109 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")
110 if _, ok := steer["fail_start"]; ok {
111 out("\x1b[31mError: could not start the sign-in\x1b[39m\r\n")
112 return 1
113 }
114 // prompt draws the link and the prompt, redrawn as the CLI does.
115 prompt := func(link string) {
116 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 "
117 for i := 0; i < 3; i++ {
118 if i > 0 {
119 out("\x1b[4A\r\x1b[J")
120 }
121 out(screen)
122 time.Sleep(10 * time.Millisecond)
123 }
124 }
125 var state, link string
126 // signIn starts a sign-in: a new state, a new link, the screen.
127 signIn := func() {
128 state = rand.Text()
129 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
130 out("Opening browser to sign in…\r\n")
131 _ = exec.Command(browser, link).Run()
132 for _, f := range []string{"⠋", "⠙", "⠹", "⠸"} {
133 out("\r\x1b[2K\x1b[36m" + f + "\x1b[39m Waiting for sign-in…")
134 time.Sleep(10 * time.Millisecond)
135 }
136 prompt(link)
137 }
138 signIn()
139 if _, ok := steer["orphan"]; ok {
140 orphan()
141 }
142 lines := make(chan string)
143 go func() {
144 scan := bufio.NewScanner(stdin)
145 for scan.Scan() {
146 lines <- scan.Text()
147 }
148 close(lines)
149 }()
150 expire := 15 * time.Minute
151 if ms, err := strconv.Atoi(steer["expire_ms"]); err == nil && ms > 0 {
152 expire = time.Duration(ms) * time.Millisecond
153 }
154 for {
155 var code string
156 select {
157 case l, ok := <-lines:
158 if !ok {
159 return 1
160 }
161 code = strings.TrimSpace(l)
162 case <-time.After(expire):
163 out("\r\n\x1b[31mTimed out waiting for the code.\x1b[39m\r\n")
164 return 1
165 }
166 if code == "" {
167 continue
168 }
169 out("\x1b[36m⠋\x1b[39m Exchanging the code…\r\n")
170 time.Sleep(20 * time.Millisecond)
171 if paths, ok := strings.CutPrefix(code, "probe:"); ok {
172 // What this process can reach: the paths named, writes in
173 // its namespace's places, a CONNECT to a host off the list.
174 probe(out, strings.Split(paths, ","))
175 prompt(link)
176 continue
177 }
178 if strings.HasPrefix(code, "orphan") {
179 // A child that ignores a hangup and outlives this process.
180 orphan()
181 return 0
182 }
183 mid, got, ok := strings.Cut(code, "#")
184 email, err := hex.DecodeString(strings.TrimPrefix(mid, "fakecode-"))
185 right := ok && got == state && strings.HasPrefix(mid, "fakecode-") && err == nil
186 // What a CLI may write during the exchange, the code and (once
187 // it has one) the token in it: its config and a scratch file.
188 kept := code
189 if right {
190 kept += "\n" + Token(string(email))
191 }
192 _ = os.WriteFile(filepath.Join(home(), ".claude.json"), []byte(kept), 0600)
193 _ = os.WriteFile(filepath.Join(os.TempDir(), "claude-exchange.log"), []byte(kept), 0600)
194 if right {
195 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=<token>\r\n")
196 return 0
197 }
198 // As 2.1.312: a code it cannot read keeps the link; one the
199 // exchange refuses starts a new sign-in. Both wait for Enter.
200 message := "Authentication failed: Invalid authorization code"
201 if !ok || mid == "" || got == "" {
202 message = "Invalid code. Please make sure the full code was copied"
203 }
204 out("\r\n\x1b[31mOAuth error: " + message + "\x1b[39m\r\n\r\nPress \x1b[1mEnter\x1b[22m to retry.\r\n")
205 if _, ok := steer["exit_on_wrong"]; ok {
206 return 1
207 }
208 select {
209 case _, open := <-lines:
210 if !open {
211 return 1
212 }
213 case <-time.After(expire):
214 return 1
215 }
216 if message == "Invalid code. Please make sure the full code was copied" {
217 prompt(link)
218 } else {
219 signIn()
220 }
221 }
222}
223
224// orphan starts a child of this process that ignores a hangup and
225// outlives it (FAKE_SETUP_CHILD), as a CLI's helper could.
226func orphan() {
227 self, err := os.Executable()
228 if err != nil {
229 return
230 }
231 ready, said, err := os.Pipe()
232 if err != nil {
233 return
234 }
235 cmd := exec.Command(self, "setup-token-child")
236 cmd.Env = append(os.Environ(), "FAKE_SETUP_CHILD=1")
237 cmd.ExtraFiles = []*os.File{said}
238 if cmd.Start() == nil {
239 // Only once it ignores a hangup: the exit sends one.
240 said.Close()
241 var b [1]byte
242 _, _ = ready.Read(b[:])
243 }
244 ready.Close()
245}
246
247// SetupChild is the orphan: it ignores SIGHUP, says so on fd 3, and
248// sleeps.
249func setupChild() int {
250 signal.Ignore(syscall.SIGHUP)
251 if f := os.NewFile(3, "ready"); f != nil {
252 _, _ = f.Write([]byte{1})
253 f.Close()
254 }
255 time.Sleep(10 * time.Minute)
256 return 0
257}
258
259// probe reports, one "probe ..." line each, whether each path reads,
260// whether each of the namespace's places takes a write, and what the
261// egress proxy says to a CONNECT for a host off the sign-in's list; then
262// "probe done".
263func probe(out func(string), paths []string) {
264 for _, p := range paths {
265 _, err := os.ReadFile(p)
266 word := "ok"
267 if os.IsNotExist(err) {
268 word = "absent"
269 } else if err != nil {
270 word = "denied"
271 }
272 out("probe read " + p + " " + word + "\r\n")
273 }
274 for _, p := range []string{"/home/runner/w", "/tmp/w", "/workspace/w", "/opt/w", "/etc/w", "/usr/w"} {
275 word := "ok"
276 if os.WriteFile(p, []byte("x"), 0600) != nil {
277 word = "denied"
278 }
279 out("probe write " + p + " " + word + "\r\n")
280 }
281 status := "no-proxy"
282 if proxy, err := url.Parse(os.Getenv("HTTPS_PROXY")); err == nil && proxy.Host != "" {
283 status = "unreachable"
284 if c, err := net.DialTimeout("tcp", proxy.Host, 5*time.Second); err == nil {
285 _ = c.SetDeadline(time.Now().Add(10 * time.Second))
286 fmt.Fprintf(c, "CONNECT example.net:443 HTTP/1.1\r\nHost: example.net:443\r\n\r\n")
287 line, _ := bufio.NewReader(c).ReadString('\n')
288 status = strings.ReplaceAll(strings.TrimSpace(line), " ", "_")
289 c.Close()
290 }
291 }
292 out("probe connect example.net " + status + "\r\nprobe done\r\n")
293}
294