Connections: Claude sign-in by a link, 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 itself, on a pseudo-terminal in the connection's new home with the login environment and a no-op BROWSER, and shows the authorize URL it prints (prompt kind authorize_link, parsed through ANSI, OSC 8 and redraws, only https claude.com or claude.ai with the code-page redirect). The page seals the code Anthropic shows to the runner's key, bound to the code endpoint and the card's attempt; the runner records the box in seen_seals, types the code into the waiting CLI and keeps the token it prints exactly as a pasted token (0600 .oauth-token, committed with the attempt turned kind token), then probes, binds and checks it with one real request before reporting healthy. A wrong code is said on the card: the same link while the CLI asks again, a new one when it had to start again. The CLI's own expiry and the CLI dying start it again with a new link (bounded); cancel and the attempt's limit kill its process group and remove the home. A stop before the token is committed ends the attempt runner_offline with its home deleted at restart; after, the attempt carries on as a token one. The terminal card and its watcher are gone; the chooser's Claude is the sign-in by a link, with "Paste a token you already have" beside it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 files changed,
+2,199
−199
internal/equipo/chat/connections.go+61 −15internal/equipo/chat_connections.go+8 −8internal/equipo/connections_view.go+8 −2internal/equipo/copy.go+10 −8internal/equipo/static/connections.js+30 −19internal/equipo/templates/models.html+18 −13internal/fakeclaude/fake.go+4 −0internal/fakeclaude/setuptoken.go+158 −0internal/headless/connections_test.go+2 −28internal/headless/signin_test.go+183 −0internal/runner/connect/setuptoken.go+425 −0internal/runner/connect/setuptoken_test.go+94 −0internal/runner/provider/token.go+11 −0internal/runner/thin/connector.go+13 −44internal/runner/thin/signin.go+318 −0internal/runner/thin/signin_test.go+516 −0internal/runner/thin/token.go+79 −49internal/thintest/connections_contract_test.go+4 −3internal/thintest/signin_contract_test.go+219 −0internal/wire/connections.go+33 −7internal/wire/connections_test.go+1 −1internal/wire/wiretest/fixtures.go+2 −2internal/wire/wiretest/testdata/api/connection-code.json+1 −0internal/wire/wiretest/testdata/api/connection-signing-in-claude.json+1 −0
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index 5b3b7f3e..ed937045 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -118,7 +118,7 @@ func (t *txn) saveConnection(r *connectionRecord, fresh bool) error { |
| r.CreatedAt = r.UpdatedAt |
| err = t.db.Create(r).Error |
| } else { |
| - err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at", "expires_at", "expires_estimated").Updates(r).Error |
| + err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("kind", "local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at", "expires_at", "expires_estimated").Updates(r).Error |
| } |
| if err != nil { |
| return err |
| @@ -229,6 +229,11 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error { |
| if r.State != wire.ConnConnecting { |
| return nil |
| } |
| + if v.State == wire.ConnHealthy && signingIn(r) { |
| + // Claude's sign-in by the runner's setup-token made a token |
| + // connection. |
| + r.Kind = wire.KindToken |
| + } |
| r.State, r.Reason = v.State, v.Reason |
| if v.Label != "" { |
| r.Label = v.Label |
| @@ -268,6 +273,26 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error { |
| return t.saveConnection(&r, false) |
| } |
| +// promptOf is a record's prompt (nil: none). |
| +func promptOf(r connectionRecord) *wire.ConnectPrompt { |
| + if r.Prompt == "" { |
| + return nil |
| + } |
| + var p wire.ConnectPrompt |
| + if json.Unmarshal([]byte(r.Prompt), &p) != nil { |
| + return nil |
| + } |
| + return &p |
| +} |
| + |
| +// signingIn says a connecting record is Claude's sign-in by the runner's |
| +// own setup-token (wire.PromptAuthorize), whose prompt it keeps until it |
| +// ends. |
| +func signingIn(r connectionRecord) bool { |
| + p := promptOf(r) |
| + return r.Provider == wire.ProviderClaude && r.Kind == wire.KindSubscription && p != nil && p.Kind == wire.PromptAuthorize |
| +} |
| + |
| // forgetSignedOut removes the person's signed-out records of one account |
| // (provider and label), except keep, each with its last event. |
| func (t *txn) forgetSignedOut(person, provider, label, keep string) error { |
| @@ -402,11 +427,12 @@ func (s *Store) Connection(ctx context.Context, person, id string) (out wire.Con |
| // StartConnection starts a connection attempt on the person's runner (spec §2.1): |
| // a Codex account by device code; a Claude account by the CLI's own |
| // sign-in, finished at the runner's machine (loopback, no paste) or, when |
| -// the person's browser is elsewhere, by `equipo-runner login claude` in |
| -// a terminal there; or a Claude account from a pasted setup token (kind |
| -// token), sealed in the app to the runner (SendSecret). Nothing the |
| -// instance can read passes through it either way. A second attempt for |
| -// the same provider while one is connecting returns that one. |
| +// the person's browser is elsewhere, by the runner's own `claude |
| +// setup-token` whose sign-in code the page seals to the runner |
| +// (wire.PromptAuthorize, SendSecret); or a Claude account from a pasted |
| +// setup token (kind token), sealed the same way. Nothing the instance |
| +// can read passes through it either way. A second attempt for the same |
| +// provider while one is connecting returns that one. |
| func (s *Store) StartConnection(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) { |
| token := in.Kind == wire.KindToken |
| if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription && !token || token && (in.Provider != wire.ProviderClaude || in.SameMachine) { |
| @@ -441,9 +467,9 @@ func (s *Store) StartConnection(ctx context.Context, person string, in wire.Conn |
| // The token card: run the command anywhere, approve, paste. |
| r.Kind, r.Prompt = wire.KindToken, asJSON(wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"}) |
| } else if in.Provider == wire.ProviderClaude && !in.SameMachine { |
| - // The honest card: Claude's sign-in finishes on the runner's |
| - // machine. The runner watches for the terminal login. |
| - r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptTerminal, Code: "equipo-runner login claude"}) |
| + // Claude with no terminal: the runner starts setup-token and |
| + // reports its link; until then the card says it is starting. |
| + r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptAuthorize}) |
| } |
| if err := t.saveConnection(&r, true); err != nil { |
| return err |
| @@ -536,7 +562,10 @@ func (s *Store) SignOut(ctx context.Context, person, id string) (out wire.Connec |
| // beside it names this attempt (its runner, Claude's endpoint, attempt |
| // 1, a short expiry) and that the box is a size a sealed token can be. |
| // One box per attempt: the attempt's token prompt goes with it, so the |
| -// card waits for the runner. The box is in no event, response or log |
| +// card waits for the runner. A sign-in code (wire.EndpointClaudeCode) |
| +// goes the same way to a sign-in attempt, one box per prompt: its |
| +// attempt is the one the card shows, and the card's link goes with it |
| +// until the runner asks again. The box is in no event, response or log |
| // line, and leaves the mailbox once the runner acks it. |
| func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Sealed) (out wire.Connection, err error) { |
| if !sealedShape(in, s.now()) { |
| @@ -552,13 +581,28 @@ func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Seale |
| } else if err != nil { |
| return err |
| } |
| - if in.RunnerID != r.RunnerID || in.ConnectionID != r.ID || in.Provider != r.Provider || r.Kind != wire.KindToken { |
| + if in.RunnerID != r.RunnerID || in.ConnectionID != r.ID || in.Provider != r.Provider { |
| return ErrInvalid |
| } |
| - if r.State != wire.ConnConnecting || r.Prompt == "" { |
| - return ErrConflict |
| + if in.Endpoint == wire.EndpointClaudeCode { |
| + if r.Provider != wire.ProviderClaude || r.Kind != wire.KindSubscription { |
| + return ErrInvalid |
| + } |
| + p := promptOf(r) |
| + if r.State != wire.ConnConnecting || p == nil || p.Kind != wire.PromptAuthorize || p.URL == "" || p.Attempt != in.Attempt { |
| + return ErrConflict |
| + } |
| + // The card waits for the runner: no link until it asks again. |
| + r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptAuthorize, Attempt: in.Attempt}) |
| + } else { |
| + if r.Kind != wire.KindToken { |
| + return ErrInvalid |
| + } |
| + if r.State != wire.ConnConnecting || r.Prompt == "" { |
| + return ErrConflict |
| + } |
| + r.Prompt = "" |
| } |
| - r.Prompt = "" |
| if err := t.saveConnection(&r, false); err != nil { |
| return err |
| } |
| @@ -570,7 +614,9 @@ func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Seale |
| // sealedShape checks what can be checked of a box without opening it. |
| func sealedShape(in wire.Sealed, now time.Time) bool { |
| - if in.Provider != wire.ProviderClaude || in.Endpoint != wire.EndpointAnthropic || in.Attempt != 1 || len(in.Box) > wire.MaxSealedBytes { |
| + token := in.Endpoint == wire.EndpointAnthropic && in.Attempt == 1 |
| + code := in.Endpoint == wire.EndpointClaudeCode && in.Attempt >= 1 && in.Attempt <= wire.MaxCodeAttempts |
| + if in.Provider != wire.ProviderClaude || !token && !code || len(in.Box) > wire.MaxSealedBytes { |
| return false |
| } |
| // The runner allows a minute of clock skew past the TTL; so does this. |
diff --git a/internal/equipo/chat_connections.go b/internal/equipo/chat_connections.go| index 9dde2b50..f5a26614 100644 |
| --- a/internal/equipo/chat_connections.go |
| +++ b/internal/equipo/chat_connections.go |
| @@ -32,14 +32,15 @@ type modelLine struct { |
| Kind string |
| Connecting bool |
| Prompt *wire.ConnectPrompt |
| - // A token card seals to RunnerID's SealKey ("" when the runner has |
| - // none to give) for Endpoint. |
| + // SignIn: Claude's sign-in by the runner's own setup-token, whose |
| + // code the card seals (wire.PromptAuthorize). |
| + SignIn bool |
| + // A token or sign-in card seals to RunnerID's SealKey ("" when the |
| + // runner has none to give) for Endpoint. |
| RunnerID, SealKey, Endpoint string |
| // Phrases are the loading line's rotating words while the runner has |
| // not yet shown the provider's sign-in. |
| Phrases string |
| - // Runner names the machine a terminal sign-in finishes on. |
| - Runner string |
| } |
| type modelsView struct { |
| @@ -231,9 +232,8 @@ func (a *application) connectionsPageFor(w http.ResponseWriter, r *http.Request, |
| render(w, "models", data) |
| } |
| -// connectionsStart is Add Codex, Add Claude (a pasted token, or the |
| -// sign-in on the runner), "I am at this machine" and a row's Sign in |
| -// again or Paste a new token. |
| +// connectionsStart is Add Codex, Add Claude (the sign-in by a link, or |
| +// a pasted token) and a row's Sign in again or Paste a new token. |
| func (a *application) connectionsStart(w http.ResponseWriter, r *http.Request) { |
| a.chatActionTo(w, r, "/conversation/settings/connections/add", func(ctx context.Context, address string) error { |
| provider, same := r.PostFormValue("provider"), r.PostFormValue("same_machine") == "1" |
| @@ -242,7 +242,7 @@ func (a *application) connectionsStart(w http.ResponseWriter, r *http.Request) { |
| kind = wire.KindToken |
| } |
| // The card open gives way to the other way of connecting: the |
| - // sign-in at this machine, a token, or the sign-in on the runner. |
| + // sign-in by a link, a token, or the sign-in at this machine. |
| conns, err := a.store.Chat().Connections(ctx, address) |
| if err != nil { |
| return err |
diff --git a/internal/equipo/connections_view.go b/internal/equipo/connections_view.go| index ff5aa90d..9732c93b 100644 |
| --- a/internal/equipo/connections_view.go |
| +++ b/internal/equipo/connections_view.go |
| @@ -94,11 +94,17 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| for _, c := range snap.Connections { |
| switch { |
| case c.State == wire.ConnConnecting: |
| - line := modelLine{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Kind: c.Kind, Connecting: true, Prompt: c.Prompt, Runner: runner, RunnerID: c.RunnerID, Endpoint: wire.EndpointAnthropic} |
| + line := modelLine{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Kind: c.Kind, Connecting: true, Prompt: c.Prompt, RunnerID: c.RunnerID, Endpoint: wire.EndpointAnthropic} |
| if c.RunnerID == snap.Runner.ID { |
| line.SealKey = snap.Runner.SealKey |
| } |
| - if c.Prompt == nil && c.Kind != wire.KindToken { |
| + line.SignIn = c.Prompt != nil && c.Prompt.Kind == wire.PromptAuthorize && c.Kind != wire.KindToken |
| + if line.SignIn { |
| + line.Endpoint = wire.EndpointClaudeCode |
| + } |
| + // Loading: nothing from the runner yet (a sign-in with no link |
| + // and no code sent is starting its CLI). |
| + if c.Prompt == nil && c.Kind != wire.KindToken || line.SignIn && c.Prompt.URL == "" && c.Prompt.Attempt == 0 { |
| line.Phrases = loadingPhrases(c.Provider) |
| } |
| v.Attempts = append(v.Attempts, line) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 4c73bc3b..b8914c32 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -696,7 +696,6 @@ var pageCopy = map[string]string{ |
| "chat.connections.add_codex": "Add Codex", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.add_claude": "Add Claude", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.connecting": "Connecting %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.same_machine": "I am at this machine", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.cancel": "Cancel", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.healthy": "Ready", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.limited": "Limited, no reset time reported", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| @@ -721,9 +720,6 @@ var pageCopy = map[string]string{ |
| "chat.connections.device_off": "OpenAI says device sign-in is off? Turn it on in ChatGPT, Settings, Security.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.copy": "Copy", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.copied": "Copied", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.open_terminal": "Open a terminal on %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.run": "Run:", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.browser_back": "Sign in in the browser it opens, then come back.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.waiting_sign_in": "Waiting for you to sign in…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.open_claude": "Open Claude", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.claude_back": "Sign in, then come back. Equipo connects on its own.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| @@ -790,8 +786,6 @@ var pageCopy = map[string]string{ |
| "chat.connections.code_once": "Shown once. It expires in 15 minutes.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.codex_fine": "Nothing but the code OpenAI generated passes through Equipo.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.claude_fine": "The sign-in happens inside Claude Code itself. Equipo never sees the code or the token.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.same_machine_hint": "At the runner's machine? Sign in with one tap instead.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.waiting_runner": "Waiting for the sign-in to finish on %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.connected_big": "%s is connected", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.connected_next": "Your coordinator can use it from the next message.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.empty_title": "Equipo works through the accounts you already have", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| @@ -803,8 +797,7 @@ var pageCopy = map[string]string{ |
| "chat.connections.loading_claude_1": "Finding your runner…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.loading_claude_2": "Warming up a fresh desk for Claude…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.loading_claude_3": "Starting Claude's own sign-in…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.paste_token": "Paste a token", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.sign_in_instead": "Or sign in on the runner instead", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.sign_in_instead": "Or sign in at Anthropic instead", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_sub": "Your Claude subscription, with a token from Claude Code.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_run": "On any computer with Claude Code, run", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_approve": "Approve in the browser.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| @@ -821,6 +814,15 @@ var pageCopy = map[string]string{ |
| "chat.connections.token_new": "Paste a new token", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_rejected": "This token was rejected. Run claude setup-token again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.copy_link": "Copy link", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.sign_in_how": "Sign in at Anthropic", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.paste_token_instead": "Paste a token you already have", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.open_anthropic": "Open Anthropic", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.code_paste": "Paste the code Anthropic shows you", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.code_wrong": "That code did not work. Open Anthropic again and paste the new code.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.code_bad": "That is not the code. Copy the whole code from Anthropic's page.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.code_failed": "That did not go through. Paste the code again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.code_no_key": "Your runner needs an update before it can take a code.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.waiting_code": "Your runner is finishing the sign-in…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.switched": "Switched to %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.switched_reset": "Switched to %s; %s resets %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.no_connection": "Nothing can answer right now. %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/static/connections.js b/internal/equipo/static/connections.js| index 689e5b2b..35175f37 100644 |
| --- a/internal/equipo/static/connections.js |
| +++ b/internal/equipo/static/connections.js |
| @@ -117,14 +117,16 @@ |
| var seen = {}; |
| box.querySelectorAll("[data-connection]").forEach(function (el) { seen[el.dataset.connection] = true; }); |
| next.querySelectorAll("[data-connection]").forEach(function (el) { if (seen[el.dataset.connection]) el.setAttribute("data-settled", ""); }); |
| - // A token card being typed into stays as it is: the same field, |
| - // its value and its focus. |
| + // A token or code card being typed into stays as it is: the same |
| + // field, its value and its focus, while the runner asks for the |
| + // same attempt. |
| var typing = null; |
| - box.querySelectorAll("[data-token-form]").forEach(function (form) { |
| - var field = form.querySelector("[data-token-field]"); |
| + box.querySelectorAll("[data-token-form], [data-code-form]").forEach(function (form) { |
| + var field = form.querySelector("[data-token-field], [data-code-field]"); |
| var card = form.closest("[data-connecting]"); |
| - var same = card && next.querySelector('[data-connecting][data-connection="' + CSS.escape(card.dataset.connection) + '"] [data-token-form]'); |
| - if (same && !form.closest("[data-token-steps]").hidden && (field.value || document.activeElement === field)) { |
| + var same = card && next.querySelector('[data-connecting][data-connection="' + CSS.escape(card.dataset.connection) + '"] :is([data-token-form], [data-code-form])'); |
| + var other = same && same.closest("[data-connecting]"); |
| + if (same && other.dataset.attempt === card.dataset.attempt && !form.closest("[data-token-steps], [data-code-steps]").hidden && (field.value || document.activeElement === field)) { |
| card.setAttribute("data-settled", ""); |
| same.closest("[data-connecting]").replaceWith(card); |
| if (document.activeElement === field) typing = field; |
| @@ -182,34 +184,43 @@ |
| else select(); |
| }); |
| - // A Claude token: checked here, sealed here to the runner's seal key |
| - // (seal.js) and posted as the box with its clear binding. The field is |
| - // cleared at once; the token is never shown, kept or sent in the clear. |
| + // A Claude token, or the one-time code of Claude's sign-in: checked |
| + // here, sealed here to the runner's seal key (seal.js) and posted as |
| + // the box with its clear binding. A token is bound to Anthropic's API |
| + // and attempt 1; a code to the code page and the attempt its card |
| + // shows. The field is cleared at once; neither is ever shown, kept or |
| + // sent in the clear. |
| var TOKEN = /^sk-ant-oat[0-9A-Za-z_-]{8,500}$/; |
| - function sealToken(form) { |
| + var CODE = /^[!-~]{8,1024}$/; |
| + function sealSecret(form) { |
| var card = form.closest("[data-connecting]"); |
| - var field = form.querySelector("[data-token-field]"); |
| + var code = form.matches("[data-code-form]"); |
| + var field = form.querySelector(code ? "[data-code-field]" : "[data-token-field]"); |
| var note = form.querySelector("[data-token-note]"); |
| - var token = field.value.trim(); |
| + var wrong = form.querySelector("[data-code-wrong]"); |
| + var secret = field.value.trim(); |
| field.value = ""; |
| function say(key) { |
| + if (wrong) wrong.hidden = true; |
| note.textContent = note.dataset[key]; |
| note.setAttribute("data-tone", "bad"); |
| note.hidden = false; |
| field.focus(); |
| } |
| - if (!TOKEN.test(token)) { token = ""; say("bad"); return; } |
| + var good = code ? CODE.test(secret) && secret.indexOf("sk-ant") < 0 : TOKEN.test(secret); |
| + if (!good) { secret = ""; say("bad"); return; } |
| var d = card.dataset; |
| - if (!d.sealKey || !window.EquipoSeal || !window.TextEncoder) { token = ""; say("noKey"); return; } |
| - var clear = { runner_id: d.runner, connection_id: d.connection, provider: d.provider, endpoint: d.endpoint, attempt: 1, expires_at: new Date(Date.now() + 10 * 60 * 1000).toISOString() }; |
| - var message = new TextEncoder().encode(JSON.stringify(Object.assign({ secret: token }, clear))); |
| - token = ""; |
| + var attempt = code ? Number(d.attempt) : 1; |
| + if (!d.sealKey || !window.EquipoSeal || !window.TextEncoder || !(attempt >= 1)) { secret = ""; say("noKey"); return; } |
| + var clear = { runner_id: d.runner, connection_id: d.connection, provider: d.provider, endpoint: d.endpoint, attempt: attempt, expires_at: new Date(Date.now() + 10 * 60 * 1000).toISOString() }; |
| + var message = new TextEncoder().encode(JSON.stringify(Object.assign({ secret: secret }, clear))); |
| + secret = ""; |
| var box; |
| try { box = window.EquipoSeal.seal(d.sealKey, message); } catch (e) { box = ""; } |
| message.fill(0); |
| if (!box) { say("noKey"); return; } |
| note.hidden = true; |
| - var steps = card.querySelector("[data-token-steps]"), waiting = card.querySelector("[data-token-waiting]"); |
| + var steps = card.querySelector("[data-token-steps], [data-code-steps]"), waiting = card.querySelector("[data-token-waiting]"); |
| if (steps) steps.hidden = true; |
| if (waiting) waiting.hidden = false; |
| fetch("/conversation/connections/" + encodeURIComponent(d.connection) + "/secret", { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify(Object.assign({ box: box }, clear)) }) |
| @@ -229,7 +240,7 @@ |
| if (!form.matches || !form.matches("form")) return; |
| if (!adding && form.matches("[data-add-form]")) return; |
| event.preventDefault(); |
| - if (form.matches("[data-token-form]")) { sealToken(form); return; } |
| + if (form.matches("[data-token-form], [data-code-form]")) { sealSecret(form); return; } |
| // An ended attempt's note goes once dismissed, or once a new |
| // attempt starts. |
| var note = form.closest("[data-connection-note]"); |
diff --git a/internal/equipo/templates/models.html b/internal/equipo/templates/models.html| index 33384eec..8f136478 100644 |
| --- a/internal/equipo/templates/models.html |
| +++ b/internal/equipo/templates/models.html |
| @@ -6,11 +6,23 @@ |
| {{define "conn-copy"}}<button type="button" rst-btn data-copy="{{.}}" data-copied="{{copy "chat.connections.copied"}}">{{copy "chat.connections.copy"}}</button>{{end}} |
| {{define "conn-copy-link"}}<button type="button" rst-btn data-copy="{{.}}" data-copy-link data-copied="{{copy "chat.connections.copied"}}">{{copy "chat.connections.copy_link"}}</button>{{end}} |
| {{define "conn-sign-in-instead"}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="subscription"><button equipo-link type="submit" data-sign-in-instead>{{copy "chat.connections.sign_in_instead"}}</button></form>{{end}} |
| +{{define "conn-paste-instead"}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="token"><button equipo-link type="submit" data-paste-instead>{{copy "chat.connections.paste_token_instead"}}</button></form>{{end}} |
| {{define "conn-waiting"}}<p equipo-conn-waiting aria-live="polite">{{template "conn-star"}}<span>{{.}}</span></p>{{end}} |
| {{define "conn-cancel"}}<form method="post" action="/conversation/connections/{{.}}/cancel" equipo-inline-form><button rst-btn data-quiet type="submit" data-connection-cancel>{{copy "chat.connections.cancel"}}</button></form>{{end}} |
| -{{define "conn-attempt"}}<div equipo-conn-card data-connection="{{.ID}}" data-connecting data-provider="{{.Provider}}"{{if eq .Kind "token"}} data-kind="token" data-runner="{{.RunnerID}}" data-endpoint="{{.Endpoint}}"{{with .SealKey}} data-seal-key="{{.}}"{{end}}{{end}}> |
| -<div equipo-conn-card-head>{{template "conn-mark" .Provider}}<div><h3>{{if eq .Provider "codex"}}{{copy "chat.connections.title_codex"}}{{else}}{{copy "chat.connections.title_claude"}}{{end}}</h3><p>{{if eq .Kind "token"}}{{copy "chat.connections.token_sub"}}{{else if not .Prompt}}{{copy "chat.connections.loading_sub"}}{{else if eq .Provider "codex"}}{{copy "chat.connections.codex_sub"}}{{else}}{{copy "chat.connections.claude_sub"}}{{end}}</p></div></div> |
| -{{if and (not .Prompt) (eq .Kind "token")}}{{template "conn-waiting" (copy "chat.connections.waiting_token")}} |
| +{{define "conn-attempt"}}<div equipo-conn-card data-connection="{{.ID}}" data-connecting data-provider="{{.Provider}}"{{if eq .Kind "token"}} data-kind="token" data-runner="{{.RunnerID}}" data-endpoint="{{.Endpoint}}"{{with .SealKey}} data-seal-key="{{.}}"{{end}}{{else if .SignIn}} data-kind="sign_in" data-runner="{{.RunnerID}}" data-endpoint="{{.Endpoint}}" data-attempt="{{.Prompt.Attempt}}"{{with .SealKey}} data-seal-key="{{.}}"{{end}}{{end}}> |
| +<div equipo-conn-card-head>{{template "conn-mark" .Provider}}<div><h3>{{if eq .Provider "codex"}}{{copy "chat.connections.title_codex"}}{{else}}{{copy "chat.connections.title_claude"}}{{end}}</h3><p>{{if eq .Kind "token"}}{{copy "chat.connections.token_sub"}}{{else if .Phrases}}{{copy "chat.connections.loading_sub"}}{{else if eq .Provider "codex"}}{{copy "chat.connections.codex_sub"}}{{else}}{{copy "chat.connections.claude_sub"}}{{end}}</p></div></div> |
| +{{if .SignIn}}{{if .Phrases}}<div equipo-conn-loading data-loading data-phrases="{{.Phrases}}">{{template "conn-star"}}<p data-phrase>{{index (split .Phrases "|") 0}}</p></div> |
| +<div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div> |
| +{{else if .Prompt.URL}}<ol equipo-conn-steps data-code-steps> |
| +<li><div equipo-conn-link-row><a rst-btn="primary" href="{{.Prompt.URL}}" rel="noopener" target="_blank" data-open-anthropic>{{icon "external-link"}}{{copy "chat.connections.open_anthropic"}}</a>{{template "conn-copy-link" .Prompt.URL}}</div></li> |
| +<li><div><form equipo-conn-token data-code-form autocomplete="off"><label for="code-{{.ID}}">{{copy "chat.connections.code_paste"}}</label>{{if .Prompt.WrongCode}}<span equipo-conn-small data-code-wrong data-tone="bad" role="status">{{copy "chat.connections.code_wrong"}}</span>{{end}}<span equipo-conn-token-row><input rst-input id="code-{{.ID}}" type="password" data-code-field autocomplete="off" autocapitalize="off" spellcheck="false" required><button rst-btn="primary" type="submit" data-code-connect>{{copy "chat.connections.token_connect"}}</button></span><span equipo-conn-small data-token-trust>{{copy "chat.connections.token_sealed"}}</span><span equipo-conn-small data-token-note role="status" hidden data-bad="{{copy "chat.connections.code_bad"}}" data-failed="{{copy "chat.connections.code_failed"}}" data-no-key="{{copy "chat.connections.code_no_key"}}"></span></form></div></li> |
| +</ol> |
| +<div data-token-waiting hidden>{{template "conn-waiting" (copy "chat.connections.waiting_code")}}</div> |
| +<div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-paste-instead"}}</span>{{template "conn-cancel" .ID}}</div> |
| +{{else}}{{template "conn-waiting" (copy "chat.connections.waiting_code")}} |
| +<p equipo-conn-small>{{copy "chat.connections.token_sealed"}}</p> |
| +<div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div> |
| +{{end}}{{else if and (not .Prompt) (eq .Kind "token")}}{{template "conn-waiting" (copy "chat.connections.waiting_token")}} |
| <p equipo-conn-small>{{copy "chat.connections.token_sealed"}}</p> |
| <div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div> |
| {{else if not .Prompt}}<div equipo-conn-loading data-loading data-phrases="{{.Phrases}}">{{template "conn-star"}}<p data-phrase>{{index (split .Phrases "|") 0}}</p></div> |
| @@ -36,18 +48,11 @@ |
| </ol> |
| <div data-token-waiting hidden>{{template "conn-waiting" (copy "chat.connections.waiting_token")}}</div> |
| <div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-sign-in-instead"}}</span>{{template "conn-cancel" .ID}}</div> |
| -{{else if eq .Prompt.Kind "terminal"}}<ol equipo-conn-steps data-finish-on> |
| -<li><div><p><strong>{{printf (copy "chat.connections.open_terminal") .Runner}}</strong></p></div></li> |
| -<li><div><p>{{copy "chat.connections.run"}}</p><div equipo-conn-code-row><code equipo-conn-code data-command>{{.Prompt.Code}}</code>{{template "conn-copy" .Prompt.Code}}</div></div></li> |
| -<li><div><p>{{copy "chat.connections.browser_back"}}</p></div></li> |
| -</ol> |
| -{{template "conn-waiting" (printf (copy "chat.connections.waiting_runner") .Runner)}} |
| -<p equipo-conn-small>{{copy "chat.connections.claude_fine"}}</p> |
| -<div equipo-conn-card-foot><span equipo-conn-small>{{copy "chat.connections.same_machine_hint"}} <form method="post" action="/conversation/connections" equipo-inline-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="same_machine" value="1"><button equipo-link type="submit" data-same-machine>{{copy "chat.connections.same_machine"}}</button></form></span>{{template "conn-cancel" .ID}}</div> |
| +{{else}}<div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div> |
| {{end}}</div>{{end}} |
| {{define "conn-chooser"}}<div equipo-conn-chooser role="group" aria-label="{{copy "chat.connections.add"}}"> |
| -<form method="post" action="/conversation/connections" data-add-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="token"><button type="submit" equipo-conn-opt data-add="claude">{{template "conn-mark" "claude"}}<span><span equipo-conn-opt-name>Claude</span><span equipo-conn-opt-desc>{{copy "chat.connections.claude_desc"}}</span><span equipo-conn-opt-how data-paste-token>{{copy "chat.connections.paste_token"}}</span></span>{{icon "chevron-right"}}</button></form> |
| -<div equipo-conn-alt>{{template "conn-sign-in-instead"}}</div> |
| +<form method="post" action="/conversation/connections" data-add-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="subscription"><button type="submit" equipo-conn-opt data-add="claude">{{template "conn-mark" "claude"}}<span><span equipo-conn-opt-name>Claude</span><span equipo-conn-opt-desc>{{copy "chat.connections.claude_desc"}}</span><span equipo-conn-opt-how data-sign-in-how>{{copy "chat.connections.sign_in_how"}}</span></span>{{icon "chevron-right"}}</button></form> |
| +<div equipo-conn-alt>{{template "conn-paste-instead"}}</div> |
| <form method="post" action="/conversation/connections" data-add-form><input type="hidden" name="provider" value="codex"><button type="submit" equipo-conn-opt data-add="codex">{{template "conn-mark" "codex"}}<span><span equipo-conn-opt-name>Codex</span><span equipo-conn-opt-desc>{{copy "chat.connections.codex_desc"}}</span></span>{{icon "chevron-right"}}</button></form> |
| <p equipo-conn-sep>{{copy "chat.connections.soon"}}</p> |
| <button type="button" equipo-conn-opt disabled>{{template "conn-mark" "local"}}<span><span equipo-conn-opt-name>{{copy "chat.connections.local"}}</span><span equipo-conn-opt-desc>{{copy "chat.connections.local_desc"}}</span></span><span equipo-conn-soon>{{copy "chat.connections.soon"}}</span></button> |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index 89251d72..78565041 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -73,6 +73,7 @@ |
| // Token's is refused as an authentication failure, and so is a turn in |
| // a home with neither a token nor a login file. A token anywhere in |
| // argv exits 3 at once. A reply on a token ends "(signed in by token)". |
| +// `setup-token` (setuptoken.go) makes such a token from a sign-in code. |
| package fakeclaude |
| import ( |
| @@ -116,6 +117,9 @@ func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { |
| fmt.Fprintln(stdout, Version+" (Claude Code)") |
| return 0 |
| } |
| + if len(args) >= 1 && args[0] == "setup-token" { |
| + return setupToken(args, stdin, stdout) |
| + } |
| if len(args) >= 3 && args[0] == "auth" && args[2] == "--help" { |
| return 0 |
| } |
diff --git a/internal/fakeclaude/setuptoken.go b/internal/fakeclaude/setuptoken.go| new file mode 100644 |
| index 00000000..3cb36d3c |
| --- /dev/null |
| +++ b/internal/fakeclaude/setuptoken.go |
| @@ -0,0 +1,158 @@ |
| +package fakeclaude |
| + |
| +import ( |
| + "bufio" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "fmt" |
| + "io" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "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 > ". What follows a code was |
| +// not observed; the fake prints the token after a right code and an |
| +// error after a wrong one, then asks again (or exits, steered). |
| +// |
| +// 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. |
| +// |
| +// Steering, from SetupSteerFile beside the binary, one word a line: |
| +// "fail_start" exits before any URL; "exit_on_wrong" exits after a wrong |
| +// code; "expire_ms=<n>" exits when no code came within n ms (the CLI's |
| +// own expiry). 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 |
| + } |
| + 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) |
| + } |
| + 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) |
| + } |
| + 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) |
| + mid, got, ok := strings.Cut(code, "#") |
| + email, err := hex.DecodeString(strings.TrimPrefix(mid, "fakecode-")) |
| + if ok && got == state && strings.HasPrefix(mid, "fakecode-") && err == nil { |
| + 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[1m" + Token(string(email)) + "\x1b[22m\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") |
| + return 0 |
| + } |
| + out("\r\n\x1b[31mOAuth error: Invalid code. Please make sure the full code was copied.\x1b[39m\r\n") |
| + if _, ok := steer["exit_on_wrong"]; ok { |
| + return 1 |
| + } |
| + out("\r\n\x1b[1mPaste code here if prompted >\x1b[22m ") |
| + } |
| +} |
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go| index 9be3cdd7..1343eef1 100644 |
| --- a/internal/headless/connections_test.go |
| +++ b/internal/headless/connections_test.go |
| @@ -1,14 +1,12 @@ |
| package headless |
| import ( |
| - "context" |
| "crypto/rand" |
| "encoding/json" |
| "fmt" |
| "net/http" |
| "net/url" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strings" |
| "testing" |
| @@ -17,7 +15,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/fakeclaude" |
| "amadan.net/oficina/equipo/internal/fakecodex" |
| "amadan.net/oficina/equipo/internal/runner" |
| - "amadan.net/oficina/equipo/internal/runner/thin" |
| "amadan.net/oficina/equipo/internal/testci" |
| "amadan.net/oficina/equipo/internal/thintest" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -279,11 +276,10 @@ func connCodexDeviceCode(t *testing.T, env *Env, inst *thintest.Instance, r *loc |
| } |
| } |
| -// C4: a second Claude account. At the runner's machine: the card links to |
| +// C4: a second Claude account at the runner's machine: the card links to |
| // Anthropic's sign-in page, whose redirect is the CLI's own loopback |
| // listener (simulated here by the browser's callback); nothing is pasted |
| -// anywhere. Elsewhere: the honest terminal card, which turns healthy when |
| -// `equipo-runner login claude` finishes there. |
| +// anywhere. (Elsewhere, the sign-in by a link: TestHeadlessClaudeSignIn.) |
| func connClaudeSignIn(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| r.start(t) |
| s := open(t, env) |
| @@ -317,28 +313,6 @@ func connClaudeSignIn(t *testing.T, env *Env, inst *thintest.Instance, r *localR |
| v := cv.Connections[c.ID] |
| return v.State == wire.ConnHealthy && v.LocalID == "claude-2" && v.Label == second |
| }) |
| - // Browser elsewhere: the terminal card. |
| - c2, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "claude"}) |
| - if err != nil || c2.Prompt == nil || c2.Prompt.Kind != wire.PromptTerminal { |
| - t.Fatalf("terminal card %+v %v", c2, err) |
| - } |
| - page := inst.Get(t, "/conversation/settings/connections/add") |
| - if !strings.Contains(page, "data-finish-on") || !strings.Contains(page, "equipo-runner login claude") || !strings.Contains(page, "data-same-machine") { |
| - t.Fatal("terminal card not on the page") |
| - } |
| - // `equipo-runner login claude` in a terminal on the runner's machine. |
| - err = thin.Login(context.Background(), r.cfg, "claude", thin.LoginOptions{Root: filepath.Join(r.root, "accounts"), Output: &strings.Builder{}, Command: func(ctx context.Context, binary string, args []string, dir string, env []string) error { |
| - cmd := exec.CommandContext(ctx, binary, args...) |
| - cmd.Dir, cmd.Env = dir, append(env, "FAKE_LOGIN_EMAIL=third@example.com") |
| - return cmd.Run() |
| - }}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - s.wait(t, "terminal sign-in seen", time.Minute, func(cv *thintest.Conversation) bool { |
| - v := cv.Connections[c2.ID] |
| - return v.State == wire.ConnHealthy && v.Label == "third@example.com" |
| - }) |
| var _ runner.Config |
| } |
diff --git a/internal/headless/signin_test.go b/internal/headless/signin_test.go| new file mode 100644 |
| index 00000000..8743efa4 |
| --- /dev/null |
| +++ b/internal/headless/signin_test.go |
| @@ -0,0 +1,183 @@ |
| +package headless |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "io/fs" |
| + "log/slog" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/fakeclaude" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/thintest" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// syncBuffer is a log several goroutines write to. |
| +type syncBuffer struct { |
| + mu sync.Mutex |
| + b bytes.Buffer |
| +} |
| + |
| +func (s *syncBuffer) Write(p []byte) (int, error) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.b.Write(p) |
| +} |
| + |
| +func (s *syncBuffer) String() string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.b.String() |
| +} |
| + |
| +// Claude with no terminal, end to end through the real runner (Paul, |
| +// 2026-11-10): Connect Claude; the runner runs setup-token itself (the |
| +// fake CLI, in a pseudo-terminal in the new home) and the card shows its |
| +// link; the person signs in (the code the fake's page would show for the |
| +// link's state) and the page seals the code to the runner's published |
| +// key; a wrong code first, then the right one; the CLI prints the token, |
| +// the runner keeps it 0600 and checks it with a real request through the |
| +// contained launch; healthy, and a turn runs on it. The canary: neither |
| +// the code nor the token is anywhere on the instance (database file and |
| +// WAL bytes, logs, API responses, pages), in the runner's log, its state |
| +// or the CLI's argv; the token is only in its file. |
| +func TestHeadlessClaudeSignIn(t *testing.T) { |
| + env, inst, r := localEnv(t) |
| + _, key, _ := ed25519.GenerateKey(rand.Reader) |
| + if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil { |
| + t.Fatal(err) |
| + } |
| + logs := &syncBuffer{} |
| + r.opts.Logger = slog.New(slog.NewTextHandler(logs, nil)) |
| + r.only(t) |
| + r.start(t) |
| + s := open(t, env) |
| + s.keep() |
| + c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var p wire.ConnectPrompt |
| + s.wait(t, "the sign-in link", time.Minute, func(cv *thintest.Conversation) bool { |
| + if v := cv.Connections[c.ID].Prompt; v != nil && v.Kind == wire.PromptAuthorize && v.URL != "" { |
| + p = *v |
| + return true |
| + } |
| + return false |
| + }) |
| + if page := inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "Open Anthropic") || p.Attempt != 1 || p.WrongCode { |
| + t.Fatalf("the card %+v", p) |
| + } |
| + u, err := url.Parse(p.URL) |
| + if err != nil || u.Host != "claude.com" || u.Query().Get("redirect_uri") != wire.EndpointClaudeCode { |
| + t.Fatalf("link %q", p.URL) |
| + } |
| + snap, err := env.Client.Snapshot(s.ctx) |
| + if err != nil || snap.Runner.SealKey == "" { |
| + t.Fatalf("no seal key published: %v", err) |
| + } |
| + send := func(code string, attempt int64) { |
| + t.Helper() |
| + sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: code, RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointClaudeCode, Attempt: attempt, ExpiresAt: time.Now().Add(wire.SealedTTL).UTC().Truncate(time.Second)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + const email = "signin@example.com" |
| + wrong := fakeclaude.SetupCode(email, "not-this-link") |
| + send(wrong, 1) |
| + s.wait(t, "the wrong-code card", time.Minute, func(cv *thintest.Conversation) bool { |
| + v := cv.Connections[c.ID].Prompt |
| + return v != nil && v.Attempt == 2 && v.WrongCode && v.URL == p.URL |
| + }) |
| + code := fakeclaude.SetupCode(email, u.Query().Get("state")) |
| + send(code, 2) |
| + var got wire.Connection |
| + s.wait(t, "healthy", 2*time.Minute, func(cv *thintest.Conversation) bool { |
| + got = cv.Connections[c.ID] |
| + return got.State == wire.ConnHealthy |
| + }) |
| + if got.Kind != wire.KindToken || got.Label != email || got.LocalID == "" || got.ExpiresAt == nil || !got.ExpiresEstimated { |
| + t.Fatalf("connection %+v", got) |
| + } |
| + // Healthy only after a real request through the contained launch. |
| + until(t, "the check's usage", func() bool { |
| + var n int |
| + err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND connection = ? AND outcome = ?", got.LocalID, wire.OutcomeReplied).Scan(&n) |
| + return err == nil && n == 1 |
| + }) |
| + home := filepath.Join(r.root, "accounts", got.LocalID) |
| + token := fakeclaude.Token(email) |
| + tokenFile := filepath.Join(home, provider.TokenFile) |
| + if raw, err := os.ReadFile(tokenFile); err != nil || string(raw) != token { |
| + t.Fatalf("token file: %v", err) |
| + } |
| + if info, err := os.Stat(tokenFile); err != nil || info.Mode().Perm() != 0600 { |
| + t.Fatalf("token file mode: %v", err) |
| + } |
| + sent := s.send(t, "Hello on the signed-in Claude.") |
| + m := replyOf(t, s, sent.Turn.ID) |
| + if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != got.LocalID { |
| + t.Fatalf("turn on the new connection: %q", m.Text) |
| + } |
| + argv, _ := os.ReadFile(filepath.Join(filepath.Dir(r.cfg.ClaudePath), fakeclaude.SetupArgvFile)) |
| + if string(argv) != "setup-token\n" { |
| + t.Fatalf("the CLI's argv: %q", argv) |
| + } |
| + |
| + // The canary sweep. |
| + list, _ := env.Client.Connections(s.ctx) |
| + api, _ := json.Marshal(list) |
| + sinks := map[string]string{"the instance's logs": inst.Logs(), "the API": string(api), "the runner's log": logs.String()} |
| + for _, path := range []string{"/conversation/settings/connections", "/conversation/settings/connections/add", "/conversation"} { |
| + sinks[path] = inst.Get(t, path) |
| + } |
| + for _, f := range []string{inst.Path, inst.Path + "-wal"} { |
| + raw, err := os.ReadFile(f) |
| + if err != nil && !os.IsNotExist(err) { |
| + t.Fatal(err) |
| + } |
| + sinks[filepath.Base(f)] = string(raw) |
| + } |
| + secrets := map[string]string{"code": code, "wrong code": wrong, "token": token, "token's middle": strings.TrimPrefix(token, "sk-ant-oat01-")} |
| + for name, sink := range sinks { |
| + for what, secret := range secrets { |
| + if strings.Contains(sink, secret) { |
| + t.Fatalf("the %s is in %s", what, name) |
| + } |
| + } |
| + } |
| + // On the runner: the code nowhere, the token only in its file (its |
| + // state database and WAL, the homes, its scratch and config, the |
| + // CLI's argv record). |
| + bin := filepath.Dir(r.cfg.ClaudePath) |
| + for _, dir := range []string{r.cfg.StateDir, filepath.Join(r.root, "accounts"), r.cfg.ScratchRoot, filepath.Dir(r.cfg.AccountBindingsPath), bin} { |
| + _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { |
| + if err != nil || d.IsDir() || !d.Type().IsRegular() || path == tokenFile || filepath.Dir(path) == bin && !strings.HasPrefix(d.Name(), "setup-token.") { |
| + return nil |
| + } |
| + raw, _ := os.ReadFile(path) |
| + for what, secret := range secrets { |
| + if bytes.Contains(raw, []byte(secret)) { |
| + t.Fatalf("the %s is in %s", what, path) |
| + } |
| + } |
| + return nil |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/connect/setuptoken.go b/internal/runner/connect/setuptoken.go| new file mode 100644 |
| index 00000000..c8a1feab |
| --- /dev/null |
| +++ b/internal/runner/connect/setuptoken.go |
| @@ -0,0 +1,425 @@ |
| +package connect |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// 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). |
| + |
| +// ErrNoBrowser: neither /usr/bin/true nor /bin/true is there to stand in |
| +// for a browser. |
| +var ErrNoBrowser = errors.New("no no-op browser") |
| + |
| +// 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`) |
| +) |
| + |
| +// noBrowser is a program that opens nothing: the CLI's BROWSER. |
| +func noBrowser() (string, error) { |
| + for _, p := range []string{"/usr/bin/true", "/bin/true"} { |
| + if info, err := os.Stat(p); err == nil && info.Mode().IsRegular() && info.Mode()&0111 != 0 { |
| + return p, nil |
| + } |
| + } |
| + return "", ErrNoBrowser |
| +} |
| + |
| +// 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) |
| + } |
| + if raw[start-1] == ']' { |
| + // 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. |
| +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 |
| + } |
| + } |
| + for _, m := range linkPattern.FindAll(text, -1) { |
| + if u, ok := AuthorizeURL(string(m)); 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 |
| +} |
| + |
| +// SetupToken is one run of `claude setup-token`. |
| +type SetupToken struct { |
| + cmd *exec.Cmd |
| + master *os.File |
| + 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. |
| + raw []byte |
| + mark int |
| + asked bool |
| +} |
| + |
| +// StartSetupToken starts the CLI in home with env (the login |
| +// environment), its BROWSER a program that opens nothing. |
| +func StartSetupToken(binary, home string, env []string) (*SetupToken, error) { |
| + browser, err := noBrowser() |
| + if err != nil { |
| + return nil, err |
| + } |
| + master, tty, err := openPTY() |
| + if err != nil { |
| + return nil, err |
| + } |
| + cmd := exec.Command(binary, "setup-token") |
| + cmd.Dir = home |
| + cmd.Env = append(append([]string{}, env...), "BROWSER="+browser, "TERM=xterm-256color") |
| + cmd.Stdin, cmd.Stdout, cmd.Stderr = tty, tty, tty |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true} |
| + if err = cmd.Start(); err != nil { |
| + tty.Close() |
| + master.Close() |
| + return nil, err |
| + } |
| + tty.Close() |
| + s := &SetupToken{cmd: cmd, master: master, exited: make(chan struct{}), 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 := master.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() { |
| + _ = cmd.Wait() |
| + close(s.exited) |
| + s.poke() |
| + }() |
| + return s, nil |
| +} |
| + |
| +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) |
| + 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.master.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.master.Write([]byte{'\r'}) |
| + return err |
| +} |
| + |
| +// Result waits for what the CLI does with the code: a token (returned; |
| +// the caller clears it), a failure with the prompt shown again while it |
| +// runs (CodeAgain), or nothing more (CodeEnded: it exited, or said the |
| +// code failed and asked for no other within giveUp). |
| +func (s *SetupToken) Result(ctx context.Context) (string, []byte, error) { |
| + var failed time.Time |
| + 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. |
| + if time.Since(failed) >= 500*time.Millisecond { |
| + s.mu.Lock() |
| + s.mark, s.asked = len(s.raw), true |
| + s.mu.Unlock() |
| + return CodeAgain, nil, nil |
| + } |
| + } else if !failed.IsZero() && time.Since(failed) > giveUp { |
| + return CodeEnded, nil, nil |
| + } |
| + if err := s.wait(ctx); err != nil { |
| + return "", nil, err |
| + } |
| + } |
| +} |
| + |
| +// 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 its process group, waits for it, and zeroes |
| +// everything it printed. |
| +func (s *SetupToken) Close() { |
| + if !s.done() { |
| + _ = unix.Kill(-s.cmd.Process.Pid, unix.SIGKILL) |
| + } |
| + <-s.exited |
| + s.master.Close() |
| + 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() |
| +} |
diff --git a/internal/runner/connect/setuptoken_test.go b/internal/runner/connect/setuptoken_test.go| new file mode 100644 |
| index 00000000..7cb7f715 |
| --- /dev/null |
| +++ b/internal/runner/connect/setuptoken_test.go |
| @@ -0,0 +1,94 @@ |
| +package connect |
| + |
| +import ( |
| + "net/url" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// authorize is the shape CLI 2.1.321 printed on 2026-11-10 (values fake). |
| +const authorize = "https://claude.com/cai/oauth/authorize?code=true&client_id=9d1c250a-fake&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&scope=user%3Ainference&code_challenge=c&code_challenge_method=S256&state=s1" |
| + |
| +// Only Anthropic's authorize page on claude.com or claude.ai, over https, |
| +// redirecting to the code page, is a link the card may show. |
| +func TestAuthorizeURL(t *testing.T) { |
| + if got, ok := AuthorizeURL(authorize); !ok || got != authorize { |
| + t.Fatalf("refused the CLI's own link: %q %v", got, ok) |
| + } |
| + if _, ok := AuthorizeURL(strings.Replace(authorize, "claude.com", "claude.ai", 1)); !ok { |
| + t.Fatal("refused claude.ai") |
| + } |
| + if u, _ := url.Parse(authorize); u.Query().Get("redirect_uri") != wire.EndpointClaudeCode { |
| + t.Fatal("the code endpoint is not the link's redirect") |
| + } |
| + for name, bad := range map[string]string{ |
| + "http": strings.Replace(authorize, "https://", "http://", 1), |
| + "other host": strings.Replace(authorize, "claude.com", "claude.com.example.net", 1), |
| + "subdomain": strings.Replace(authorize, "claude.com", "evil.claude.com", 1), |
| + "user info": strings.Replace(authorize, "https://", "https://x@", 1), |
| + "port": strings.Replace(authorize, "claude.com", "claude.com:8443", 1), |
| + "loopback": strings.Replace(authorize, "https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback", "http%3A%2F%2Flocalhost%3A1234%2Fcallback", 1), |
| + "other page": strings.Replace(authorize, "/oauth/authorize", "/oauth/elsewhere", 1), |
| + "token flow": strings.Replace(authorize, "response_type=code", "response_type=token", 1), |
| + "no state": strings.Replace(authorize, "&state=s1", "", 1), |
| + "fragment": authorize + "#x", |
| + "not a url": "Paste code here", |
| + "javascript": "javascript:alert(1)//claude.com/oauth/authorize", |
| + "redirect twin": authorize + "&redirect_uri=https%3A%2F%2Fexample.net", |
| + } { |
| + if _, ok := AuthorizeURL(bad); ok { |
| + t.Errorf("%s: accepted %q", name, bad) |
| + } |
| + } |
| +} |
| + |
| +// The screen the CLI draws: colours, cursor moves, a spinner, the link as |
| +// an OSC 8 hyperlink (ended by ST or BEL), redrawn. The link is found; |
| +// a truncated visible copy beside a whole hyperlink target does not hide |
| +// it; a plain visible link is found when there is no hyperlink. |
| +func TestAuthorizeThroughEscapes(t *testing.T) { |
| + screen := "\x1b[1mWelcome to Claude Code\x1b[22m\r\n\r\nThis will guide you through long-lived (1-year) auth token setup.\r\nOpening browser to sign in…\r\n" |
| + for _, f := range []string{"⠋", "⠙", "⠹"} { |
| + screen += "\r\x1b[2K\x1b[36m" + f + "\x1b[39m" |
| + } |
| + draw := "\r\x1b[2KBrowser didn't open? Use the url below to sign in \x1b[2m(c to copy)\x1b[22m\r\n\x1b]8;id=1;" + authorize + "\x1b\\\x1b[34m" + authorize[:60] + "…\x1b[39m\x1b]8;;\x1b\\\r\n\x1b[1mPaste code here if prompted >\x1b[22m " |
| + raw := screen + draw + "\x1b[3A\r\x1b[J" + strings.Replace(draw, "\x1b\\\x1b[34m", "\x07\x1b[34m", 1) |
| + if got, ok := authorizeIn([]byte(raw)); !ok || got != authorize { |
| + t.Fatalf("hyperlink: %q %v", got, ok) |
| + } |
| + text, links := visible([]byte(raw)) |
| + if strings.Contains(string(text), "\x1b") || len(links) != 2 || !strings.Contains(string(text), "Paste code here if prompted >") { |
| + t.Fatalf("visible %q links %q", text, links) |
| + } |
| + plain := screen + "\r\nhttps://claude.ai/x \x1b[34m" + authorize + "\x1b[39m\r\n" |
| + if got, ok := authorizeIn([]byte(plain)); !ok || got != authorize { |
| + t.Fatalf("plain: %q %v", got, ok) |
| + } |
| + // Not yet whole: an OSC cut off mid-way finds nothing. |
| + if _, ok := authorizeIn([]byte(screen + "\x1b]8;;" + authorize[:40])); ok { |
| + t.Fatal("found a link in a cut-off sequence") |
| + } |
| +} |
| + |
| +// A token counts once something follows it (or the CLI exited); a failure |
| +// on the prompt's own line (the echoed code) does not count. |
| +func TestTokenAndFailure(t *testing.T) { |
| + tok := "sk-ant-oat01-abc_DEF-123" |
| + if tokenIn([]byte("token:\n"+tok), false) != nil { |
| + t.Fatal("took a token that may go on") |
| + } |
| + if got := tokenIn([]byte("token:\n"+tok), true); string(got) != tok { |
| + t.Fatalf("at exit: %q", got) |
| + } |
| + if got := tokenIn([]byte("x "+tok+"\n"), false); string(got) != tok { |
| + t.Fatalf("whole: %q", got) |
| + } |
| + if failedAt([]byte("Paste code here if prompted > error-in-code\n")) != -1 { |
| + t.Fatal("the echoed prompt line counted as a failure") |
| + } |
| + if at := failedAt([]byte("Exchanging…\nOAuth error: Invalid code\n")); at != len("Exchanging…\nOAuth ") { |
| + t.Fatalf("failure at %d", at) |
| + } |
| +} |
diff --git a/internal/runner/provider/token.go b/internal/runner/provider/token.go| index 5397c973..fe5cfe9c 100644 |
| --- a/internal/runner/provider/token.go |
| +++ b/internal/runner/provider/token.go |
| @@ -45,6 +45,17 @@ func ValidToken(raw []byte) bool { |
| return true |
| } |
| +// MaxCodeBytes bounds a sign-in code (wire.PromptAuthorize). |
| +const MaxCodeBytes = 1024 |
| + |
| +// ValidCode reports whether raw can be the one-time code Anthropic's |
| +// code page shows: one line of printable ASCII without spaces, as |
| +// ValidToken, and never a token (the CLI echoes what is typed, and a |
| +// token in its output is taken as the one it made). |
| +func ValidCode(raw []byte) bool { |
| + return len(raw) >= 8 && len(raw) <= MaxCodeBytes && ValidToken(raw) && !bytes.Contains(raw, []byte("sk-ant")) |
| +} |
| + |
| // ReadToken reads a token home's credential without following links: |
| // a regular 0600 file of the runner's, one link, a valid token. |
| func ReadToken(home string) ([]byte, error) { |
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go| index c5b7aa3a..8a7f0c96 100644 |
| --- a/internal/runner/thin/connector.go |
| +++ b/internal/runner/thin/connector.go |
| @@ -34,11 +34,11 @@ const ConnectLimit = 10 * time.Minute |
| // Connector adds connections from the app (spec §2): a Codex account by |
| // device code, a Claude account by the CLI's own sign-in finished at |
| // this machine (loopback, no paste), or, when the person's browser is |
| -// elsewhere, by `equipo-runner login claude` in a terminal here, which |
| -// the connector watches for. The provider's own CLI signs in, in a new |
| -// dedicated home; the instance only ever sees the provider's display |
| -// code or sign-in page and the account's email. Nothing moves from the |
| -// app to the runner but the request to begin. |
| +// elsewhere, by the runner's own `claude setup-token` with the sign-in |
| +// code relayed sealed (signin.go), or from a pasted token (token.go). |
| +// The provider's own CLI signs in, in a new dedicated home; the instance |
| +// only ever sees the provider's display code or sign-in page, the |
| +// account's email and boxes it cannot open. |
| type Connector struct { |
| Runner runner.Config |
| State *State |
| @@ -68,8 +68,10 @@ type Connector struct { |
| mu sync.Mutex |
| attempts map[string]context.CancelFunc |
| ctx context.Context |
| - // waits wakes a token attempt waiting for its secret. |
| + // waits wakes a token attempt waiting for its secret; codes holds the |
| + // sign-in attempts waiting for a code. |
| waits map[string]chan struct{} |
| + codes map[string]*codeWait |
| // delivery serialises a secret's delivery with its attempt's end. |
| delivery sync.Mutex |
| } |
| @@ -126,7 +128,7 @@ func (c *Connector) log(msg string, err error) { |
| // process died with it) and removes their unfinished homes. |
| func (c *Connector) Start(ctx context.Context) error { |
| c.mu.Lock() |
| - c.ctx, c.attempts, c.waits = ctx, map[string]context.CancelFunc{}, map[string]chan struct{}{} |
| + c.ctx, c.attempts, c.waits, c.codes = ctx, map[string]context.CancelFunc{}, map[string]chan struct{}{}, map[string]*codeWait{} |
| c.mu.Unlock() |
| if _, err := c.State.db.ExecContext(ctx, "DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)); err != nil { |
| return err |
| @@ -148,7 +150,9 @@ func (c *Connector) Start(ctx context.Context) error { |
| rows.Close() |
| for _, l := range all { |
| // A token attempt lost no process: it recovers its delivery and |
| - // waits on (or finishes) where it was. |
| + // waits on (or finishes) where it was. So does a sign-in attempt |
| + // whose token was committed (it is kind token then); one that was |
| + // not lost its CLI with the process, and ends below. |
| if l.kind == wire.KindToken { |
| if err = c.resumeToken(ctx, l.id, l.person, l.home, l.created); err != nil { |
| return err |
| @@ -440,7 +444,7 @@ func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire |
| return |
| } |
| if cmd.Provider == wire.ProviderClaude && !cmd.SameMachine { |
| - c.watchTerminal(ctx, cmd, base, fail) |
| + c.runSignIn(ctx, cmd, base) |
| return |
| } |
| if err := os.MkdirAll(c.Root, 0700); err != nil { |
| @@ -595,41 +599,6 @@ func (c *Connector) mine(person string) []runner.AccountBinding { |
| return out |
| } |
| -// watchTerminal is the remote Claude case (spec §2.3 case 2): the |
| -// sign-in finishes in a terminal on this machine with `equipo-runner |
| -// login claude`, where any paste goes into the CLI. The attempt shows |
| -// that and turns healthy when the new connection appears. |
| -func (c *Connector) watchTerminal(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, fail func(string)) { |
| - before := map[string]bool{} |
| - for _, b := range c.mine(cmd.Person) { |
| - before[b.ID] = true |
| - } |
| - r := base |
| - r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptTerminal, Code: "equipo-runner login claude"} |
| - c.report(r) |
| - tick := time.NewTicker(2 * time.Second) |
| - defer tick.Stop() |
| - for { |
| - select { |
| - case <-ctx.Done(): |
| - fail(reasonOf(ctx.Err())) |
| - return |
| - case <-tick.C: |
| - } |
| - for _, b := range c.mine(cmd.Person) { |
| - if b.Provider == wire.ProviderClaude && !before[b.ID] { |
| - if c.Conns != nil { |
| - c.Conns.changed() |
| - } |
| - done := base |
| - done.State, done.LocalID, done.Label = wire.ConnHealthy, b.ID, b.AccountID |
| - c.finish(cmd.Connection, done) |
| - return |
| - } |
| - } |
| - } |
| -} |
| - |
| // removeHome deletes a home this connector created that never became a |
| // connection: never one a binding names. |
| func (c *Connector) removeHome(home string) { |
diff --git a/internal/runner/thin/signin.go b/internal/runner/thin/signin.go| new file mode 100644 |
| index 00000000..6e7a733e |
| --- /dev/null |
| +++ b/internal/runner/thin/signin.go |
| @@ -0,0 +1,318 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "os" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// Claude with no terminal (Paul, 2026-11-10: "Can you not run this on |
| +// the server and get a link to give to the browser? We're trying to |
| +// avoid the round-trip over SSH here."). The runner runs the unmodified |
| +// `claude setup-token` itself, on a pseudo-terminal, in the connection's |
| +// new dedicated home with the login environment, and shows the authorize |
| +// URL it prints (wire.PromptAuthorize). The person signs in at Anthropic |
| +// and pastes the one-time code it shows; the page seals the code to this |
| +// runner (wire.EndpointClaudeCode, the prompt's attempt) and the instance |
| +// relays the box as it relays a token. The runner opens it, records the |
| +// box as seen, and types the code into the waiting CLI, which prints the |
| +// long-lived token. The token is kept as a pasted one is (keep: the 0600 |
| +// token file, committed with the attempt turned kind token), then |
| +// madeToken probes it, binds it and checks it with one real request; the |
| +// connection is healthy only then. The code and the token are never |
| +// written to a log, an error, a report, a frame or argv, and the code is |
| +// never written to disk. |
| +// |
| +// A wrong code is said on the card: the CLI is asked again when it asks |
| +// again (the same link), else it is started again and the card shows the |
| +// new link. The CLI exiting on its own before a code starts it again too. |
| +// Cancel, the attempt's time limit and a refused box stop the CLI and its |
| +// process group and remove the home as every unfinished attempt does. |
| + |
| +// maxLaunches bounds the CLI's runs in one attempt. |
| +const maxLaunches = 4 |
| + |
| +// codeWait is a sign-in attempt waiting for the code of its attempt |
| +// number; a box that cannot be taken ends it with refuse. |
| +type codeWait struct { |
| + attempt int64 |
| + ch chan codeIn |
| +} |
| + |
| +type codeIn struct { |
| + code []byte |
| + refuse string |
| +} |
| + |
| +// expectCode registers the attempt as waiting for attempt's code. |
| +func (c *Connector) expectCode(id string, attempt int64) chan codeIn { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + w := &codeWait{attempt: attempt, ch: make(chan codeIn, 1)} |
| + c.codes[id] = w |
| + return w.ch |
| +} |
| + |
| +// stopCode ends the wait; a code handed over and not taken is zeroed. |
| +func (c *Connector) stopCode(id string, ch chan codeIn) { |
| + c.mu.Lock() |
| + if w := c.codes[id]; w != nil && w.ch == ch { |
| + delete(c.codes, id) |
| + } |
| + c.mu.Unlock() |
| + select { |
| + case in := <-ch: |
| + clear(in.code) |
| + default: |
| + } |
| +} |
| + |
| +// codeWaiting reports whether the attempt waits for attempt's code. |
| +func (c *Connector) codeWaiting(id string, attempt int64) bool { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + w := c.codes[id] |
| + return w != nil && w.attempt == attempt |
| +} |
| + |
| +// handCode gives the waiting attempt its code (or its refusal): false |
| +// when it is no longer waiting for that attempt's. |
| +func (c *Connector) handCode(id string, attempt int64, in codeIn) bool { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + w := c.codes[id] |
| + if w == nil || w.attempt != attempt { |
| + return false |
| + } |
| + delete(c.codes, id) |
| + w.ch <- in |
| + return true |
| +} |
| + |
| +// runSignIn is a sign-in attempt: the home, the CLI and its link, the |
| +// code, then the token kept and carried on as a token attempt. |
| +func (c *Connector) runSignIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { |
| + home, err := c.tokenHome(ctx, cmd.Connection) |
| + if err != nil { |
| + c.log("connect home", err) |
| + c.failToken(cmd, base, home, "provider_refused") |
| + return |
| + } |
| + lock, err := os.Open(home) |
| + if err == nil { |
| + err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) |
| + } |
| + if err != nil { |
| + if lock != nil { |
| + lock.Close() |
| + } |
| + c.failToken(cmd, base, home, "provider_refused") |
| + return |
| + } |
| + token, reason := c.signIn(ctx, cmd, base, home) |
| + lock.Close() |
| + if token == nil { |
| + // "": a test fault stopped it; "ended" is the test's stop of a |
| + // process whose CLI died with it, before anything is cleaned. |
| + if reason != "" && c.stop("ended") == nil { |
| + c.failToken(cmd, base, home, reason) |
| + } |
| + return |
| + } |
| + cmd.Kind = wire.KindToken |
| + c.delivery.Lock() |
| + dir, err := pinHome(home) |
| + if err == nil { |
| + err = c.keep(ctx, cmd.Connection, dir, token, func(*sql.Tx) error { return nil }) |
| + dir.Close() |
| + } |
| + c.delivery.Unlock() |
| + clear(token) |
| + if errors.Is(err, errStopped) { |
| + return |
| + } |
| + if err != nil { |
| + reason = "provider_refused" |
| + if errors.Is(err, errNotWaiting) || ctx.Err() != nil { |
| + reason = reasonOf(firstErr(ctx.Err(), context.Canceled)) |
| + } |
| + c.log("connect sign-in", err) |
| + c.failToken(cmd, base, home, reason) |
| + return |
| + } |
| + a, _, err := c.attempt(ctx, cmd.Connection) |
| + if err != nil { |
| + c.failToken(cmd, base, home, "provider_refused") |
| + return |
| + } |
| + c.madeToken(ctx, cmd, base, home, a) |
| +} |
| + |
| +// signIn runs the CLI until it prints a token: the token (the caller |
| +// clears it), or nil and the reason the attempt ends ("" when a test |
| +// fault stopped it as if the process had). |
| +func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, home string) ([]byte, string) { |
| + var attempt int64 |
| + wrong, reason := false, "provider_refused" |
| + for launch := 0; launch < maxLaunches; launch++ { |
| + cli, err := connect.StartSetupToken(c.Runner.ClaudePath, home, provider.LoginEnvironment(wire.ProviderClaude, home)) |
| + if err != nil { |
| + c.log("connect sign-in", err) |
| + return nil, "provider_refused" |
| + } |
| + link, err := cli.URL(ctx) |
| + if err != nil { |
| + cli.Close() |
| + if ctx.Err() != nil { |
| + return nil, reasonOf(ctx.Err()) |
| + } |
| + // Exited before a link: nothing to show, nothing to retry. |
| + return nil, "provider_refused" |
| + } |
| + for cli != nil { |
| + if attempt++; attempt > wire.MaxCodeAttempts { |
| + cli.Close() |
| + return nil, "provider_refused" |
| + } |
| + codes := c.expectCode(cmd.Connection, attempt) |
| + r := base |
| + r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: link, Attempt: attempt, WrongCode: wrong} |
| + c.report(r) |
| + var in codeIn |
| + select { |
| + case <-ctx.Done(): |
| + c.stopCode(cmd.Connection, codes) |
| + cli.Close() |
| + return nil, reasonOf(ctx.Err()) |
| + case <-cli.Done(): |
| + // It stopped waiting on its own (its own time limit): a new |
| + // run, a new link. |
| + c.stopCode(cmd.Connection, codes) |
| + cli.Close() |
| + cli, wrong, reason = nil, false, "timed_out" |
| + continue |
| + case in = <-codes: |
| + } |
| + c.stopCode(cmd.Connection, codes) |
| + if in.refuse != "" { |
| + cli.Close() |
| + return nil, in.refuse |
| + } |
| + err = cli.Submit(ctx, in.code) |
| + clear(in.code) |
| + if err == nil && c.stop("code_typed") != nil { |
| + cli.Close() |
| + return nil, "" |
| + } |
| + outcome, token := connect.CodeEnded, []byte(nil) |
| + if err == nil { |
| + outcome, token, err = cli.Result(ctx) |
| + } |
| + if ctx.Err() != nil { |
| + clear(token) |
| + cli.Close() |
| + return nil, reasonOf(ctx.Err()) |
| + } |
| + switch { |
| + case err == nil && outcome == connect.CodeToken: |
| + cli.Close() |
| + if !provider.ValidToken(token) { |
| + clear(token) |
| + return nil, "provider_refused" |
| + } |
| + return token, "" |
| + case err == nil && outcome == connect.CodeAgain: |
| + // It asks again: the same link, a new code. |
| + wrong = true |
| + default: |
| + // It stopped: a new run, a new link. The code was wrong |
| + // unless it never took it. |
| + cli.Close() |
| + cli, wrong, reason = nil, err == nil, "provider_refused" |
| + } |
| + } |
| + } |
| + return nil, reason |
| +} |
| + |
| +// code takes a sealed sign-in code for a sign-in attempt (Secret, spec |
| +// §2.4's steps for a secret that is never stored): (i) received; (ii) |
| +// opened and checked: this runner, this connection and person, Claude, |
| +// the code endpoint, the attempt number the CLI waits for, the shape of |
| +// a code; (iii) committed: one transaction records (connection, attempt, |
| +// frame) in seen_seals while the attempt is running and not cancelled; |
| +// (iv) handed to the attempt, which types it; acked once this returns |
| +// nil. A box for an attempt number the CLI no longer waits for (a new |
| +// link came first) is dropped; a box that does not open or is expired |
| +// ends the attempt with a reason, as a token's does. |
| +func (c *Connector) code(ctx context.Context, frameID string, cmd wire.SecretCommand, a tokenAttempt) error { |
| + s := cmd.Sealed |
| + if a.state != "running" || a.cancelled || !c.codeWaiting(a.id, s.Attempt) { |
| + c.refused("not_waiting") |
| + return nil |
| + } |
| + refuse := func(reason string) error { |
| + c.refused(reason) |
| + if !c.handCode(a.id, s.Attempt, codeIn{refuse: reason}) { |
| + c.refused("not_waiting") |
| + } |
| + 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) |
| + if p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != wire.ProviderClaude || p.Endpoint != wire.EndpointClaudeCode || p.Attempt != s.Attempt || !provider.ValidCode(secret) { |
| + return refuse("provider_refused") |
| + } |
| + if err = c.stop("code_opened"); err != nil { |
| + return err |
| + } |
| + err = c.State.tx(ctx, func(t *sql.Tx) error { |
| + res, err := t.Exec("UPDATE connect_attempts SET state=state WHERE id=? AND state='running' AND cancelled=0", a.id) |
| + if err != nil { |
| + return err |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + return firstErr(err, errNotWaiting) |
| + } |
| + 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) { |
| + c.refused("not_waiting") |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = c.stop("code_committed"); err != nil { |
| + return err |
| + } |
| + given := append([]byte(nil), secret...) |
| + if !c.handCode(a.id, s.Attempt, codeIn{code: given}) { |
| + clear(given) |
| + c.refused("not_waiting") |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/thin/signin_test.go b/internal/runner/thin/signin_test.go| new file mode 100644 |
| index 00000000..fb2ae0fb |
| --- /dev/null |
| +++ b/internal/runner/thin/signin_test.go |
| @@ -0,0 +1,516 @@ |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "io/fs" |
| + "log/slog" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/fakeclaude" |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// Claude with no terminal (signin.go): the runner's own `claude |
| +// setup-token` (the fake, steered from SetupSteerFile beside it) in a |
| +// pseudo-terminal, the link it prints on the card, the code sealed and |
| +// typed into it, the token it prints kept and checked. |
| + |
| +// steer writes the fake setup-token's steering words. |
| +func (r *tokenRig) steer(words ...string) { |
| + r.t.Helper() |
| + if err := os.WriteFile(filepath.Join(r.dir, "bin", fakeclaude.SetupSteerFile), []byte(strings.Join(words, "\n")), 0600); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +// crashable starts a connector whose process can be stopped as a crash |
| +// stops it: at stage (or at once, by crash) every later boundary stops |
| +// too and its context ends, so its CLI dies with it and nothing it does |
| +// after reaches the state. |
| +type crashable struct { |
| + *Connector |
| + cancel context.CancelFunc |
| + dead atomic.Bool |
| +} |
| + |
| +func (r *tokenRig) crashable(stage string) *crashable { |
| + r.t.Helper() |
| + ctx, cancel := context.WithCancel(r.ctx) |
| + keys := r.keys |
| + limit := time.Hour |
| + if r.limit > 0 { |
| + limit = r.limit |
| + } |
| + k := &crashable{cancel: cancel} |
| + k.Connector = &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: limit, Logger: slog.New(slog.NewTextHandler(&r.logs, nil))} |
| + k.spawn = func(f func()) { f() } |
| + k.fault = func(at string) error { |
| + if at == stage { |
| + k.dead.Store(true) |
| + } |
| + if k.dead.Load() { |
| + return errStopped |
| + } |
| + return nil |
| + } |
| + if err := k.Start(ctx); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return k |
| +} |
| + |
| +// crash stops the process: the boundaries stop, the context ends (the |
| +// CLI is killed), and its attempts have returned. |
| +func (k *crashable) crash(r *tokenRig) { |
| + r.t.Helper() |
| + k.dead.Store(true) |
| + k.cancel() |
| + r.waitFor(func() bool { |
| + k.mu.Lock() |
| + defer k.mu.Unlock() |
| + return len(k.attempts) == 0 |
| + }, "the stopped process's attempts to return") |
| +} |
| + |
| +// signIn starts a sign-in attempt and waits for its card's link. |
| +func (r *tokenRig) signIn(c *Connector, id string) (string, string) { |
| + r.t.Helper() |
| + if err := c.Accept(r.ctx, "f-connect-"+id, wire.ConnectCommand{Connection: id, Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + p := r.prompt(id, 1) |
| + var home string |
| + _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home) |
| + if home == "" || filepath.Dir(home) != r.root { |
| + r.t.Fatalf("attempt home %q", home) |
| + } |
| + return p.URL, home |
| +} |
| + |
| +// prompt waits for the card asking for attempt's code. |
| +func (r *tokenRig) prompt(id string, attempt int64) wire.ConnectPrompt { |
| + r.t.Helper() |
| + var got wire.ConnectPrompt |
| + r.waitFor(func() bool { |
| + for _, v := range r.reports(id) { |
| + if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptAuthorize && v.Prompt.Attempt == attempt && v.Prompt.URL != "" { |
| + got = *v.Prompt |
| + return true |
| + } |
| + } |
| + return false |
| + }, "the sign-in card for attempt "+strconv.FormatInt(attempt, 10)) |
| + if _, ok := connect.AuthorizeURL(got.URL); !ok { |
| + r.t.Fatalf("card link %q", got.URL) |
| + } |
| + return got |
| +} |
| + |
| +// codeFor is the code Anthropic's page shows for email after the sign-in |
| +// that link started. |
| +func codeFor(link, email string) string { |
| + u, _ := url.Parse(link) |
| + return fakeclaude.SetupCode(email, u.Query().Get("state")) |
| +} |
| + |
| +// sealedCode is a code's box, as the page seals it. |
| +func (r *tokenRig) sealedCode(id, code string, attempt int64, change func(*wire.SealedPayload)) wire.SecretCommand { |
| + r.t.Helper() |
| + return r.sealed(id, code, func(p *wire.SealedPayload) { |
| + p.Endpoint, p.Attempt = wire.EndpointClaudeCode, attempt |
| + if change != nil { |
| + change(p) |
| + } |
| + }) |
| +} |
| + |
| +// pids are the fake CLI's runs so far. |
| +func (r *tokenRig) pids() []int { |
| + raw, _ := os.ReadFile(filepath.Join(r.dir, "bin", fakeclaude.SetupPidFile)) |
| + var out []int |
| + for _, l := range strings.Fields(string(raw)) { |
| + n, _ := strconv.Atoi(l) |
| + out = append(out, n) |
| + } |
| + return out |
| +} |
| + |
| +// gone waits until every run of the CLI has exited. |
| +func (r *tokenRig) gone() { |
| + r.t.Helper() |
| + r.waitFor(func() bool { |
| + for _, pid := range r.pids() { |
| + // A zombie is reaped by its parent's Wait; kill(0) on one |
| + // still succeeds, so read its state. |
| + raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat") |
| + if err == nil && !bytes.Contains(raw, []byte(") Z ")) { |
| + return false |
| + } |
| + } |
| + return true |
| + }, "the CLI to have exited") |
| +} |
| + |
| +// nowhere fails if secret is in any file under the rig's directory (the |
| +// runner's state database and its WAL, the homes, the fake's records). |
| +func (r *tokenRig) nowhere(secret, what string) { |
| + r.t.Helper() |
| + _ = filepath.WalkDir(r.dir, func(path string, d fs.DirEntry, err error) error { |
| + if err != nil || d.IsDir() || filepath.Dir(path) == filepath.Join(r.dir, "bin") && d.Name() == "claude" { |
| + return nil |
| + } |
| + if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(secret)) { |
| + r.t.Fatalf("the %s is in %s", what, path) |
| + } |
| + return nil |
| + }) |
| + if bytes.Contains(r.logs.Bytes(), []byte(secret)) { |
| + r.t.Fatalf("the %s is in the runner's log", what) |
| + } |
| +} |
| + |
| +// The whole sign-in: the CLI started on a terminal in the attempt's own |
| +// home with BROWSER a no-op (else the fake opens nothing and exits), its |
| +// link on the card, the code sealed, typed in, the token it printed kept |
| +// 0600 and checked by one real request before the connection is healthy. |
| +// The CLI's argv is setup-token alone; the code is on no disk and in no |
| +// log, the token only in its file. |
| +func TestSignInConnect(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + link, home := r.signIn(c, "cn_s1") |
| + if len(r.pids()) != 1 { |
| + t.Fatalf("%d runs of the CLI", len(r.pids())) |
| + } |
| + code := codeFor(link, "s@example.com") |
| + if !r.deliver(c, "f-code", r.sealedCode("cn_s1", code, 1, nil)) { |
| + t.Fatal(r.errs) |
| + } |
| + token := fakeclaude.Token("s@example.com") |
| + r.healthy("cn_s1", home, token, "s@example.com") |
| + if r.checks.Load() != 1 { |
| + t.Fatalf("%d real checks", r.checks.Load()) |
| + } |
| + r.gone() |
| + argv, _ := os.ReadFile(filepath.Join(r.dir, "bin", fakeclaude.SetupArgvFile)) |
| + if string(argv) != "setup-token\n" { |
| + t.Fatalf("argv %q", argv) |
| + } |
| + r.nowhere(code, "code") |
| + r.nowhere(strings.TrimPrefix(code, "fakecode-"), "code") |
| + // The token: in its file and nowhere else. |
| + tokenFile := filepath.Join(home, provider.TokenFile) |
| + _ = filepath.WalkDir(r.dir, func(path string, d fs.DirEntry, err error) error { |
| + if err == nil && !d.IsDir() && path != tokenFile { |
| + if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(token)) { |
| + t.Fatalf("the token is in %s", path) |
| + } |
| + } |
| + return nil |
| + }) |
| + for _, v := range r.reports("cn_s1") { |
| + if v.Prompt != nil && (strings.Contains(v.Prompt.URL, code) || v.Prompt.Code != "") { |
| + t.Fatalf("report %+v", v) |
| + } |
| + } |
| +} |
| + |
| +// The check is what makes the connection: a token the provider refuses |
| +// ends the attempt provider_refused, nothing kept. |
| +func TestSignInTokenRejected(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + refused := error(provider.ErrLoginRequired) |
| + r.refuse.Store(&refused) |
| + link, home := r.signIn(c, "cn_s2") |
| + r.deliver(c, "f-code", r.sealedCode("cn_s2", codeFor(link, "s2@example.com"), 1, nil)) |
| + end := r.ended("cn_s2") |
| + if end.State != wire.ConnError || end.Reason != "provider_refused" || r.checks.Load() != 1 { |
| + t.Fatalf("end %+v after %d checks", end, r.checks.Load()) |
| + } |
| + r.waitFor(func() bool { _, err := os.Stat(home); return os.IsNotExist(err) }, "the home to go") |
| + if _, ok := r.binding(filepath.Base(home)); ok { |
| + t.Fatal("bound") |
| + } |
| + for _, v := range r.reports("cn_s2") { |
| + if v.State == wire.ConnHealthy { |
| + t.Fatal("healthy before the check") |
| + } |
| + } |
| +} |
| + |
| +// A wrong code while the CLI asks again: the card says so with the same |
| +// link and the next attempt; the right code then connects. |
| +func TestSignInWrongCodeAgain(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + link, home := r.signIn(c, "cn_w1") |
| + r.deliver(c, "f-code-1", r.sealedCode("cn_w1", "fakecode-not-the-right-one#x", 1, nil)) |
| + p := r.prompt("cn_w1", 2) |
| + if p.URL != link || !p.WrongCode { |
| + t.Fatalf("second card %+v", p) |
| + } |
| + if len(r.pids()) != 1 { |
| + t.Fatal("the CLI was started again") |
| + } |
| + r.deliver(c, "f-code-2", r.sealedCode("cn_w1", codeFor(link, "w@example.com"), 2, nil)) |
| + r.healthy2("cn_w1", home, fakeclaude.Token("w@example.com"), "w@example.com", 2) |
| +} |
| + |
| +// healthy2 is healthy for an attempt that took seals boxes. |
| +func (r *tokenRig) healthy2(id, home, token, email string, seals int) { |
| + r.t.Helper() |
| + end := r.ended(id) |
| + if end.State != wire.ConnHealthy || end.LocalID != filepath.Base(home) || end.Label != email || r.seals(id) != seals { |
| + r.t.Fatalf("end %+v, %d seals", end, r.seals(id)) |
| + } |
| + raw, err := os.ReadFile(filepath.Join(home, provider.TokenFile)) |
| + if err != nil || string(raw) != token { |
| + r.t.Fatalf("token file: %v", err) |
| + } |
| +} |
| + |
| +// A wrong code the CLI exits on: it is started again, and the card says |
| +// the code was wrong with the new link. The first link's code does not |
| +// work on the new run; the new one's does. |
| +func TestSignInWrongCodeRestarts(t *testing.T) { |
| + r := newTokenRig(t) |
| + r.steer("exit_on_wrong") |
| + c := r.connector() |
| + link, home := r.signIn(c, "cn_w2") |
| + r.deliver(c, "f-code-1", r.sealedCode("cn_w2", "fakecode-wrong#x", 1, nil)) |
| + p := r.prompt("cn_w2", 2) |
| + if p.URL == link || !p.WrongCode || len(r.pids()) != 2 { |
| + t.Fatalf("second card %+v after %d runs", p, len(r.pids())) |
| + } |
| + r.deliver(c, "f-code-2", r.sealedCode("cn_w2", codeFor(link, "w2@example.com"), 2, nil)) |
| + p3 := r.prompt("cn_w2", 3) |
| + if p3.URL == p.URL || !p3.WrongCode { |
| + t.Fatalf("third card %+v", p3) |
| + } |
| + r.deliver(c, "f-code-3", r.sealedCode("cn_w2", codeFor(p3.URL, "w2@example.com"), 3, nil)) |
| + r.healthy2("cn_w2", home, fakeclaude.Token("w2@example.com"), "w2@example.com", 3) |
| +} |
| + |
| +// The CLI's own time limit: it exits waiting; it is started again with a |
| +// new link (no wrong code said), up to maxLaunches runs, then the |
| +// attempt ends timed_out, the home gone. |
| +func TestSignInCLIExpires(t *testing.T) { |
| + r := newTokenRig(t) |
| + r.steer("expire_ms=300") |
| + c := r.connector() |
| + link, home := r.signIn(c, "cn_e1") |
| + p := r.prompt("cn_e1", 2) |
| + if p.URL == link || p.WrongCode { |
| + t.Fatalf("second card %+v", p) |
| + } |
| + end := r.ended("cn_e1") |
| + if end.State != wire.ConnError || end.Reason != "timed_out" || len(r.pids()) != maxLaunches { |
| + t.Fatalf("end %+v after %d runs", end, len(r.pids())) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatalf("home %v", err) |
| + } |
| + r.gone() |
| +} |
| + |
| +// The CLI fails before any link: provider_refused, the home gone. |
| +func TestSignInCLIFailsToStart(t *testing.T) { |
| + r := newTokenRig(t) |
| + r.steer("fail_start") |
| + c := r.connector() |
| + if err := c.Accept(r.ctx, "f-connect", wire.ConnectCommand{Connection: "cn_f1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if end := r.ended("cn_f1"); end.State != wire.ConnError || end.Reason != "provider_refused" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if entries, _ := os.ReadDir(r.root); len(entries) != 0 { |
| + t.Fatalf("left %v", entries) |
| + } |
| +} |
| + |
| +// Cancel, and the attempt's own time limit: the CLI and its group are |
| +// killed, the home deleted, the end reported; a code after is acked and |
| +// dropped, never typed. |
| +func TestSignInCancelAndLimit(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + link, home := r.signIn(c, "cn_k1") |
| + if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_k1", Person: connPerson}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if end := r.ended("cn_k1"); end.State != wire.ConnError || end.Reason != "cancelled" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + r.gone() |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatalf("home %v", err) |
| + } |
| + if !r.deliver(c, "f-late", r.sealedCode("cn_k1", codeFor(link, "k@example.com"), 1, nil)) || r.seals("cn_k1") != 0 { |
| + t.Fatal("a late code was not dropped") |
| + } |
| + |
| + r.limit = 1500 * time.Millisecond |
| + c = r.connector() |
| + _, home = r.signIn(c, "cn_k2") |
| + if end := r.ended("cn_k2"); end.State != wire.ConnError || end.Reason != "timed_out" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + r.gone() |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatalf("home %v", err) |
| + } |
| +} |
| + |
| +// A code's box: the resend is acked and nothing else; a box for an |
| +// attempt the CLI no longer waits for is dropped and the attempt waits |
| +// on; a token's box, an expired one, one with a code that holds a token |
| +// and one for another runner are refused, ending the attempt; a code's |
| +// box to a token attempt is refused too. |
| +func TestSignInCodeReplayAndRefusals(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + link, home := r.signIn(c, "cn_r1") |
| + r.deliver(c, "f-stale", r.sealedCode("cn_r1", codeFor(link, "r@example.com"), 2, nil)) |
| + if r.seals("cn_r1") != 0 || len(r.reports("cn_r1")) != 1 { |
| + t.Fatal("a stale attempt's box was taken") |
| + } |
| + cmd := r.sealedCode("cn_r1", codeFor(link, "r@example.com"), 1, nil) |
| + r.deliver(c, "f-1", cmd) |
| + r.healthy2("cn_r1", home, fakeclaude.Token("r@example.com"), "r@example.com", 1) |
| + reports, logged := len(r.reports("cn_r1")), r.logs.Len() |
| + for _, frame := range []string{"f-1", "f-1-again"} { |
| + if !r.deliver(c, frame, cmd) { |
| + t.Fatal(r.errs) |
| + } |
| + } |
| + if r.logs.Len() != logged || len(r.reports("cn_r1")) != reports || r.seals("cn_r1") != 1 || len(r.pids()) != 1 { |
| + t.Fatal("a replay was handled again") |
| + } |
| + |
| + for i, x := range []struct { |
| + name, reason string |
| + box func(id, link string) wire.SecretCommand |
| + }{ |
| + {"a token's box", "provider_refused", func(id, link string) wire.SecretCommand { |
| + return r.sealed(id, fakeclaude.Token("x@example.com"), nil) |
| + }}, |
| + {"expired", "timed_out", func(id, link string) wire.SecretCommand { |
| + return r.sealedCode(id, codeFor(link, "x@example.com"), 1, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Second).UTC() }) |
| + }}, |
| + {"a token as the code", "provider_refused", func(id, link string) wire.SecretCommand { |
| + return r.sealedCode(id, fakeclaude.Token("x@example.com"), 1, nil) |
| + }}, |
| + {"another runner", "provider_refused", func(id, link string) wire.SecretCommand { |
| + return r.sealedCode(id, codeFor(link, "x@example.com"), 1, func(p *wire.SealedPayload) { p.RunnerID = "run_other" }) |
| + }}, |
| + } { |
| + t.Run(x.name, func(t *testing.T) { |
| + id := "cn_x" + strconv.Itoa(i) |
| + link, home := r.signIn(c, id) |
| + if !r.deliver(c, "f-"+id, x.box(id, link)) { |
| + t.Fatal("not acked") |
| + } |
| + if end := r.ended(id); end.State != wire.ConnError || end.Reason != x.reason { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals(id) != 0 { |
| + t.Fatalf("home %v, %d seals", err, r.seals(id)) |
| + } |
| + }) |
| + } |
| + r.gone() |
| + home = r.connect(c, "cn_t1") |
| + r.deliver(c, "f-t1", r.sealedCode("cn_t1", "fakecode-00#x", 1, func(p *wire.SealedPayload) { p.Attempt = 1 })) |
| + if end := r.ended("cn_t1"); end.Reason != "provider_refused" || r.seals("cn_t1") != 0 { |
| + t.Fatalf("a token attempt took a code: %+v", end) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// A stop at each boundary of a code's delivery and its token's keeping. |
| +// Before the token is committed the CLI died with the process: the |
| +// restart ends the attempt runner_offline and deletes its home (with any |
| +// staged or renamed token file), and the resent box is acked and |
| +// dropped. Once committed, the restart carries the attempt on as a token |
| +// attempt to healthy. The code is never on disk. |
| +func TestSignInSurvivesCrashes(t *testing.T) { |
| + for _, stage := range []string{"code_opened", "code_committed", "code_typed", "staged", "transaction", "committed"} { |
| + t.Run(stage, func(t *testing.T) { |
| + r := newTokenRig(t) |
| + first := r.crashable(stage) |
| + id := "cn_c_" + stage |
| + link, home := r.signIn(first.Connector, id) |
| + code := codeFor(link, "c@example.com") |
| + cmd := r.sealedCode(id, code, 1, nil) |
| + acked := r.deliver(first.Connector, "f-code", cmd) |
| + if acked == (stage == "code_opened" || stage == "code_committed") { |
| + t.Fatalf("acked %v through a stop at %s", acked, stage) |
| + } |
| + if stage != "code_opened" && stage != "code_committed" { |
| + r.waitFor(first.dead.Load, "the stop") |
| + } |
| + first.crash(r) |
| + r.gone() |
| + second := r.connector() |
| + if !r.deliver(second, "f-code", cmd) { |
| + t.Fatal(r.errs) |
| + } |
| + token := fakeclaude.Token("c@example.com") |
| + if stage == "committed" { |
| + r.healthy2(id, home, token, "c@example.com", 1) |
| + return |
| + } |
| + if end := r.ended(id); end.State != wire.ConnError || end.Reason != "runner_offline" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if _, err := os.Stat(home); !os.IsNotExist(err) { |
| + t.Fatalf("home %v", err) |
| + } |
| + if want := map[bool]int{true: 0, false: 1}[stage == "code_opened"]; r.seals(id) != want { |
| + t.Fatalf("%d seals", r.seals(id)) |
| + } |
| + r.nowhere(code, "code") |
| + r.nowhere(token, "token") |
| + }) |
| + } |
| +} |
| + |
| +// The CLI killed mid-sign-in by its own crash (not the runner's): it is |
| +// started again with a new link, and nothing is left of the first run. |
| +func TestSignInCLIDies(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + link, _ := r.signIn(c, "cn_d1") |
| + pids := r.pids() |
| + if err := unix.Kill(pids[0], unix.SIGKILL); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := r.prompt("cn_d1", 2) |
| + if p.URL == link || p.WrongCode || len(r.pids()) != 2 { |
| + t.Fatalf("card %+v", p) |
| + } |
| + if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_d1", Person: connPerson}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.ended("cn_d1") |
| + r.gone() |
| + if len(r.errs) != 0 && !errors.Is(r.errs[0], errStopped) { |
| + t.Fatal(r.errs) |
| + } |
| +} |
diff --git a/internal/runner/thin/token.go b/internal/runner/thin/token.go| index 0e7dd554..b0b3b9f7 100644 |
| --- a/internal/runner/thin/token.go |
| +++ b/internal/runner/thin/token.go |
| @@ -37,24 +37,31 @@ 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 attempt's row. |
| +// tokenAttempt is a token or sign-in attempt's row. |
| type tokenAttempt struct { |
| - id, person, home, state, kind, secret string |
| - cancelled bool |
| + id, person, home, state, kind, secret, provider string |
| + cancelled, same bool |
| } |
| func (a tokenAttempt) waiting() bool { |
| return a.state == "running" && a.kind == wire.KindToken && !a.cancelled && a.secret == "" && a.home != "" |
| } |
| +// signIn says the attempt is Claude's sign-in by the runner's own |
| +// `claude setup-token` (signin.go): Claude, not a token, not at this |
| +// machine. Once its token is committed it is a token attempt. |
| +func (a tokenAttempt) signIn() bool { |
| + return a.provider == wire.ProviderClaude && a.kind != wire.KindToken && !a.same |
| +} |
| + |
| 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, cancelled FROM connect_attempts WHERE id=?", id).Scan(&a.person, &a.home, &a.state, &a.kind, &a.secret, &cancelled) |
| + var cancelled, same int |
| + err := c.State.db.QueryRowContext(ctx, "SELECT person, home, state, kind, secret, provider, same_machine, cancelled FROM connect_attempts WHERE id=?", id).Scan(&a.person, &a.home, &a.state, &a.kind, &a.secret, &a.provider, &same, &cancelled) |
| if errors.Is(err, sql.ErrNoRows) { |
| return a, false, nil |
| } |
| - a.cancelled = cancelled == 1 |
| + a.cancelled, a.same = cancelled == 1, same == 1 |
| return a, err == nil, err |
| } |
| @@ -111,28 +118,27 @@ func (c *Connector) tokenHome(ctx context.Context, id string) (string, error) { |
| 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. |
| +// the status probe, the binding and the healthy report (madeToken). |
| func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { |
| - // end finishes the attempt (one not yet saved) and removes its home, |
| - // never while a secret is being delivered to it. |
| - end := func(home string, r wire.ConnectionReport) { |
| - c.delivery.Lock() |
| - defer c.delivery.Unlock() |
| - c.removeHome(home) |
| - if home != "" && exists(home) { |
| - // Not deleted (still bound): the durable sign-out does it. |
| - go c.endToken(cmd.Connection, cmd.Person, home, r.Reason) |
| - return |
| - } |
| - c.finish(cmd.Connection, r) |
| - } |
| - failed := func(home, reason string) { |
| - r := base |
| - r.State, r.Reason = wire.ConnError, reason |
| - end(home, r) |
| - } |
| + 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) |
| @@ -164,6 +170,14 @@ func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base |
| } |
| 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 { |
| @@ -453,6 +467,9 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC |
| 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 |
| @@ -481,32 +498,56 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC |
| if p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != wire.ProviderClaude || p.Endpoint != wire.EndpointAnthropic || p.Attempt < 1 || !provider.ValidToken(secret) { |
| return refuse("provider_refused") |
| } |
| - // (ii) staged. |
| dir, err := pinHome(a.home) |
| if err != nil { |
| return err |
| } |
| defer dir.Close() |
| - if err = stage(dir, secret); err != nil { |
| + err = c.keep(ctx, a.id, 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 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 string, dir *os.File, secret []byte, record func(*sql.Tx) error) error { |
| + err := stage(dir, secret) |
| clear(secret) |
| + if err != nil { |
| + return err |
| + } |
| if err = c.stop("staged"); err != nil { |
| return err |
| } |
| - // (iii) committed. |
| err = c.State.tx(ctx, func(t *sql.Tx) error { |
| - res, err := t.Exec("UPDATE connect_attempts SET secret=? WHERE id=? AND state='running' AND cancelled=0 AND secret=''", credentialPresent, a.id) |
| + res, err := t.Exec("UPDATE connect_attempts SET secret=?, kind=? WHERE id=? AND state='running' AND cancelled=0 AND secret=''", credentialPresent, wire.KindToken, id) |
| if err != nil { |
| return err |
| } |
| if n, err := res.RowsAffected(); err != nil || n != 1 { |
| return firstErr(err, errNotWaiting) |
| } |
| - 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 |
| - } |
| - if _, err = t.Exec("DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)); err != nil { |
| + if err = record(t); err != nil { |
| return err |
| } |
| if err = unix.Renameat(int(dir.Fd()), provider.TokenStaging, int(dir.Fd()), provider.TokenFile); err != nil { |
| @@ -520,25 +561,14 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC |
| return c.stop("transaction") |
| }) |
| if err != nil { |
| - if errors.Is(err, errStopped) { |
| - return err |
| - } |
| - // Not committed: nothing of it stays. A cancel that won the race |
| - // is acked; anything else is retried on the resend. |
| - _ = unix.Unlinkat(int(dir.Fd()), provider.TokenStaging, 0) |
| - _ = unix.Unlinkat(int(dir.Fd()), provider.TokenFile, 0) |
| - _ = dir.Sync() |
| - if errors.Is(err, errNotWaiting) { |
| - c.refused("not_waiting") |
| - return 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 |
| } |
| - if err = c.stop("committed"); err != nil { |
| - return err |
| - } |
| - c.wake(a.id) |
| - return nil |
| + return c.stop("committed") |
| } |
| var errNotWaiting = errors.New("the attempt is not waiting for its secret") |
diff --git a/internal/thintest/connections_contract_test.go b/internal/thintest/connections_contract_test.go| index 0ee3baec..59c654f1 100644 |
| --- a/internal/thintest/connections_contract_test.go |
| +++ b/internal/thintest/connections_contract_test.go |
| @@ -108,12 +108,13 @@ func TestContractConnections(t *testing.T) { |
| t.Fatalf("late frame reopened the attempt: %+v", v) |
| } |
| - // Claude, browser elsewhere: the honest card, and the runner watches. |
| + // Claude, browser elsewhere: the sign-in by a link, starting on the |
| + // runner (no link yet). |
| claude, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) |
| - if err != nil || claude.Prompt == nil || claude.Prompt.Kind != wire.PromptTerminal || claude.Prompt.Code != "equipo-runner login claude" { |
| + if err != nil || claude.Prompt == nil || claude.Prompt.Kind != wire.PromptAuthorize || claude.Prompt.URL != "" || claude.Prompt.Attempt != 0 || claude.Kind != wire.KindSubscription { |
| t.Fatalf("claude attempt %+v %v", claude, err) |
| } |
| - if _, body, err = runner.Expect(r.ctx, wire.FrameConnect); err != nil || body.(*wire.ConnectCommand).SameMachine { |
| + if _, body, err = runner.Expect(r.ctx, wire.FrameConnect); err != nil || body.(*wire.ConnectCommand).SameMachine || body.(*wire.ConnectCommand).Kind != wire.KindSubscription { |
| t.Fatalf("claude connect %+v %v", body, err) |
| } |
| cancelled, err := r.client.CancelConnection(r.ctx, claude.ID) |
diff --git a/internal/thintest/signin_contract_test.go b/internal/thintest/signin_contract_test.go| new file mode 100644 |
| index 00000000..666416f1 |
| --- /dev/null |
| +++ b/internal/thintest/signin_contract_test.go |
| @@ -0,0 +1,219 @@ |
| +package thintest |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "html" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// canaryCode is an obviously fake sign-in code. |
| +const canaryCode = "CANARYCODE-not-a-real-code#CANARYSTATE" |
| + |
| +// signInLink is the authorize link a runner's setup-token printed (fake). |
| +const signInLink = "https://claude.com/cai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=s1" |
| + |
| +// TestContractSignInCode (Paul, 2026-11-10): Claude with the browser |
| +// elsewhere starts the runner's own setup-token (kind subscription, the |
| +// card starting); the runner's link goes on the card with its attempt; |
| +// a sealed code bound to the code endpoint and that attempt goes to the |
| +// runner as a durable secret frame, one per card, the card waiting; a |
| +// wrong code's new card takes the next; healthy turns the record into a |
| +// token connection. A box the card did not ask for is refused. The |
| +// code's plaintext and the box appear nowhere on the instance. |
| +func TestContractSignInCode(t *testing.T) { |
| + r := newRig(t) |
| + rec := &recorder{} |
| + r.client.HTTP.Transport = rec |
| + keys := sealKeys(t) |
| + runner := r.dial(0) |
| + hello := held() |
| + hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString() |
| + if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) |
| + var runnerID string |
| + waitFor(t, "the seal key published", func() bool { |
| + list, err := r.client.Runners(r.ctx) |
| + if err != nil || len(list.Items) != 1 { |
| + return false |
| + } |
| + runnerID = list.Items[0].ID |
| + return list.Items[0].SealKey == keys.PublicString() |
| + }) |
| + |
| + attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) |
| + if err != nil || attempt.Kind != wire.KindSubscription || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptAuthorize || attempt.Prompt.URL != "" || attempt.Prompt.Attempt != 0 { |
| + t.Fatalf("sign-in attempt %+v %v", attempt, err) |
| + } |
| + f, body, err := runner.Expect(r.ctx, wire.FrameConnect) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cmd := body.(*wire.ConnectCommand); cmd.Kind != wire.KindSubscription || cmd.SameMachine || cmd.Provider != "claude" { |
| + t.Fatalf("connect frame %+v", cmd) |
| + } |
| + _ = runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}) |
| + seal := func(code string, n int64, endpoint string) wire.Sealed { |
| + t.Helper() |
| + s, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: code, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: endpoint, Attempt: n, ExpiresAt: time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| + } |
| + // No link yet: nothing to answer. |
| + if _, err = r.client.Secret(r.ctx, attempt.ID, seal(canaryCode, 1, wire.EndpointClaudeCode)); Status(err) != 409 { |
| + t.Fatalf("a code before the link: %v", err) |
| + } |
| + if err = runner.Send(r.ctx, "r-link", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLink, Attempt: 1}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.wait("the link on the card", func(c *Conversation) bool { |
| + p := c.Connections[attempt.ID].Prompt |
| + return p != nil && p.URL == signInLink && p.Attempt == 1 |
| + }) |
| + page := html.UnescapeString(r.inst.Get(t, "/conversation/settings/connections/add")) |
| + for _, want := range []string{"Open Anthropic", "Copy link", "Paste the code Anthropic shows you", `data-attempt="1"`, `data-endpoint="` + wire.EndpointClaudeCode + `"`, `data-seal-key="` + keys.PublicString() + `"`, "Paste a token you already have"} { |
| + if !strings.Contains(page, want) { |
| + t.Fatalf("the card lacks %q", want) |
| + } |
| + } |
| + if strings.Contains(page, "That code did not work.") { |
| + t.Fatal("a first card says the code was wrong") |
| + } |
| + for name, box := range map[string]wire.Sealed{ |
| + "attempt 0": seal(canaryCode, 0, wire.EndpointClaudeCode), |
| + "past the last": seal(canaryCode, wire.MaxCodeAttempts+1, wire.EndpointClaudeCode), |
| + "a token's binding": seal(canaryCode, 1, wire.EndpointAnthropic), |
| + "another endpoint": seal(canaryCode, 1, "https://platform.claude.com/oauth/other"), |
| + } { |
| + if _, err := r.client.Secret(r.ctx, attempt.ID, box); Status(err) != 422 { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + if _, err := r.client.Secret(r.ctx, attempt.ID, seal(canaryCode, 2, wire.EndpointClaudeCode)); Status(err) != 409 { |
| + t.Fatalf("an attempt the card did not ask for: %v", err) |
| + } |
| + first := seal(canaryCode, 1, wire.EndpointClaudeCode) |
| + posted, err := r.client.Secret(r.ctx, attempt.ID, first) |
| + if err != nil || posted.Prompt == nil || posted.Prompt.Kind != wire.PromptAuthorize || posted.Prompt.URL != "" || posted.Prompt.Attempt != 1 { |
| + t.Fatalf("code %+v %v", posted, err) |
| + } |
| + if _, err := r.client.Secret(r.ctx, attempt.ID, first); Status(err) != 409 { |
| + t.Fatalf("a second box for one card: %v", err) |
| + } |
| + if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "Your runner is finishing the sign-in") || strings.Contains(page, "Open Anthropic") { |
| + t.Fatal("the card does not wait for the runner") |
| + } |
| + f, body, err = runner.Expect(r.ctx, wire.FrameSecret) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := body.(*wire.SecretCommand) |
| + if opened, err := keys.Open(cmd.Sealed, time.Now()); err != nil || opened.Secret != canaryCode || opened.Endpoint != wire.EndpointClaudeCode || opened.Attempt != 1 { |
| + t.Fatalf("the runner's box: %v", err) |
| + } |
| + _ = runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID}) |
| + |
| + // A wrong code: the runner's next card says so and takes attempt 2. |
| + if err = runner.Send(r.ctx, "r-wrong", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLink, Attempt: 2, WrongCode: true}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.wait("the wrong-code card", func(c *Conversation) bool { |
| + p := c.Connections[attempt.ID].Prompt |
| + return p != nil && p.Attempt == 2 && p.WrongCode && p.URL != "" |
| + }) |
| + if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil { |
| + t.Fatal(err) |
| + } else { |
| + shape(t, "api/connection-signing-in-claude.json", got) |
| + } |
| + if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "That code did not work. Open Anthropic again and paste the new code.") || !strings.Contains(page, `data-attempt="2"`) { |
| + t.Fatal("the card does not say the code was wrong") |
| + } |
| + second := seal(canaryCode, 2, wire.EndpointClaudeCode) |
| + shape(t, "api/connection-code.json", second) |
| + if _, err = r.client.Secret(r.ctx, attempt.ID, second); err != nil { |
| + t.Fatal(err) |
| + } |
| + f, _, err = runner.Expect(r.ctx, wire.FrameSecret) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = runner.Send(r.ctx, "a-secret-2", wire.FrameAck, wire.Ack{ID: f.ID}) |
| + |
| + // Healthy: a token connection now, its expiry an estimate. |
| + if err = runner.Send(r.ctx, "r-healthy", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: Owner}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.wait("healthy", func(c *Conversation) bool { return c.Connections[attempt.ID].State == wire.ConnHealthy }) |
| + if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.Kind != wire.KindToken || got.ExpiresAt == nil || !got.ExpiresEstimated || got.Prompt != nil { |
| + t.Fatalf("connection %+v %v", got, err) |
| + } |
| + |
| + // A sign-in that ends refused says so plainly: not "This token was |
| + // rejected", and it stays a subscription attempt. |
| + other, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = runner.Send(r.ctx, "r-refused", wire.FrameConnection, wire.ConnectionReport{Connection: other.ID, Person: Owner, Provider: "claude", State: wire.ConnError, Reason: "provider_refused"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.wait("refused", func(c *Conversation) bool { return c.Connections[other.ID].State == wire.ConnError }) |
| + if got, _ := r.client.Connection(r.ctx, other.ID); got.Kind != wire.KindSubscription { |
| + t.Fatalf("ended %+v", got) |
| + } |
| + if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "The provider did not complete the sign-in.") || strings.Contains(page, "This token was rejected") { |
| + t.Fatal("the ended sign-in's note") |
| + } |
| + |
| + // The sweep: pages, API responses, events, logs, rows, database and |
| + // WAL bytes. |
| + var sinks []string |
| + for _, path := range []string{"/conversation/settings/connections", "/conversation/settings/connections/add", "/conversation"} { |
| + sinks = append(sinks, r.inst.Get(t, path)) |
| + } |
| + if _, err := r.client.Connections(r.ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + var events, rows string |
| + _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(body, '|'), '') FROM chat_events").Scan(&events) |
| + _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(coalesce(prompt,'') || label || state || kind, '|'), '') FROM chat_connections").Scan(&rows) |
| + sinks = append(sinks, rawEvents(t, r), rec.String(), r.inst.Logs(), events, rows) |
| + canaries := []string{canaryCode, "CANARYCODE", "CANARYSTATE", base64.StdEncoding.EncodeToString([]byte(canaryCode))} |
| + for i, s := range sinks { |
| + for _, c := range canaries { |
| + if strings.Contains(s, c) { |
| + t.Fatalf("sink %d holds the code %q", i, c) |
| + } |
| + } |
| + for _, box := range []wire.Sealed{first, second} { |
| + if strings.Contains(s, box.Box[:24]) { |
| + t.Fatalf("sink %d holds a sealed box", i) |
| + } |
| + } |
| + } |
| + for _, suffix := range []string{"", "-wal", "-shm"} { |
| + raw, err := os.ReadFile(r.inst.Path + suffix) |
| + if err != nil { |
| + if os.IsNotExist(err) && suffix != "" { |
| + continue |
| + } |
| + t.Fatal(err) |
| + } |
| + for _, c := range canaries { |
| + if bytes.Contains(raw, []byte(c)) { |
| + t.Fatalf("database%s holds the code %q", suffix, c) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/wire/connections.go b/internal/wire/connections.go| index d4f02824..2fada7c0 100644 |
| --- a/internal/wire/connections.go |
| +++ b/internal/wire/connections.go |
| @@ -28,14 +28,30 @@ const ( |
| ) |
| // Prompt kinds on a connecting card: a device code to enter at URL, a |
| -// sign-in link to open on the runner's machine, or the terminal step at |
| -// the runner (Claude when the browser is elsewhere). |
| +// sign-in link to open on the runner's machine, or Claude's sign-in link |
| +// whose code comes back sealed (PromptAuthorize). |
| const ( |
| PromptDeviceCode = "device_code" |
| PromptLink = "link" |
| - PromptTerminal = "terminal" |
| + // PromptAuthorize is Claude's sign-in with no terminal (Paul, |
| + // 2026-11-10): the runner runs the unmodified `claude setup-token` |
| + // itself and shows the authorize URL the CLI prints; the person signs |
| + // in at Anthropic, which shows a one-time code; the page seals the |
| + // code to the runner (EndpointClaudeCode, Attempt the prompt's), and |
| + // the runner types it into the waiting CLI. The token the CLI prints |
| + // is kept as a pasted one is. A Claude Connect with Kind subscription |
| + // and not SameMachine starts it; the record is kind subscription |
| + // while it connects and kind token once healthy. With no URL and |
| + // Attempt 0 the runner is starting the CLI; with no URL and an |
| + // Attempt, that attempt's code was sent and the runner is finishing. |
| + PromptAuthorize = "authorize_link" |
| ) |
| +// MaxCodeAttempts bounds the codes one sign-in attempt takes: a wrong |
| +// code asks for another (the same link while the CLI waits, a new link |
| +// when it had to start again), up to this many. |
| +const MaxCodeAttempts = 5 |
| + |
| // ConnectReasons end a connection attempt in error. Never provider text. |
| var ConnectReasons = map[string]bool{ |
| "": true, |
| @@ -71,11 +87,15 @@ type Headroom struct { |
| // ConnectPrompt is what a connecting card shows: Kind is a Prompt* |
| // constant; URL is the provider's own page and Code the provider's |
| -// display code (device code only). Neither is a secret. |
| +// display code (device code only). Neither is a secret. For |
| +// PromptAuthorize, Attempt is the code attempt the page seals for (from |
| +// 1) and WrongCode says the last code did not work. |
| type ConnectPrompt struct { |
| - Kind string `json:"kind"` |
| - URL string `json:"url"` |
| - Code string `json:"code"` |
| + Kind string `json:"kind"` |
| + URL string `json:"url"` |
| + Code string `json:"code"` |
| + Attempt int64 `json:"attempt,omitempty"` |
| + WrongCode bool `json:"wrong_code,omitempty"` |
| } |
| // Connection is GET /api/v1/connections/{id}: one of the person's own |
| @@ -243,6 +263,12 @@ const ( |
| PromptToken = "token" |
| // EndpointAnthropic is the endpoint a Claude token is bound to. |
| EndpointAnthropic = "https://api.anthropic.com:443" |
| + // EndpointClaudeCode is what a sealed sign-in code is bound to: the |
| + // redirect of the authorize URL that made it (PromptAuthorize). A |
| + // box with it is a code, typed into the waiting CLI and never kept; |
| + // a box with EndpointAnthropic is a token. Neither is taken as the |
| + // other. |
| + EndpointClaudeCode = "https://platform.claude.com/oauth/code/callback" |
| // SealedTTL is how long a sealed box may wait to be opened. |
| SealedTTL = 10 * time.Minute |
| // MaxSealedBytes caps a box (base64 included). |
diff --git a/internal/wire/connections_test.go b/internal/wire/connections_test.go| index 85db134e..8b58e624 100644 |
| --- a/internal/wire/connections_test.go |
| +++ b/internal/wire/connections_test.go |
| @@ -64,7 +64,7 @@ func TestConnectionTypesCarryNoSecrets(t *testing.T) { |
| // TestConnectionFixturesCarryNoSecrets: the recorded documents a native |
| // app replays hold no secret-shaped key either. |
| func TestConnectionFixturesCarryNoSecrets(t *testing.T) { |
| - for _, name := range []string{"api/connections.json", "api/connection-connecting-codex.json", "api/connect-request.json", "api/event-connection.json", "frames/connect.json", "frames/cancel_connect.json", "frames/connection.json", "frames/hello.json", "frames/reply-usage.json", "frames/usage.json", "frames/disconnect.json", "frames/sync.json", "frames/preference.json", "api/preferences.json", "api/event-preference.json"} { |
| + for _, name := range []string{"api/connections.json", "api/connection-connecting-codex.json", "api/connection-signing-in-claude.json", "api/connect-request.json", "api/event-connection.json", "frames/connect.json", "frames/cancel_connect.json", "frames/connection.json", "frames/hello.json", "frames/reply-usage.json", "frames/usage.json", "frames/disconnect.json", "frames/sync.json", "frames/preference.json", "api/preferences.json", "api/event-preference.json"} { |
| // seal_key is public (spec §2.4). |
| raw := strings.ReplaceAll(strings.ToLower(string(wiretest.Fixture(name))), `"seal_key"`, "") |
| for _, bad := range []string{"token\"", "secret", "credential", "password", "sealed", "_key", "api_key", "access_token", "refresh"} { |
diff --git a/internal/wire/wiretest/fixtures.go b/internal/wire/wiretest/fixtures.go| index 4d5ea6ed..06a9995a 100644 |
| --- a/internal/wire/wiretest/fixtures.go |
| +++ b/internal/wire/wiretest/fixtures.go |
| @@ -99,13 +99,13 @@ func APIType(name string) any { |
| return &wire.AskQuestion{} |
| case "connections.json": |
| return &wire.ConnectionList{} |
| - case "connection-connecting-codex.json": |
| + case "connection-connecting-codex.json", "connection-signing-in-claude.json": |
| return &wire.Connection{} |
| case "connect-request.json": |
| return &wire.Connect{} |
| case "preferences.json": |
| return &wire.Preferences{} |
| - case "connection-secret.json": |
| + case "connection-secret.json", "connection-code.json": |
| return &wire.Sealed{} |
| case "duplicate-request.json": |
| return &wire.MarkDuplicate{} |
diff --git a/internal/wire/wiretest/testdata/api/connection-code.json b/internal/wire/wiretest/testdata/api/connection-code.json| new file mode 100644 |
| index 00000000..9f8b3ceb |
| --- /dev/null |
| +++ b/internal/wire/wiretest/testdata/api/connection-code.json |
| @@ -0,0 +1 @@ |
| +{"box":"c2VhbGVkLWJveC1wbGFjZWhvbGRlcg==","runner_id":"rn_0001","connection_id":"cn_0004","provider":"claude","endpoint":"https://platform.claude.com/oauth/code/callback","attempt":2,"expires_at":"2026-11-10T10:12:00Z"} |
| \ No newline at end of file |
diff --git a/internal/wire/wiretest/testdata/api/connection-signing-in-claude.json b/internal/wire/wiretest/testdata/api/connection-signing-in-claude.json| new file mode 100644 |
| index 00000000..32203869 |
| --- /dev/null |
| +++ b/internal/wire/wiretest/testdata/api/connection-signing-in-claude.json |
| @@ -0,0 +1 @@ |
| +{"id":"cn_0004","revision":4,"runner_id":"rn_0001","local_id":"","provider":"claude","kind":"subscription","label":"","state":"connecting","reason":"","plan":"","headroom":null,"prompt":{"kind":"authorize_link","url":"https://claude.com/cai/oauth/authorize?code=true\u0026client_id=fake\u0026response_type=code\u0026redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback\u0026state=fake-state","code":"","attempt":2,"wrong_code":true},"created_at":"2026-11-10T10:00:00Z","updated_at":"2026-11-10T10:02:00Z","expires_at":null,"expires_estimated":false} |
| \ No newline at end of file |