返回 last30days-skill
chrome_cdp.py
根目录 / skills / last30days / scripts / lib / chrome_cdp.py
1 """Live Chrome cookie reader over the DevTools Protocol (CDP).
2
3 An EXTRA-host cookie lookup for the bird backend: when a Chrome/Chromium
4 instance is running with a remote-debugging endpoint and the user is signed
5 into x.com in it, that live session holds the ``auth_token`` + ``ct0`` cookies
6 bird needs — even on Linux, where the on-disk cookie store cannot be decrypted
7 here. This module talks to that endpoint and pulls the pair via
8 ``Network.getAllCookies``.
9
10 Deliberate constraints (see docs/plans/2026-08-31 X plan):
11
12 * **Extras only.** The engine only calls this on extra hosts (Linux, Mac mini,
13 Darwin agentcookie sink, or ``AGENTCOOKIE=on``); the gating lives in
14 ``env.x_extras_enabled``. On a plain MacBook this is never called, so no
15 socket is opened (AE8).
16 * **No port scan.** Endpoint resolution is: ``BROWSER_CDP_URL`` if set, else
17 port ``18800`` if it answers as Chrome, else ``9222`` + the X display number.
18 No 9222..9232 sweep. ``18800`` is NOT box-chrome's built-in default (that is
19 ``9222`` + the display number); it is the last30days extras NUX convention —
20 the agent launches the throwaway login Chrome with
21 ``SAND_CHROME_REMOTE_DEBUG_PORT=18800`` (see SKILL.md), so a leftover daily
22 profile on ``9222``+display is not mistaken for the login session. If ``18800``
23 answers with no complete pair we fall through; if it answers with a stale or
24 wrong pair, pin ``BROWSER_CDP_URL`` after the NUX rather than scanning.
25 * **Require a Chrome page target.** ``/json/version`` must report a Chrome /
26 Chromium browser (a Node inspector is rejected) and ``/json`` must expose a
27 ``page`` target.
28 * **Explicit consent required.** ``BROWSER_CONSENT=true`` or an explicit
29 Chromium/``auto`` selection permits CDP. ``FROM_BROWSER=off`` or a recorded
30 refusal blocks it, including when an endpoint is configured.
31 * Stdlib only: a tiny RFC 6455 websocket client, no third-party dependency.
32 * Cookie **values are never logged** — only counts and endpoints.
33 * First complete pair wins: both ``auth_token`` and ``ct0`` must be present.
34 """
35
36 from __future__ import annotations
37
38 import base64
39 import json
40 import os
41 import re
42 import socket
43 import struct
44 import urllib.error
45 import urllib.parse
46 import urllib.request
47 from typing import Any, Dict, List, Optional, Tuple
48
49 from . import log
50
51 X_COOKIE_NAMES = ("auth_token", "ct0")
52 _BASE_DEBUG_PORT = 9222
53 # The last30days extras NUX convention port: the agent launches the throwaway
54 # login Chrome with SAND_CHROME_REMOTE_DEBUG_PORT=18800 so this lookup finds it.
55 # NOT box-chrome's built-in default (which is 9222 + the X display number).
56 _BOX_CHROME_PORT = 18800
57
58 _HTTP_TIMEOUT = 1.5 # /json and /json/version fetches
59 _WS_TIMEOUT = 3.0 # websocket exchange
60 _MAX_HTTP_JSON_BYTES = 4 * 1024 * 1024
61 _LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})
62 _WS_TARGET_RE = re.compile(r"/[A-Za-z0-9._~:/?\[\]@!$&'()*+,;=%-]+")
63
64
65 class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
66 """Refuse HTTP 3xx redirects on loopback CDP requests."""
67
68 def redirect_request(self, req, fp, code, msg, headers, newurl):
69 if fp is not None:
70 try:
71 fp.close()
72 except OSError:
73 pass
74 raise urllib.error.HTTPError(
75 req.full_url, code, f"CDP redirects are refused: {msg}", headers, None
76 )
77
78
79 def _build_cdp_opener() -> urllib.request.OpenerDirector:
80 """Build an explicit HTTP-only, no-proxy, no-redirect opener for CDP."""
81 opener = urllib.request.OpenerDirector()
82 opener.add_handler(urllib.request.ProxyHandler({}))
83 opener.add_handler(urllib.request.HTTPHandler())
84 opener.add_handler(_NoRedirectHandler())
85 opener.add_handler(urllib.request.HTTPDefaultErrorHandler())
86 opener.add_handler(urllib.request.HTTPErrorProcessor())
87 return opener
88
89
90 _CDP_OPENER = _build_cdp_opener()
91
92
93 def _format_netloc(host: str, port: int) -> str:
94 return f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
95
96
97 def _parse_cdp_url(
98 raw: str,
99 *,
100 allowed_schemes: Tuple[str, ...],
101 allow_implicit_http: bool = False,
102 require_base_path: bool = False,
103 ) -> Optional[Tuple[str, str, int, str]]:
104 """Strictly validate a loopback CDP URL and return ``(scheme, host, port, target)``."""
105 if not isinstance(raw, str):
106 return None
107 if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in raw) or not raw.isascii():
108 return None
109 candidate = raw.strip(" ") if allow_implicit_http else raw
110 if not candidate or any(ch.isspace() for ch in candidate):
111 return None
112 if allow_implicit_http and "://" not in candidate:
113 candidate = f"http://{candidate}"
114 try:
115 parts = urllib.parse.urlsplit(candidate)
116 except ValueError:
117 return None
118 scheme = parts.scheme.lower()
119 if scheme not in allowed_schemes:
120 return None
121 if parts.username is not None or parts.password is not None or "@" in parts.netloc:
122 return None
123 if parts.fragment or "#" in candidate:
124 return None
125 host = (parts.hostname or "").lower()
126 if host not in _LOOPBACK_HOSTS:
127 return None
128 try:
129 port = parts.port
130 except ValueError:
131 return None
132 if port is None or not (1 <= port <= 65535):
133 return None
134
135 target = parts.path + (f"?{parts.query}" if parts.query else "")
136 if scheme == "ws":
137 if not _WS_TARGET_RE.fullmatch(target):
138 return None
139 return (scheme, host, port, target)
140
141 if require_base_path:
142 if parts.query or parts.path not in ("", "/"):
143 return None
144 return (scheme, host, port, "")
145
146 if target and target != "/" and not _WS_TARGET_RE.fullmatch(target):
147 return None
148 return (scheme, host, port, target or "/")
149
150
151 def _log(msg: str) -> None:
152 log.source_log("chrome-cdp", msg, tty_only=False)
153
154
155 def _display_number() -> Optional[int]:
156 """Parse the X display number from ``$DISPLAY`` (e.g. ``:99`` -> 99)."""
157 disp = os.environ.get("DISPLAY") or ""
158 match = re.search(r":(\d+)", disp)
159 if not match:
160 return None
161 try:
162 return int(match.group(1))
163 except ValueError:
164 return None
165
166
167 def _normalize_base(url: str) -> Optional[str]:
168 """Return a validated canonical loopback ``http://host:port`` or ``ws://...`` endpoint."""
169 parsed = _parse_cdp_url(
170 url,
171 allowed_schemes=("http", "ws"),
172 allow_implicit_http=True,
173 require_base_path=True,
174 )
175 if parsed is None:
176 return None
177 scheme, host, port, target = parsed
178 netloc = _format_netloc(host, port)
179 if scheme == "ws":
180 return f"ws://{netloc}{target}"
181 return f"http://{netloc}"
182
183
184 def candidate_endpoints(config: Optional[Dict[str, Any]] = None) -> List[str]:
185 """Debug endpoints to try, most-specific first (no port scan).
186
187 Order: an explicit ``BROWSER_CDP_URL`` (used exclusively when set), else the
188 last30days extras NUX port ``18800`` (where the agent launches the throwaway
189 login Chrome via ``SAND_CHROME_REMOTE_DEBUG_PORT=18800``), then ``9222`` +
190 the X display number (box-chrome's own built-in default). ``18800`` is tried
191 first but read_x_cookies falls through when it yields no complete pair, so a
192 logged-out Chrome there never shadows a logged-in daily profile.
193 """
194 explicit = ""
195 if config is not None:
196 raw_cfg = config.get("BROWSER_CDP_URL")
197 if raw_cfg is not None:
198 explicit = str(raw_cfg).strip(" ")
199 if not explicit:
200 explicit = (os.environ.get("BROWSER_CDP_URL") or "").strip(" ")
201 if explicit:
202 normalized = _normalize_base(explicit)
203 return [normalized] if normalized is not None else []
204
205 endpoints = [f"http://127.0.0.1:{_BOX_CHROME_PORT}"]
206 display = _display_number()
207 display_port = _BASE_DEBUG_PORT + (display or 0)
208 if 1 <= display_port <= 65535:
209 endpoints.append(f"http://127.0.0.1:{display_port}")
210 return endpoints
211
212
213 def _http_get_json(url: str) -> Optional[Any]:
214 """GET loopback CDP ``url`` (no proxy, no redirects) and parse JSON, or None."""
215 parsed = _parse_cdp_url(url, allowed_schemes=("http",), allow_implicit_http=False)
216 if parsed is None:
217 return None
218 scheme, host, port, target = parsed
219 safe_url = f"{scheme}://{_format_netloc(host, port)}{target}"
220 try:
221 with _CDP_OPENER.open(safe_url, timeout=_HTTP_TIMEOUT) as resp:
222 body = resp.read(_MAX_HTTP_JSON_BYTES)
223 except (OSError, ValueError, OverflowError, UnicodeEncodeError):
224 return None
225 try:
226 return json.loads(body)
227 except (json.JSONDecodeError, TypeError, UnicodeDecodeError):
228 return None
229
230
231 def _is_chrome_endpoint(base: str) -> bool:
232 """True when ``base``/json/version reports a Chrome/Chromium browser.
233
234 Rejects a Node ``--inspect`` endpoint (whose ``Browser`` is ``node.js/...``)
235 so we never mistake an inspector for a browser.
236 """
237 version = _http_get_json(f"{base}/json/version")
238 if not isinstance(version, dict):
239 return False
240 browser = str(version.get("Browser") or "").lower()
241 return "chrome" in browser or "chromium" in browser
242
243
244 def _page_ws_url(base: str) -> Optional[str]:
245 """Find a Chrome PAGE target's webSocketDebuggerUrl on ``base``."""
246 base_parsed = _parse_cdp_url(
247 base, allowed_schemes=("http",), allow_implicit_http=False, require_base_path=True
248 )
249 if base_parsed is None:
250 return None
251 _, base_host, base_port, _ = base_parsed
252 targets = _http_get_json(f"{base}/json")
253 if not isinstance(targets, list):
254 return None
255 for target in targets:
256 if not isinstance(target, dict):
257 continue
258 if target.get("type") != "page":
259 continue
260 ws_url = target.get("webSocketDebuggerUrl")
261 if not isinstance(ws_url, str):
262 continue
263 ws_parsed = _parse_cdp_url(ws_url, allowed_schemes=("ws",), allow_implicit_http=False)
264 if ws_parsed is None:
265 continue
266 _, ws_host, ws_port, ws_target = ws_parsed
267 if ws_host != base_host or ws_port != base_port:
268 _log(
269 f"refusing cross-endpoint webSocketDebuggerUrl host/port "
270 f"({ws_host}:{ws_port} != {base_host}:{base_port})"
271 )
272 continue
273 return f"ws://{_format_netloc(ws_host, ws_port)}{ws_target}"
274 return None
275
276
277 class _WSConn:
278 """Minimal RFC 6455 websocket client (text frames only) over a TCP socket."""
279
280 def __init__(self, sock: socket.socket) -> None:
281 self._sock = sock
282 self._buf = b""
283
284 def _fill(self, n: int) -> Optional[bytes]:
285 while len(self._buf) < n:
286 try:
287 chunk = self._sock.recv(65536)
288 except OSError:
289 return None
290 if not chunk:
291 return None
292 self._buf += chunk
293 out, self._buf = self._buf[:n], self._buf[n:]
294 return out
295
296 @classmethod
297 def connect(cls, ws_url: str, timeout: float) -> Optional["_WSConn"]:
298 # Plaintext loopback ws:// only. A wss:// URL would need real TLS;
299 # refuse non-ws, non-loopback, malformed, or control-char URLs before
300 # opening any socket.
301 parsed = _parse_cdp_url(ws_url, allowed_schemes=("ws",), allow_implicit_http=False)
302 if parsed is None:
303 return None
304 _, host, port, path = parsed
305 host_header = _format_netloc(host, port)
306 sock: Optional[socket.socket] = None
307 try:
308 sock = socket.create_connection((host, port), timeout=timeout)
309 sock.settimeout(timeout)
310 key = base64.b64encode(os.urandom(16)).decode("ascii")
311 handshake = (
312 f"GET {path} HTTP/1.1\r\n"
313 f"Host: {host_header}\r\n"
314 "Upgrade: websocket\r\n"
315 "Connection: Upgrade\r\n"
316 f"Sec-WebSocket-Key: {key}\r\n"
317 "Sec-WebSocket-Version: 13\r\n\r\n"
318 )
319 sock.sendall(handshake.encode("ascii"))
320 conn = cls(sock)
321 header = conn._read_http_headers()
322 if header is None or b" 101 " not in header.split(b"\r\n", 1)[0]:
323 sock.close()
324 return None
325 return conn
326 except (OSError, ValueError, OverflowError, UnicodeEncodeError):
327 if sock is not None:
328 try:
329 sock.close()
330 except OSError:
331 pass
332 return None
333
334 def _read_http_headers(self) -> Optional[bytes]:
335 while b"\r\n\r\n" not in self._buf:
336 try:
337 chunk = self._sock.recv(65536)
338 except OSError:
339 return None
340 if not chunk:
341 return None
342 self._buf += chunk
343 head, _, rest = self._buf.partition(b"\r\n\r\n")
344 self._buf = rest # any bytes after the header belong to the frame stream
345 return head
346
347 def send_text(self, payload: bytes) -> bool:
348 header = bytearray([0x81]) # FIN + text opcode
349 mask = os.urandom(4)
350 length = len(payload)
351 if length < 126:
352 header.append(0x80 | length)
353 elif length < 65536:
354 header.append(0x80 | 126)
355 header += struct.pack(">H", length)
356 else:
357 header.append(0x80 | 127)
358 header += struct.pack(">Q", length)
359 header += mask
360 masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
361 try:
362 self._sock.sendall(bytes(header) + masked)
363 return True
364 except OSError:
365 return False
366
367 def recv_message(self) -> Optional[bytes]:
368 """Read one (possibly fragmented) data message; skip control frames."""
369 message = b""
370 while True:
371 first = self._fill(2)
372 if first is None:
373 return None
374 fin = first[0] & 0x80
375 opcode = first[0] & 0x0F
376 length = first[1] & 0x7F
377 masked = first[1] & 0x80
378 if length == 126:
379 ext = self._fill(2)
380 if ext is None:
381 return None
382 length = struct.unpack(">H", ext)[0]
383 elif length == 127:
384 ext = self._fill(8)
385 if ext is None:
386 return None
387 length = struct.unpack(">Q", ext)[0]
388 mask = self._fill(4) if masked else b""
389 payload = self._fill(length) if length else b""
390 if length and payload is None:
391 return None
392 if masked and payload:
393 payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
394 if opcode == 0x8: # close
395 return None
396 if opcode in (0x9, 0xA): # ping / pong — ignore
397 continue
398 message += payload or b""
399 if fin:
400 return message
401
402 def close(self) -> None:
403 try:
404 self._sock.close()
405 except OSError:
406 pass
407
408
409 def _get_all_cookies(ws_url: str) -> Optional[List[Dict[str, Any]]]:
410 """Run Network.enable then Network.getAllCookies over one CDP websocket."""
411 conn = _WSConn.connect(ws_url, _WS_TIMEOUT)
412 if conn is None:
413 return None
414 try:
415 if not conn.send_text(json.dumps({"id": 1, "method": "Network.enable"}).encode("utf-8")):
416 return None
417 if not conn.send_text(json.dumps({"id": 2, "method": "Network.getAllCookies"}).encode("utf-8")):
418 return None
419 # Read frames until the id=2 response arrives (skipping enable's ack and
420 # any Network.* events the browser pushes after enable).
421 for _ in range(200):
422 raw = conn.recv_message()
423 if raw is None:
424 return None
425 try:
426 msg = json.loads(raw)
427 except (json.JSONDecodeError, UnicodeDecodeError):
428 continue
429 if isinstance(msg, dict) and msg.get("id") == 2:
430 result = msg.get("result")
431 if isinstance(result, dict) and isinstance(result.get("cookies"), list):
432 return result["cookies"]
433 return None
434 return None
435 finally:
436 conn.close()
437
438
439 # Registrable X hosts we accept cookies from, in preference order. Matched
440 # EXACTLY after stripping a single leading dot (never endswith), so a lookalike
441 # like ``notx.com`` is not treated as x.com and cannot contribute a cookie.
442 _ALLOWED_X_HOSTS = ("x.com", "twitter.com")
443
444
445 def _canonical_partition(raw: Any) -> Optional[str]:
446 """Canonicalize a CDP ``partitionKey`` to a hashable scope tag.
447
448 CDP may send ``partitionKey`` as a string, as an object
449 (``{"topLevelSite": ..., "hasCrossSiteAncestor": ...}``), or omit it for an
450 unpartitioned cookie. Returns None for "unpartitioned" (so all unpartitioned
451 cookies share one scope) and a stable string otherwise (so a partitioned
452 cookie never shares a scope with an unpartitioned one, nor with a different
453 partition).
454 """
455 if raw is None:
456 return None
457 if isinstance(raw, str):
458 return raw.strip() or None
459 if isinstance(raw, dict):
460 try:
461 return json.dumps(raw, sort_keys=True, separators=(",", ":"))
462 except (TypeError, ValueError):
463 return repr(sorted((str(k), str(v)) for k, v in raw.items()))
464 return str(raw)
465
466
467 def _pair_from_cookies(cookies: List[Dict[str, Any]]) -> Dict[str, str]:
468 """Extract a complete X cookie pair from ONE cookie scope.
469
470 ``auth_token`` and ``ct0`` are only a usable pair when they share the SAME
471 cookie scope — same registrable host AND same ``path`` AND same partition.
472 Chrome can hold duplicate names across scopes (different ``path`` or
473 ``partitionKey``), so pairing across the whole host jar could hand Bird a
474 token from one session scope and a ct0 from another, and a valid login would
475 look unauthorized. We therefore group by the full scope key
476 ``(host, path, partition)`` and only ever pair WITHIN one scope.
477
478 Host is matched EXACTLY against ``_ALLOWED_X_HOSTS`` after stripping one
479 leading dot (never ``endswith``, so ``notx.com`` never counts). Missing
480 ``path`` is treated as ``/``; ``partitionKey`` is canonicalized so
481 unpartitioned cookies stay together. Preference order for the returned pair:
482 host ``x.com`` before ``twitter.com``; unpartitioned before partitioned;
483 path ``/`` before other paths. A scope with only one of the two cookies is
484 skipped so a later complete scope still wins. When no scope has a complete
485 pair, a single scope's partial is returned for the caller's incomplete-pair
486 log — never a cross-scope mix.
487 """
488 # scopes[host][(path, partition)] -> {name: value}
489 scopes: Dict[str, Dict[tuple, Dict[str, str]]] = {host: {} for host in _ALLOWED_X_HOSTS}
490 for cookie in cookies:
491 if not isinstance(cookie, dict):
492 continue
493 name = cookie.get("name")
494 value = cookie.get("value")
495 if name not in X_COOKIE_NAMES or not (isinstance(value, str) and value):
496 continue
497 host = str(cookie.get("domain") or "").lstrip(".").lower()
498 if host not in scopes:
499 continue
500 path = cookie.get("path")
501 if not isinstance(path, str) or not path:
502 path = "/"
503 scope_key = (path, _canonical_partition(cookie.get("partitionKey")))
504 jar = scopes[host].setdefault(scope_key, {})
505 # First value WITHIN this scope only — never across scopes.
506 jar.setdefault(name, value)
507
508 def _scope_rank(item: tuple) -> tuple:
509 (path, partition), _jar = item
510 # unpartitioned (None) before partitioned; path "/" before others.
511 return (partition is not None, path != "/", path)
512
513 for host in _ALLOWED_X_HOSTS:
514 for _key, jar in sorted(scopes[host].items(), key=_scope_rank):
515 if all(name in jar for name in X_COOKIE_NAMES):
516 return {name: jar[name] for name in X_COOKIE_NAMES}
517
518 for host in _ALLOWED_X_HOSTS:
519 for _key, jar in sorted(scopes[host].items(), key=_scope_rank):
520 if jar:
521 return dict(jar)
522 return {}
523
524
525 def cookie_access_allowed(config: Optional[Dict[str, Any]] = None) -> bool:
526 from . import env
527
528 env_consent = {
529 name: env.read_secret_env(name)
530 for name in ("BROWSER_CONSENT", "FROM_BROWSER")
531 }
532 if env.cookie_access_denied(env_consent):
533 return False
534 config = config or {}
535 if env.cookie_access_denied(config):
536 return False
537 from_browser = str(config.get("FROM_BROWSER") or "").strip().lower()
538 consent = config.get("BROWSER_CONSENT")
539 if consent is not None:
540 return str(consent).strip().lower() in {"1", "true", "yes", "on"}
541 requested = {browser.strip() for browser in from_browser.split(",")}
542 return bool(requested & {"auto", "chrome", "brave", "edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium"})
543
544
545 def read_x_cookies(config: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, str]]:
546 """Return the complete X cookie pair from a live Chrome session, or None.
547
548 Resolves the debug endpoint (BROWSER_CDP_URL, else 18800 if Chrome, else
549 9222+$DISPLAY), requires a Chrome page target, and calls
550 ``Network.getAllCookies``. Returns ``{"auth_token", "ct0"}`` only when BOTH
551 cookies are found (no half-pair). Without explicit consent, returns None
552 before resolving endpoints or opening a socket. Any failure returns None
553 so the caller falls through.
554 Never raises.
555
556 Host gating (extras-only) lives in the caller (``env.x_extras_enabled``);
557 on a plain MacBook this function is never invoked, so no socket is opened.
558 """
559 if not cookie_access_allowed(config):
560 return None
561
562 for base in candidate_endpoints(config):
563 # Plaintext loopback http:// and ws:// only. Defense in depth even if
564 # candidate_endpoints is overridden: refuse TLS, remote hosts, userinfo,
565 # fragments, invalid ports, or control characters before any network I/O.
566 parsed = _parse_cdp_url(
567 base,
568 allowed_schemes=("http", "ws"),
569 allow_implicit_http=False,
570 require_base_path=True,
571 )
572 if parsed is None:
573 _log(f"refusing unsupported or non-loopback CDP endpoint {base!r}")
574 continue
575 scheme, host, port, target = parsed
576 netloc = _format_netloc(host, port)
577 # ws:// endpoints (rare, explicit) connect directly; http bases are
578 # validated as Chrome and asked for a page target.
579 if scheme == "ws":
580 ws_url = f"ws://{netloc}{target}"
581 else:
582 http_base = f"http://{netloc}"
583 if not _is_chrome_endpoint(http_base):
584 continue
585 ws_url = _page_ws_url(http_base)
586 if not ws_url:
587 continue
588 cookies = _get_all_cookies(ws_url)
589 if not cookies:
590 continue
591 found = _pair_from_cookies(cookies)
592 if all(name in found for name in X_COOKIE_NAMES):
593 _log(f"read a complete X cookie pair from a live Chrome session at {base}")
594 return {name: found[name] for name in X_COOKIE_NAMES}
595 if found:
596 _log(
597 f"live Chrome at {base} had an incomplete pair "
598 f"({sorted(found)}); ignoring per no-half-pair rule"
599 )
600 return None
601
601 lines PYTHON