oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package connect
2
3import (
4 "bytes"
5 "context"
6 "io"
7 "net/url"
8 "regexp"
9 "strings"
10 "sync"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/wire"
14)
15
16// Claude's sign-in with no terminal (Paul, 2026-11-10: "Can you not run
17// this on the server and get a link to give to the browser?"). The
18// runner runs the unmodified `claude setup-token` on a pseudo-terminal in
19// the connection's new home, reads the authorize URL it prints, and
20// later types the one-time code Anthropic showed the person into it. The
21// CLI prints the long-lived token, which the caller keeps as a pasted
22// token is kept. The CLI's output is read only for the URL, the prompt,
23// the token and a failure; it is never logged or returned, and it is
24// zeroed when the run ends (it echoes the code and shows the token).
25
26// Outcomes of a typed code (SetupToken.Result).
27const (
28 // CodeToken: the CLI printed a token.
29 CodeToken = "token"
30 // CodeAgain: the CLI said the code failed and asks for another.
31 CodeAgain = "again"
32 // CodeEnded: the CLI exited, or said the code failed and stopped
33 // asking, with no token.
34 CodeEnded = "ended"
35)
36
37// setupOutput bounds the output kept: the last of it, enough for the
38// screen the CLI redraws.
39const setupOutput = 256 << 10
40
41// promptText is the CLI's line asking for the code.
42const promptText = "Paste code here"
43
44// giveUp is how long a failure may stand with no new prompt before the
45// CLI is taken to have stopped asking.
46const giveUp = 5 * time.Second
47
48var (
49 linkPattern = regexp.MustCompile(`https://[^\s"'<>\x60]+`)
50 tokenPattern = regexp.MustCompile(`sk-ant-oat[0-9A-Za-z_-]+`)
51 failPattern = regexp.MustCompile(`(?i)\b(error|invalid|failed|failure|expired|wrong|try again)\b`)
52)
53
54// AuthorizeURL checks a URL the CLI printed: Anthropic's own authorize
55// page on claude.com or claude.ai, over https, whose redirect is the code
56// page (wire.EndpointClaudeCode) that shows the person a code to paste.
57func AuthorizeURL(raw string) (string, bool) {
58 u, err := url.Parse(strings.TrimSpace(raw))
59 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 != "" {
60 return "", false
61 }
62 q, err := url.ParseQuery(u.RawQuery)
63 if err != nil {
64 return "", false
65 }
66 for _, k := range []string{"redirect_uri", "response_type", "state", "client_id"} {
67 if len(q[k]) != 1 {
68 return "", false
69 }
70 }
71 if q.Get("redirect_uri") != wire.EndpointClaudeCode || q.Get("response_type") != "code" || q.Get("state") == "" || q.Get("client_id") == "" {
72 return "", false
73 }
74 return u.String(), true
75}
76
77// visible is what a terminal shows of raw, line by line: escape
78// sequences dropped (CSI, OSC, DCS and the rest), carriage returns as
79// line ends, other controls dropped. links are the targets of OSC 8
80// hyperlinks, in order.
81func visible(raw []byte) (text []byte, links []string) {
82 text = make([]byte, 0, len(raw))
83 for i := 0; i < len(raw); i++ {
84 c := raw[i]
85 switch {
86 case c == 0x1b && i+1 < len(raw):
87 i++
88 switch raw[i] {
89 case '[':
90 // CSI: parameters, then one final byte.
91 for i+1 < len(raw) && (raw[i+1] < 0x40 || raw[i+1] > 0x7e) {
92 i++
93 }
94 i++
95 case ']', 'P', '_', '^', 'X':
96 // OSC, DCS, APC, PM, SOS: to BEL or ST (ESC \).
97 start := i + 1
98 end := len(raw)
99 for j := start; j < len(raw); j++ {
100 if raw[j] == 0x07 {
101 end, i = j, j
102 break
103 }
104 if raw[j] == 0x1b && j+1 < len(raw) && raw[j+1] == '\\' {
105 end, i = j, j+1
106 break
107 }
108 }
109 if end == len(raw) {
110 i = len(raw)
111 }
112 // An OSC not yet terminated is not yet a link: its target
113 // may still be arriving.
114 if raw[start-1] == ']' && end < len(raw) {
115 // OSC 8 ; params ; URI
116 if body := string(raw[start:end]); strings.HasPrefix(body, "8;") {
117 if _, target, ok := strings.Cut(body[2:], ";"); ok && target != "" {
118 links = append(links, target)
119 }
120 }
121 }
122 }
123 case c == 0x1b:
124 case c == '\r' || c == '\n':
125 text = append(text, '\n')
126 case c == '\t':
127 text = append(text, ' ')
128 case c < 0x20 || c == 0x7f:
129 default:
130 text = append(text, c)
131 }
132 }
133 return text, links
134}
135
136// authorizeIn finds the first valid authorize URL in raw: an OSC 8
137// target first, else the visible text; only whole ones (TestAuthorize
138// NeverTruncated).
139func authorizeIn(raw []byte) (string, bool) {
140 text, links := visible(raw)
141 defer clear(text)
142 for _, l := range links {
143 if u, ok := AuthorizeURL(l); ok {
144 return u, true
145 }
146 }
147 // A visible link counts once something follows it: the rest of it
148 // may still be arriving.
149 for _, loc := range linkPattern.FindAllIndex(text, -1) {
150 if loc[1] == len(text) {
151 continue
152 }
153 if u, ok := AuthorizeURL(string(text[loc[0]:loc[1]])); ok {
154 return u, true
155 }
156 }
157 return "", false
158}
159
160// tokenIn finds a whole token in text: one with something printed after
161// it, or at the very end once the CLI has exited.
162func tokenIn(text []byte, ended bool) []byte {
163 for _, loc := range tokenPattern.FindAllIndex(text, -1) {
164 if loc[1] < len(text) || ended {
165 return bytes.Clone(text[loc[0]:loc[1]])
166 }
167 }
168 return nil
169}
170
171// failedAt is where the first failure the CLI printed in text starts
172// (-1: none). The prompt's own line, which echoes the code, never counts.
173func failedAt(text []byte) int {
174 at := 0
175 for _, line := range bytes.SplitAfter(text, []byte("\n")) {
176 if !bytes.Contains(line, []byte(promptText)) {
177 if loc := failPattern.FindIndex(line); loc != nil {
178 return at + loc[0]
179 }
180 }
181 at += len(line)
182 }
183 return -1
184}
185
186// Terminal is one run of the CLI on a pseudo-terminal, started by its
187// host inside the launch's containment: reads and writes go to the
188// terminal; Done is closed once the CLI has exited; Stop ends the whole
189// launch boundary (every process the CLI started, whether or not it is
190// still running itself) and returns only once that is proven, or with
191// an error when it cannot be.
192type Terminal interface {
193 io.ReadWriter
194 Done() <-chan struct{}
195 Stop() error
196}
197
198// SetupToken is one run of `claude setup-token`.
199type SetupToken struct {
200 term Terminal
201 exited <-chan struct{}
202 read chan struct{}
203 more chan struct{}
204
205 mu sync.Mutex
206 // raw is the last of what the CLI printed; mark is where in raw the
207 // output after the last typed code starts; asked says the CLI asked
208 // again for a code before mark; link is the latest whole link.
209 raw []byte
210 mark int
211 asked bool
212 link string
213}
214
215// NewSetupToken reads the CLI's output on term from now on. The host
216// started it as `claude setup-token` with BROWSER a program that opens
217// nothing (provider.BuildSignInPolicy).
218func NewSetupToken(term Terminal) *SetupToken {
219 s := &SetupToken{term: term, exited: term.Done(), read: make(chan struct{}), more: make(chan struct{}, 1)}
220 go func() {
221 defer close(s.read)
222 buf := make([]byte, 8192)
223 defer clear(buf)
224 for {
225 n, err := term.Read(buf)
226 if n > 0 {
227 s.mu.Lock()
228 s.raw = append(s.raw, buf[:n]...)
229 if over := len(s.raw) - setupOutput; over > 0 {
230 kept := bytes.Clone(s.raw[over:])
231 clear(s.raw)
232 s.raw, s.mark = kept, max(0, s.mark-over)
233 }
234 s.mu.Unlock()
235 s.poke()
236 }
237 if err != nil {
238 return
239 }
240 }
241 }()
242 go func() {
243 <-s.exited
244 s.poke()
245 }()
246 return s
247}
248
249func (s *SetupToken) poke() {
250 select {
251 case s.more <- struct{}{}:
252 default:
253 }
254}
255
256// done reports whether the CLI has exited.
257func (s *SetupToken) done() bool {
258 select {
259 case <-s.exited:
260 return true
261 default:
262 return false
263 }
264}
265
266// settled waits, briefly, for the output of a CLI that exited.
267func (s *SetupToken) settled() {
268 select {
269 case <-s.read:
270 case <-time.After(time.Second):
271 }
272}
273
274// wait blocks until there is more output, the CLI exits, ctx ends or a
275// short tick passes.
276func (s *SetupToken) wait(ctx context.Context) error {
277 select {
278 case <-ctx.Done():
279 return ctx.Err()
280 case <-s.more:
281 case <-time.After(100 * time.Millisecond):
282 }
283 return nil
284}
285
286// URL waits for the authorize URL the CLI prints. ErrRefused: the CLI
287// exited before printing one.
288func (s *SetupToken) URL(ctx context.Context) (string, error) {
289 for {
290 ended := s.done()
291 if ended {
292 s.settled()
293 }
294 s.mu.Lock()
295 u, ok := authorizeIn(s.raw)
296 if ok {
297 s.link = u
298 }
299 s.mu.Unlock()
300 if ok {
301 return u, nil
302 }
303 if ended {
304 return "", ErrRefused
305 }
306 if err := s.wait(ctx); err != nil {
307 return "", err
308 }
309 }
310}
311
312// Submit types code into the CLI and presses Enter, once its prompt
313// shows (or after ten seconds). The caller clears code.
314func (s *SetupToken) Submit(ctx context.Context, code []byte) error {
315 deadline := time.Now().Add(10 * time.Second)
316 for time.Now().Before(deadline) {
317 s.mu.Lock()
318 text, _ := visible(s.raw[s.mark:])
319 shown := s.asked || bytes.Contains(text, []byte(promptText))
320 clear(text)
321 s.mu.Unlock()
322 if shown || s.done() {
323 break
324 }
325 if err := s.wait(ctx); err != nil {
326 return err
327 }
328 }
329 if s.done() {
330 return ErrRefused
331 }
332 s.mu.Lock()
333 s.mark, s.asked = len(s.raw), false
334 s.mu.Unlock()
335 if _, err := s.term.Write(code); err != nil {
336 return err
337 }
338 // Enter apart from the text, so it is a key press and not part of a
339 // paste.
340 select {
341 case <-ctx.Done():
342 return ctx.Err()
343 case <-time.After(150 * time.Millisecond):
344 }
345 _, err := s.term.Write([]byte{'\r'})
346 return err
347}
348
349// Result waits for what the CLI does with the code: a token (returned;
350// the caller clears it), a failure after which the CLI asks again while
351// it runs (CodeAgain; Link is then the link to show), or nothing more
352// (CodeEnded: it exited, or said the code failed and asked for no other
353// within giveUp). The pinned CLI (2.1.312, read statically) shows a
354// failed code as "OAuth error: ..." and waits for Enter to retry: for a
355// code it could not read, at the same link; for one the exchange
356// refused, in a new sign-in with a new link. Result presses Enter once
357// for it.
358func (s *SetupToken) Result(ctx context.Context) (string, []byte, error) {
359 var failed time.Time
360 pressed := false
361 for {
362 ended := s.done()
363 if ended {
364 s.settled()
365 }
366 s.mu.Lock()
367 text, _ := visible(s.raw[s.mark:])
368 s.mu.Unlock()
369 token := tokenIn(text, ended)
370 at := failedAt(text)
371 again := at >= 0 && bytes.Contains(text[at:], []byte(promptText))
372 clear(text)
373 switch {
374 case token != nil:
375 return CodeToken, token, nil
376 case ended:
377 return CodeEnded, nil, nil
378 case at >= 0 && failed.IsZero():
379 failed = time.Now()
380 }
381 if again {
382 // Asked again: let the screen settle, then hand the prompt
383 // back with the link it shows now.
384 if time.Since(failed) >= 500*time.Millisecond {
385 s.mu.Lock()
386 s.mark, s.asked = len(s.raw), true
387 if u, ok := lastAuthorize(s.raw); ok {
388 s.link = u
389 }
390 s.mu.Unlock()
391 return CodeAgain, nil, nil
392 }
393 } else if !failed.IsZero() && !pressed && time.Since(failed) >= time.Second {
394 // The error screen waits for Enter to retry.
395 pressed = true
396 if _, err := s.term.Write([]byte{'\r'}); err != nil {
397 return CodeEnded, nil, nil
398 }
399 } else if !failed.IsZero() && time.Since(failed) > giveUp {
400 return CodeEnded, nil, nil
401 }
402 if err := s.wait(ctx); err != nil {
403 return "", nil, err
404 }
405 }
406}
407
408// Link is the latest whole link the CLI printed.
409func (s *SetupToken) Link() string {
410 s.mu.Lock()
411 defer s.mu.Unlock()
412 return s.link
413}
414
415// lastAuthorize finds the last valid authorize URL in raw, as
416// authorizeIn finds the first.
417func lastAuthorize(raw []byte) (string, bool) {
418 text, links := visible(raw)
419 defer clear(text)
420 for i := len(links) - 1; i >= 0; i-- {
421 if u, ok := AuthorizeURL(links[i]); ok {
422 return u, true
423 }
424 }
425 locs := linkPattern.FindAllIndex(text, -1)
426 for i := len(locs) - 1; i >= 0; i-- {
427 if locs[i][1] == len(text) {
428 continue
429 }
430 if u, ok := AuthorizeURL(string(text[locs[i][0]:locs[i][1]])); ok {
431 return u, true
432 }
433 }
434 return "", false
435}
436
437// Done is closed once the CLI has exited, on its own or stopped.
438func (s *SetupToken) Done() <-chan struct{} { return s.exited }
439
440// Close stops the CLI and everything it started (Terminal.Stop: the
441// whole launch boundary, proven gone) and zeroes everything it printed.
442// An error says the boundary could not be proven gone: the caller keeps
443// what it would delete until recovery proves it.
444func (s *SetupToken) Close() error {
445 err := s.term.Stop()
446 select {
447 case <-s.read:
448 case <-time.After(2 * time.Second):
449 }
450 s.mu.Lock()
451 clear(s.raw)
452 s.raw, s.mark = nil, 0
453 s.mu.Unlock()
454 return err
455}
456