diff --git a/bin/deck-browser b/bin/deck-browser index 9f0c697..307d0db 100755 --- a/bin/deck-browser +++ b/bin/deck-browser @@ -1,273 +1,142 @@ -#!/usr/bin/env python3 -"""deck-browser — read (do not drive) the Chrome running on the Steam Deck. +#!/usr/bin/env bash +# deck-browser — read the Chrome running on the Steam Deck from arceus. +# +# Chrome on the Deck exposes a CDP WebSocket at 127.0.0.1:9222/devtools/browser once +# "Allow remote debugging for this browser instance" is ticked at +# chrome://inspect/#remote-debugging. Playwright attaches to a ws:// endpoint directly +# (connectOverCDP accepts one), so this is a thin wrapper that opens the SSH tunnel and +# drives `playwright-cli` — not a protocol client of its own. +# +# deck-browser tabs list tabs (index, title, url) +# deck-browser text --match linkedin innerText of a tab +# deck-browser html --index 3 outerHTML +# deck-browser shot --out /tmp/x.png screenshot (default /tmp/deck-shot-.png) +# deck-browser status user agent of the attached browser +# deck-browser cli tab-select 2 pass any playwright-cli command through +# +# Options: --index N | --match SUBSTR (default: current tab), --limit CHARS (default 8000). +# Read-only by intent: no click/type/navigate helper exists here, because driving an +# authenticated session is what gets accounts restricted. +# +# Env: DECK_HOST (deck), DECK_CDP_PORT (9222), DECK_SESSION (deck) +set -euo pipefail -Chrome on the Deck exposes a CDP WebSocket at 127.0.0.1:9222/devtools/browser once -"Allow remote debugging for this browser instance" is ticked at -chrome://inspect/#remote-debugging. This tool opens an SSH tunnel to that loopback -port and talks CDP directly, using only the Python standard library. +HOST=${DECK_HOST:-deck} +PORT=${DECK_CDP_PORT:-9222} +SESSION=${DECK_SESSION:-deck} +WS="ws://127.0.0.1:${PORT}/devtools/browser" -Deliberately read-only: list tabs, dump text/HTML, take a screenshot. There is no -click, type or navigate command, because driving a logged-in session is what gets -accounts restricted. `--unsafe-eval` exists for one-off inspection and is opt-in. +die() { echo "deck-browser: $*" >&2; exit 1; } -Usage: - deck-browser tabs - deck-browser text [--index N | --match SUBSTR] [--limit CHARS] - deck-browser html [--index N | --match SUBSTR] [--limit CHARS] - deck-browser shot [--index N | --match SUBSTR] [--out FILE.png] - deck-browser status +port_open() { (exec 3<>"/dev/tcp/127.0.0.1/${PORT}") 2>/dev/null; } -Environment: DECK_HOST (default "deck"), DECK_CDP_PORT (default 9222). -""" +ensure_tunnel() { + port_open && return 0 + ssh -o BatchMode=yes -o ExitOnForwardFailure=yes -f -N \ + -L "${PORT}:127.0.0.1:${PORT}" "$HOST" \ + || die "cannot open tunnel to ${HOST} — is the Deck awake?" + for _ in $(seq 1 25); do port_open && return 0; sleep 0.2; done + die "no CDP endpoint on 127.0.0.1:${PORT}. + On the Deck: chrome://inspect/#remote-debugging → tick + 'Allow remote debugging for this browser instance', then retry." +} -from __future__ import annotations +ensure_attached() { + ensure_tunnel + playwright-cli -s="$SESSION" eval '1' >/dev/null 2>&1 && return 0 + playwright-cli -s="$SESSION" attach --cdp="$WS" >/dev/null 2>&1 \ + || die "playwright-cli could not attach to ${WS} (is the box still ticked?)" +} -import argparse -import atexit -import base64 -import json -import os -import socket -import struct -import subprocess -import sys -import time -import urllib.parse +# tab_list → "INDEXTITLEURL" +tab_list() { + playwright-cli -s="$SESSION" tab-list 2>/dev/null \ + | sed -n 's/^- \([0-9]\+\): \(.*\)\[\(.*\)\](\(.*\))$/\1\t\3\t\4/p' +} -HOST = os.environ.get("DECK_HOST", "deck") -PORT = int(os.environ.get("DECK_CDP_PORT", "9222")) -LOCAL = "127.0.0.1" +resolve_tab() { # args: --index N | --match SUBSTR + local idx="" match="" + while [ $# -gt 0 ]; do + case "$1" in + --index) idx=${2:-}; shift 2 ;; + --match) match=${2:-}; shift 2 ;; + *) shift ;; + esac + done + if [ -n "$match" ]; then + idx=$(tab_list | awk -F'\t' -v m="$(echo "$match" | tr 'A-Z' 'a-z')" \ + 'tolower($0) ~ m {print $1; exit}') + [ -n "$idx" ] || die "no tab matching '$match'" + fi + printf '%s' "${idx:-}" +} - -# --- minimal WebSocket client ------------------------------------------------- - -class WS: - """Just enough of RFC 6455 to speak CDP: text frames, fragmentation, ping.""" - - def __init__(self, host: str, port: int, path: str, timeout: float = 10.0): - self.sock = socket.create_connection((host, port), timeout=timeout) - self.sock.settimeout(timeout) - key = base64.b64encode(os.urandom(16)).decode() - req = ( - f"GET {path} HTTP/1.1\r\nHost: {host}:{port}\r\nUpgrade: websocket\r\n" - f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n" - "Sec-WebSocket-Version: 13\r\n\r\n" - ) - self.sock.sendall(req.encode()) - resp = self._read_until(b"\r\n\r\n") - if b"101" not in resp.split(b"\r\n")[0]: - head = resp.split(b"\r\n")[0].decode(errors="replace") - raise RuntimeError(f"CDP handshake failed: {head}") - - def _read_until(self, marker: bytes) -> bytes: - buf = b"" - while marker not in buf: - chunk = self.sock.recv(4096) - if not chunk: - raise RuntimeError("connection closed during handshake") - buf += chunk - return buf - - def _recv_exact(self, n: int) -> bytes: - buf = b"" - while len(buf) < n: - chunk = self.sock.recv(n - len(buf)) - if not chunk: - raise RuntimeError("connection closed") - buf += chunk - return buf - - def send(self, text: str) -> None: - payload = text.encode() - header = bytearray([0x81]) # FIN + text - n = len(payload) - if n < 126: - header.append(0x80 | n) - elif n < (1 << 16): - header.append(0x80 | 126) - header += struct.pack(">H", n) - else: - header.append(0x80 | 127) - header += struct.pack(">Q", n) - mask = os.urandom(4) - header += mask - masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) - self.sock.sendall(bytes(header) + masked) - - def recv(self) -> str: - chunks = [] - while True: - b0, b1 = self._recv_exact(2) - opcode = b0 & 0x0F - fin = b0 & 0x80 - n = b1 & 0x7F - if n == 126: - n = struct.unpack(">H", self._recv_exact(2))[0] - elif n == 127: - n = struct.unpack(">Q", self._recv_exact(8))[0] - if b1 & 0x80: # server frames should not be masked - self._recv_exact(4) - payload = self._recv_exact(n) - if opcode == 0x9: # ping -> pong - self.sock.sendall(bytes([0x8A, 0x80]) + os.urandom(4)) - continue - if opcode == 0x8: # close - raise RuntimeError("server closed the CDP socket") - chunks.append(payload) - if fin: - return b"".join(chunks).decode(errors="replace") - - def close(self) -> None: +# json_unquote turns playwright's JSON-quoted eval result into plain text. +json_unquote() { + python3 -c ' +import json, sys +for line in sys.stdin.read().splitlines(): + line = line.strip() + if line[:1] == chr(34) and line[-1:] == chr(34): try: - self.sock.close() - except OSError: + sys.stdout.write(json.loads(line)); break + except Exception: pass +' +} +OPTS=() +for a in "$@"; do :; done +CMD=${1:-}; shift || true -# --- CDP helper --------------------------------------------------------------- - -class CDP: - def __init__(self, ws: WS): - self.ws = ws - self._id = 0 - - def call(self, method: str, params: dict | None = None, session: str | None = None): - self._id += 1 - msg = {"id": self._id, "method": method, "params": params or {}} - if session: - msg["sessionId"] = session - self.ws.send(json.dumps(msg)) - while True: - reply = json.loads(self.ws.recv()) - if reply.get("id") != self._id: - continue # event, not our reply - if "error" in reply: - raise RuntimeError(f"{method}: {reply['error'].get('message')}") - return reply.get("result", {}) - - def pages(self): - targets = self.call("Target.getTargets")["targetInfos"] - return [t for t in targets if t.get("type") == "page"] - - def attach(self, target_id: str) -> str: - return self.call("Target.attachToTarget", {"targetId": target_id, "flatten": True})["sessionId"] - - -# --- tunnel ------------------------------------------------------------------- - -_tunnel: subprocess.Popen | None = None - - -def _port_open() -> bool: - with socket.socket() as s: - s.settimeout(0.6) - return s.connect_ex((LOCAL, PORT)) == 0 - - -def ensure_tunnel() -> None: - global _tunnel - if _port_open(): - return - _tunnel = subprocess.Popen( - ["ssh", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes", - "-N", "-L", f"{PORT}:{LOCAL}:{PORT}", HOST], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - ) - atexit.register(lambda: _tunnel and _tunnel.terminate()) - for _ in range(25): - if _port_open(): - return - time.sleep(0.2) - sys.exit( - f"deck-browser: no CDP endpoint on {LOCAL}:{PORT}.\n" - " On the Deck, open chrome://inspect/#remote-debugging and tick\n" - " 'Allow remote debugging for this browser instance'.\n" - f" Then check: ssh {HOST} 'ss -ltn | grep {PORT}'" - ) - - -def connect() -> CDP: - ensure_tunnel() - return CDP(WS(LOCAL, PORT, "/devtools/browser")) - - -def pick(pages, index: int | None, match: str | None): - if match: - for p in pages: - hay = f"{p.get('url','')} {p.get('title','')}".lower() - if match.lower() in hay: - return p - sys.exit(f"deck-browser: no tab matching {match!r}") - if index is None: - index = 0 - if index >= len(pages): - sys.exit(f"deck-browser: index {index} out of range (have {len(pages)})") - return pages[index] - - -def main() -> int: - ap = argparse.ArgumentParser(prog="deck-browser", description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - sub = ap.add_subparsers(dest="cmd", required=True) - for name in ("tabs", "status"): - sub.add_parser(name) - for name in ("text", "html", "shot"): - p = sub.add_parser(name) - p.add_argument("--index", type=int, default=None, help="tab index from `tabs` (default 0)") - p.add_argument("--match", default=None, help="substring of the tab URL or title") - if name in ("text", "html"): - p.add_argument("--limit", type=int, default=8000, help="characters to print (default 8000)") - else: - p.add_argument("--out", default=None, help="output PNG (default /tmp/deck-shot-