cdp.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #!/usr/bin/env python3
  2. """Launch (or detect) the operator's local Chrome/Chromium over the DevTools Protocol (CDP).
  3. Phase-2 work -- sending opt-out/CCPA email through the operator's logged-in webmail, and driving
  4. session-bound multi-step opt-out gates (e.g. PeopleConnect guided-mode) -- must run in the
  5. operator's OWN browser: real fingerprint, residential IP, and the operator's signed-in sessions.
  6. A headless cloud browser (Browserbase) is the wrong tool there (it has no webmail session and is
  7. itself anti-bot-gated on those exact flows). This module launches the operator's real Chrome with
  8. remote debugging on a DEDICATED profile so Hermes's browser (`/browser connect`) can attach at 127.0.0.1:<port>.
  9. Stdlib only; cross-platform (macOS / Linux / Windows). Nothing here touches a password or PII.
  10. """
  11. from __future__ import annotations
  12. import json
  13. import os
  14. import shutil
  15. import subprocess
  16. import sys
  17. import urllib.error
  18. import urllib.request
  19. from pathlib import Path
  20. import paths
  21. DEFAULT_PORT = 9222
  22. # Chromium-family binaries we know how to drive, in preference order. Names first (works on any OS
  23. # where one is on PATH), then per-OS absolute-path fallbacks below.
  24. _PATH_NAMES = (
  25. "google-chrome", "google-chrome-stable", "chromium", "chromium-browser",
  26. "brave-browser", "microsoft-edge", "microsoft-edge-stable", "chrome",
  27. )
  28. def default_profile() -> Path:
  29. """Dedicated debug profile dir, NOT the operator's Default Chrome profile.
  30. Chrome refuses remote-debugging on a profile that is already open in another Chrome instance,
  31. so we isolate the debug session in its own user-data-dir under HERMES_HOME.
  32. """
  33. return paths.hermes_home() / "chrome-debug"
  34. def _mac_candidates() -> list[str]:
  35. return [
  36. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
  37. "/Applications/Chromium.app/Contents/MacOS/Chromium",
  38. "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
  39. "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
  40. "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
  41. ]
  42. def _windows_candidates() -> list[str]:
  43. bases = [
  44. os.environ.get("ProgramFiles", r"C:\Program Files"),
  45. os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"),
  46. os.environ.get("LOCALAPPDATA", ""),
  47. ]
  48. rels = [
  49. r"Google\Chrome\Application\chrome.exe",
  50. r"Chromium\Application\chrome.exe",
  51. r"BraveSoftware\Brave-Browser\Application\brave.exe",
  52. r"Microsoft\Edge\Application\msedge.exe",
  53. ]
  54. out: list[str] = []
  55. for base in bases:
  56. if not base:
  57. continue
  58. for rel in rels:
  59. out.append(str(Path(base) / rel))
  60. return out
  61. def find_browser(override: str | None = None) -> str | None:
  62. """Return the first usable Chromium-family browser path/command, or None.
  63. `override` (an explicit path, or a command on PATH) wins when it resolves.
  64. """
  65. if override:
  66. if Path(override).exists():
  67. return override
  68. return shutil.which(override) # may be None -> caller reports "not found"
  69. for name in _PATH_NAMES:
  70. found = shutil.which(name)
  71. if found:
  72. return found
  73. if sys.platform == "darwin":
  74. candidates = _mac_candidates()
  75. elif sys.platform == "win32":
  76. candidates = _windows_candidates()
  77. else:
  78. candidates = []
  79. for cand in candidates:
  80. if Path(cand).exists():
  81. return cand
  82. return None
  83. def launch_command(browser: str, port: int = DEFAULT_PORT, profile: Path | None = None) -> list[str]:
  84. """The exact argv used to start the debug browser (also handy for `--print`)."""
  85. profile = profile or default_profile()
  86. return [
  87. browser,
  88. f"--remote-debugging-port={int(port)}",
  89. f"--user-data-dir={profile}",
  90. "--no-first-run",
  91. "--no-default-browser-check",
  92. ]
  93. def _http_get(url: str, timeout: float) -> bytes:
  94. req = urllib.request.Request(url, headers={"User-Agent": "unbroker-cdp/1.0"})
  95. with urllib.request.urlopen(req, timeout=timeout) as resp:
  96. return resp.read()
  97. def endpoint_status(port: int = DEFAULT_PORT, host: str = "127.0.0.1",
  98. timeout: float = 1.0) -> dict | None:
  99. """Return the CDP `/json/version` dict if a debuggable browser is live at host:port, else None.
  100. (Chrome restricts this endpoint to localhost/IP Host headers, so we always hit 127.0.0.1.)
  101. """
  102. url = f"http://{host}:{int(port)}/json/version"
  103. try:
  104. raw = _http_get(url, timeout)
  105. except (urllib.error.URLError, TimeoutError, ConnectionError, OSError, ValueError):
  106. return None
  107. try:
  108. data = json.loads(raw.decode("utf-8", errors="replace"))
  109. except (ValueError, AttributeError):
  110. return None
  111. return data if isinstance(data, dict) else None
  112. def launch(browser: str, port: int = DEFAULT_PORT, profile: Path | None = None) -> int:
  113. """Start the browser detached with remote debugging; return the child PID.
  114. Detach so the browser outlives this short-lived CLI call. POSIX uses start_new_session (which
  115. avoids referencing os.setsid, so there is no Windows import-time footgun); Windows uses
  116. DETACHED_PROCESS + a new process group.
  117. """
  118. profile = profile or default_profile()
  119. profile.mkdir(parents=True, exist_ok=True)
  120. cmd = launch_command(browser, port, profile)
  121. kwargs: dict = {
  122. "stdin": subprocess.DEVNULL,
  123. "stdout": subprocess.DEVNULL,
  124. "stderr": subprocess.DEVNULL,
  125. }
  126. if sys.platform == "win32":
  127. kwargs["creationflags"] = (
  128. subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP # windows-footgun: ok
  129. )
  130. else:
  131. kwargs["start_new_session"] = True
  132. proc = subprocess.Popen(cmd, **kwargs)
  133. return proc.pid