|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Minimal, dependency-free Chrome DevTools Protocol client for the smoke gate. |
| 3 | +
|
| 4 | +Drives a running content_shell over CDP (default :9222): optionally overrides the |
| 5 | +user-agent, navigates to a URL, waits for a readiness JS expression, prints the |
| 6 | +document title, and writes a PNG screenshot. Stdlib only (no websocket-client) so |
| 7 | +it runs inside the build image with nothing extra installed. |
| 8 | +""" |
| 9 | +import argparse |
| 10 | +import base64 |
| 11 | +import json |
| 12 | +import os |
| 13 | +import socket |
| 14 | +import struct |
| 15 | +import sys |
| 16 | +import time |
| 17 | +import urllib.request |
| 18 | + |
| 19 | + |
| 20 | +def http_json(port, path): |
| 21 | + with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=5) as r: |
| 22 | + return json.load(r) |
| 23 | + |
| 24 | + |
| 25 | +def wait_endpoint(port, tries=40): |
| 26 | + for _ in range(tries): |
| 27 | + try: |
| 28 | + return http_json(port, "/json/version") |
| 29 | + except Exception: |
| 30 | + time.sleep(1) |
| 31 | + raise RuntimeError(f"DevTools endpoint on :{port} never came up") |
| 32 | + |
| 33 | + |
| 34 | +class WS: |
| 35 | + """Just enough RFC6455 client for CDP: masked text frames out, reassembled frames in.""" |
| 36 | + |
| 37 | + def __init__(self, url): |
| 38 | + assert url.startswith("ws://") |
| 39 | + host_port, _, self.path = url[5:].partition("/") |
| 40 | + self.path = "/" + self.path |
| 41 | + host, _, port = host_port.partition(":") |
| 42 | + self.sock = socket.create_connection((host, int(port or 80)), timeout=10) |
| 43 | + key = base64.b64encode(os.urandom(16)).decode() |
| 44 | + req = ( |
| 45 | + f"GET {self.path} HTTP/1.1\r\nHost: {host_port}\r\n" |
| 46 | + "Upgrade: websocket\r\nConnection: Upgrade\r\n" |
| 47 | + f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n" |
| 48 | + ) |
| 49 | + self.sock.sendall(req.encode()) |
| 50 | + buf = b"" |
| 51 | + while b"\r\n\r\n" not in buf: |
| 52 | + buf += self.sock.recv(4096) |
| 53 | + if b" 101 " not in buf.split(b"\r\n", 1)[0]: |
| 54 | + raise RuntimeError(f"ws handshake failed: {buf[:120]!r}") |
| 55 | + self._rest = buf.split(b"\r\n\r\n", 1)[1] |
| 56 | + |
| 57 | + def _recv(self, n): |
| 58 | + while len(self._rest) < n: |
| 59 | + chunk = self.sock.recv(65536) |
| 60 | + if not chunk: |
| 61 | + raise ConnectionError("ws closed") |
| 62 | + self._rest += chunk |
| 63 | + out, self._rest = self._rest[:n], self._rest[n:] |
| 64 | + return out |
| 65 | + |
| 66 | + def send(self, text): |
| 67 | + data = text.encode() |
| 68 | + hdr = bytearray([0x81]) # FIN + text |
| 69 | + n = len(data) |
| 70 | + if n < 126: |
| 71 | + hdr.append(0x80 | n) |
| 72 | + elif n < 65536: |
| 73 | + hdr.append(0x80 | 126) |
| 74 | + hdr += struct.pack(">H", n) |
| 75 | + else: |
| 76 | + hdr.append(0x80 | 127) |
| 77 | + hdr += struct.pack(">Q", n) |
| 78 | + mask = os.urandom(4) |
| 79 | + hdr += mask |
| 80 | + self.sock.sendall(bytes(hdr) + bytes(b ^ mask[i % 4] for i, b in enumerate(data))) |
| 81 | + |
| 82 | + def recv(self): |
| 83 | + payload = b"" |
| 84 | + while True: |
| 85 | + b0, b1 = self._recv(2) |
| 86 | + fin, opcode = b0 & 0x80, b0 & 0x0F |
| 87 | + length = b1 & 0x7F |
| 88 | + if length == 126: |
| 89 | + length = struct.unpack(">H", self._recv(2))[0] |
| 90 | + elif length == 127: |
| 91 | + length = struct.unpack(">Q", self._recv(8))[0] |
| 92 | + payload += self._recv(length) |
| 93 | + if opcode == 0x8: # close |
| 94 | + raise ConnectionError("ws close frame") |
| 95 | + if fin: |
| 96 | + return payload.decode(errors="replace") |
| 97 | + |
| 98 | + |
| 99 | +class CDP: |
| 100 | + def __init__(self, port): |
| 101 | + self.port = port |
| 102 | + self._enabled = [] |
| 103 | + self.connect() |
| 104 | + |
| 105 | + def connect(self): |
| 106 | + self.ws = WS(pick_page_target(self.port)) |
| 107 | + self._id = 0 |
| 108 | + for method in self._enabled: # re-arm domains on a fresh target |
| 109 | + self.call(method, _no_reconnect=True) |
| 110 | + if getattr(self, "_ua", None): # Leanback tears down targets; keep the UA sticky |
| 111 | + self.call("Network.enable", _no_reconnect=True) |
| 112 | + self.call("Network.setUserAgentOverride", {"userAgent": self._ua}, |
| 113 | + _no_reconnect=True) |
| 114 | + |
| 115 | + def call(self, method, params=None, timeout=30, _no_reconnect=False): |
| 116 | + if method.endswith(".enable") and method not in self._enabled: |
| 117 | + self._enabled.append(method) |
| 118 | + try: |
| 119 | + self._id += 1 |
| 120 | + mid = self._id |
| 121 | + self.ws.send(json.dumps({"id": mid, "method": method, "params": params or {}})) |
| 122 | + deadline = time.monotonic() + timeout |
| 123 | + while time.monotonic() < deadline: |
| 124 | + msg = json.loads(self.ws.recv()) |
| 125 | + if msg.get("id") == mid: |
| 126 | + if "error" in msg: |
| 127 | + raise RuntimeError(f"{method}: {msg['error']}") |
| 128 | + return msg.get("result", {}) |
| 129 | + raise TimeoutError(f"{method} timed out") |
| 130 | + except (ConnectionError, BrokenPipeError, OSError): |
| 131 | + if _no_reconnect: |
| 132 | + raise |
| 133 | + self.connect() # target was torn down (Leanback navigations) — re-attach |
| 134 | + return self.call(method, params, timeout, _no_reconnect=True) |
| 135 | + |
| 136 | + def evaluate(self, expr): |
| 137 | + r = self.call("Runtime.evaluate", |
| 138 | + {"expression": expr, "returnByValue": True, "awaitPromise": True}) |
| 139 | + return r.get("result", {}).get("value") |
| 140 | + |
| 141 | + |
| 142 | +def pick_page_target(port, tries=30): |
| 143 | + for _ in range(tries): |
| 144 | + try: |
| 145 | + for t in http_json(port, "/json"): |
| 146 | + if t.get("type") == "page" and t.get("webSocketDebuggerUrl"): |
| 147 | + return t["webSocketDebuggerUrl"] |
| 148 | + except Exception: |
| 149 | + pass |
| 150 | + time.sleep(1) |
| 151 | + raise RuntimeError("no page target with a ws url appeared") |
| 152 | + |
| 153 | + |
| 154 | +def main(): |
| 155 | + ap = argparse.ArgumentParser() |
| 156 | + ap.add_argument("--port", type=int, default=9222) |
| 157 | + ap.add_argument("--ua") |
| 158 | + ap.add_argument("--navigate") |
| 159 | + ap.add_argument("--out") |
| 160 | + ap.add_argument("--expect", default="!!document.body && document.body.innerText.length >= 0") |
| 161 | + ap.add_argument("--print", dest="print_expr") |
| 162 | + ap.add_argument("--ready-timeout", type=int, default=45) |
| 163 | + args = ap.parse_args() |
| 164 | + |
| 165 | + ver = wait_endpoint(args.port) |
| 166 | + print(f"browser UA (pre-override): {ver.get('User-Agent')}") |
| 167 | + |
| 168 | + cdp = CDP(args.port) |
| 169 | + cdp.call("Page.enable") |
| 170 | + cdp.call("Runtime.enable") |
| 171 | + if args.ua: |
| 172 | + cdp._ua = args.ua # sticky: re-applied by connect() after Leanback tears down the target |
| 173 | + cdp.call("Network.enable") |
| 174 | + cdp.call("Network.setUserAgentOverride", {"userAgent": args.ua}) |
| 175 | + print(f"UA override applied: {args.ua}") |
| 176 | + if args.navigate: |
| 177 | + cdp.call("Page.navigate", {"url": args.navigate}) |
| 178 | + |
| 179 | + deadline = time.monotonic() + args.ready_timeout |
| 180 | + ready = False |
| 181 | + while time.monotonic() < deadline: |
| 182 | + try: |
| 183 | + if cdp.evaluate(args.expect): |
| 184 | + ready = True |
| 185 | + break |
| 186 | + except Exception: |
| 187 | + pass |
| 188 | + time.sleep(1) |
| 189 | + |
| 190 | + title = cdp.evaluate("document.title") |
| 191 | + url = cdp.evaluate("document.location.href") |
| 192 | + ua_seen = cdp.evaluate("navigator.userAgent") |
| 193 | + body_len = cdp.evaluate("document.body ? document.body.innerText.length : -1") |
| 194 | + print(f"ready={ready} title={title!r} url={url!r} body_chars={body_len}") |
| 195 | + print(f"navigator.userAgent={ua_seen}") |
| 196 | + if args.print_expr: |
| 197 | + print(f"probe={cdp.evaluate(args.print_expr)}") |
| 198 | + |
| 199 | + if args.out: |
| 200 | + # Best-effort: headless SwiftShader (dead GPU process) can stall Page.captureScreenshot. |
| 201 | + # A paint failure must not fail the smoke — the DOM assertion above is the gate. |
| 202 | + try: |
| 203 | + shot = cdp.call("Page.captureScreenshot", {"format": "png"}, timeout=30) |
| 204 | + with open(args.out, "wb") as f: |
| 205 | + f.write(base64.b64decode(shot["data"])) |
| 206 | + print(f"screenshot: {args.out} ({os.path.getsize(args.out)} bytes)") |
| 207 | + except Exception as e: |
| 208 | + print(f"screenshot skipped ({type(e).__name__}: {e})") |
| 209 | + |
| 210 | + sys.exit(0 if ready else 2) |
| 211 | + |
| 212 | + |
| 213 | +if __name__ == "__main__": |
| 214 | + main() |
0 commit comments