Coverage for src/ai_shell/claude_login.py: 87%
111 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
1"""Drive ``claude auth login`` from the host instead of through the container TTY.
3Inside a dev container the OAuth callback can never reach Claude Code, so
4login falls back to the manual flow: Claude prints a ~600 character
5authorize URL and waits for the code the browser shows afterwards. Doing
6that through ``docker exec -it`` on Windows is fragile in two ways:
8* The URL wraps in the TTY and a copied, mangled URL still signs you in,
9 but with a broken ``state``; the code then fails with "That code wasn't
10 accepted ... from an earlier sign-in attempt".
11* Pasting the code into the Ink prompt through ConPTY often drops it.
13``claude auth login`` behaves well without a TTY: it prints the URL on one
14line and reads the code from standard input. So this module runs it over
15pipes, opens the URL itself (in the account's host Chrome through the
16DevTools port when there is one), and takes the code from a plain prompt
17on the host terminal.
18"""
20from __future__ import annotations
22import json
23import logging
24import re
25import subprocess
26import threading
27from collections.abc import Callable
28from http.client import HTTPConnection, HTTPException
29from queue import Empty, Queue
30from urllib.parse import quote
32logger = logging.getLogger(__name__)
34LOGIN_URL_PATTERN = re.compile(r"https://\S+oauth\S*", re.IGNORECASE)
35LOGIN_URL_TIMEOUT_SECONDS = 45.0
36LOGIN_EXIT_TIMEOUT_SECONDS = 120.0
37LOGIN_SUCCESS_MARKER = "Login successful"
40def extract_login_url(line: str) -> str | None:
41 """Return the OAuth authorize URL in *line*, or ``None``."""
42 match = LOGIN_URL_PATTERN.search(line)
43 if match is None:
44 return None
45 # Claude prints the URL followed by nothing, but be safe about trailing
46 # punctuation from any wrapper text.
47 return match.group(0).rstrip(".,)")
50def open_in_chrome(port: int, url: str) -> bool:
51 """Open *url* as a new tab in the host Chrome listening on *port*.
53 Uses the DevTools HTTP endpoint ``PUT /json/new?<url>`` from the host,
54 so the tab lands in the account's own profile window. The URL is
55 percent-encoded in full: passed raw, Chrome cuts it at the first ``&``
56 and the sign-in page fails with "Missing client_id parameter". Chrome
57 unescapes the query before opening it. Returns ``True`` only when
58 Chrome's reply shows the new tab carries the full URL.
59 """
60 connection = HTTPConnection("127.0.0.1", port, timeout=5)
61 try:
62 connection.request("PUT", f"/json/new?{quote(url, safe='')}")
63 response = connection.getresponse()
64 body = response.read()
65 if response.status != 200:
66 return False
67 except (OSError, HTTPException) as exc:
68 logger.debug("Could not open login URL in Chrome on port %s: %s", port, exc)
69 return False
70 finally:
71 connection.close()
72 try:
73 target = json.loads(body.decode("utf-8", "replace"))
74 except ValueError:
75 target = {}
76 opened = target.get("url", "") if isinstance(target, dict) else ""
77 if not _same_login_url(opened, url):
78 logger.warning("Chrome opened %r instead of the full login URL", opened)
79 return False
80 return True
83def _same_login_url(opened: str, wanted: str) -> bool:
84 """True when the tab Chrome reports carries every query parameter we sent."""
85 if not opened:
86 return False
87 wanted_query = wanted.split("?", 1)[1] if "?" in wanted else ""
88 opened_query = opened.split("?", 1)[1] if "?" in opened else ""
89 wanted_params = {part.split("=", 1)[0] for part in wanted_query.split("&") if part}
90 opened_params = {part.split("=", 1)[0] for part in opened_query.split("&") if part}
91 return wanted_params <= opened_params
94def _pump(stream: object, queue: Queue[str | None]) -> None:
95 for line in iter(stream.readline, ""): # type: ignore[attr-defined]
96 queue.put(line)
97 queue.put(None)
100def run_piped_login(
101 args: list[str],
102 *,
103 open_url: Callable[[str], bool],
104 prompt_code: Callable[[], str],
105 echo: Callable[[str], None] | None = None,
106 url_timeout: float = LOGIN_URL_TIMEOUT_SECONDS,
107 exit_timeout: float = LOGIN_EXIT_TIMEOUT_SECONDS,
108) -> int | None:
109 """Run *args* (a ``claude auth login`` command) over pipes.
111 Waits for the authorize URL, hands it to *open_url*, asks *prompt_code*
112 for the code and writes it to the process. Returns the exit code, or
113 ``None`` when no URL appeared within *url_timeout* (the caller should
114 fall back to an interactive login). *echo* receives every other output
115 line so the user still sees what Claude says.
116 """
117 echo = echo or (lambda _line: None)
118 logger.debug("piped login: %s", " ".join(args))
119 proc = subprocess.Popen( # noqa: S603
120 args,
121 stdin=subprocess.PIPE,
122 stdout=subprocess.PIPE,
123 stderr=subprocess.STDOUT,
124 text=True,
125 bufsize=1,
126 )
127 assert proc.stdin is not None and proc.stdout is not None
128 lines: Queue[str | None] = Queue()
129 threading.Thread(target=_pump, args=(proc.stdout, lines), daemon=True).start()
131 url: str | None = None
132 finished = False
133 output: list[str] = []
134 try:
135 while url is None and not finished:
136 try:
137 line = lines.get(timeout=url_timeout)
138 except Empty:
139 break
140 if line is None:
141 finished = True
142 break
143 output.append(line)
144 url = extract_login_url(line)
145 if url is None:
146 echo(line.rstrip("\n"))
148 if url is None:
149 proc.kill()
150 proc.wait()
151 logger.debug("piped login: no URL seen; output was %r", "".join(output))
152 return None
154 if not open_url(url):
155 echo("Open this URL in a browser signed in as the account:")
156 echo(url)
158 code = prompt_code().strip()
159 if not code:
160 proc.kill()
161 proc.wait()
162 return 1
163 proc.stdin.write(code + "\n")
164 proc.stdin.flush()
165 proc.stdin.close()
167 # Drain the rest so the user sees "Login successful" or the error.
168 while True:
169 try:
170 line = lines.get(timeout=exit_timeout)
171 except Empty:
172 proc.kill()
173 break
174 if line is None:
175 break
176 text = line.rstrip("\n")
177 # The prompt line itself has no newline until the code is typed;
178 # strip it so only Claude's verdict is echoed.
179 text = text.replace("Paste code here if prompted >", "").strip()
180 if text:
181 echo(text)
182 output.append(line)
183 return proc.wait(timeout=10)
184 finally:
185 if proc.poll() is None:
186 proc.kill()
187 proc.wait()
190def login_succeeded(exit_code: int | None) -> bool:
191 """True when :func:`run_piped_login` reports success."""
192 return exit_code == 0