| 1 | """First-run setup wizard for last30days. |
| 2 | |
| 3 | Detects first run, performs auto-setup (cookie extraction + yt-dlp check), |
| 4 | and writes configuration. The actual wizard UI is SKILL.md-driven (the LLM |
| 5 | presents it), but this module provides the detection and setup actions. |
| 6 | """ |
| 7 | |
| 8 | import json |
| 9 | import logging |
| 10 | import os |
| 11 | import re |
| 12 | import shutil |
| 13 | import stat |
| 14 | import subprocess |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import time |
| 18 | from pathlib import Path |
| 19 | from typing import Any, Callable, Dict, Optional, Tuple |
| 20 | from urllib.error import HTTPError, URLError |
| 21 | from urllib.parse import urlsplit |
| 22 | from urllib.request import ( |
| 23 | HTTPDefaultErrorHandler, |
| 24 | HTTPErrorProcessor, |
| 25 | HTTPHandler, |
| 26 | HTTPRedirectHandler, |
| 27 | HTTPSHandler, |
| 28 | OpenerDirector, |
| 29 | ProxyHandler, |
| 30 | Request, |
| 31 | UnknownHandler, |
| 32 | getproxies, |
| 33 | ) |
| 34 | |
| 35 | from . import brightdata, health, private_files, providers, rust_accel |
| 36 | from .private_files import replace_private_text, write_private_text |
| 37 | |
| 38 | logger = logging.getLogger(__name__) |
| 39 | |
| 40 | |
| 41 | def is_first_run(config: Dict[str, Any]) -> bool: |
| 42 | """Return True if the setup wizard has not been completed. |
| 43 | |
| 44 | Checks for SETUP_COMPLETE in the config dict. If it's not set |
| 45 | (None or empty string), the user hasn't gone through setup yet. |
| 46 | """ |
| 47 | return not config.get("SETUP_COMPLETE") |
| 48 | |
| 49 | |
| 50 | _WELCOME_TEXT = """Welcome to /last30days! I research any topic across Reddit, X, YouTube, TikTok, Digg, arXiv, Techmeme, HN, Polymarket & more - what people actually said in the last 30 days. Let's get you set up (~30s). |
| 51 | |
| 52 | I synthesize what people are actually saying right now across social, news, and market sources. |
| 53 | |
| 54 | Auto setup gives you the core sources free in about 30 seconds: |
| 55 | - Reddit with comments - free keyless discovery (Reddit search + shreddit), no API key needed. |
| 56 | - YouTube search + transcripts - installs yt-dlp (open source, 190K+ GitHub stars). |
| 57 | - Digg - trending news, GitHub stars, and pipeline feeds - installs the free, keyless Digg CLI. |
| 58 | - arXiv (papers) + Techmeme (tech-news) + News RSS (mainstream news & OPML feeds) - install free, keyless Printing Press CLIs and run on any topic (arXiv is relevance + recency gated to research topics). |
| 59 | - Yahoo Finance - the share-price move over your 30 days - installs the free, keyless Yahoo Finance CLI; shows only when your topic is a listed company or the person who leads one. |
| 60 | - StockTwits - retail trader sentiment - auto-on when your topic is a ticker or crypto (e.g. "$NVDA earnings", "bitcoin"), off for everything else. |
| 61 | - Trustpilot - brand/company review sentiment - opt-in (add trustpilot to INCLUDE_SOURCES), off by default. |
| 62 | - Hacker News + Polymarket + GitHub (auto-on if the gh CLI is installed) - always on, zero config. |
| 63 | - X/Twitter - optional. It stays available when you already configured it, or after you explicitly approve a browser-cookie read; skipping it never blocks research. |
| 64 | |
| 65 | Want TikTok and Instagram too? ScrapeCreators adds those (10,000 free calls, scrapecreators.com). No kickbacks, no affiliation. |
| 66 | |
| 67 | Power users can turn on more sources in the Manual Setup guide (LinkedIn, Bluesky, Perplexity, and others) - each needs its own credential, so they are off by default.""" |
| 68 | |
| 69 | |
| 70 | def render_welcome() -> str: |
| 71 | """Return the first-run welcome text. |
| 72 | |
| 73 | Owned by the engine (single source of truth) so the model relays it rather |
| 74 | than re-authoring it -- authored prose gets skipped, relayed command output |
| 75 | does not. Mirrors the SKILL.md welcome; keep in sync if the source set |
| 76 | changes. |
| 77 | """ |
| 78 | return _WELCOME_TEXT |
| 79 | |
| 80 | |
| 81 | # Neutral note recorded on an official-only host instead of a cookie scan. |
| 82 | # Deliberately names no cookie mechanism beyond the fact that none is used |
| 83 | # (the vocabulary rule for Grok Bot onboarding output). |
| 84 | OFFICIAL_HOST_COOKIE_NOTE = "browser sessions are not read on this host" |
| 85 | |
| 86 | |
| 87 | def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = False) -> Dict[str, Any]: |
| 88 | """Perform the auto-setup actions. |
| 89 | |
| 90 | - Optionally runs cookie extraction for all registered domains, trying the |
| 91 | browsers from ``env.cookie_extraction_browsers()``. Browser reads are off |
| 92 | unless ``allow_browser_cookies`` is true. |
| 93 | - Checks if yt-dlp is installed |
| 94 | - Best-effort install of digg-pp-cli (Printing Press library) |
| 95 | |
| 96 | Returns: |
| 97 | Dict with keys: |
| 98 | cookies_found: {source_name: browser_name} for each source where cookies were found |
| 99 | browser_cookie_scan_attempted: bool (True only after explicit consent |
| 100 | and at least one browser is eligible for extraction) |
| 101 | x_cookie_access_denied: browser names denied during an attempted X |
| 102 | cookie read when no other browser supplied a complete X pair |
| 103 | cookie_note: present only on an official-only host, where the scan |
| 104 | is skipped for every domain (neutral, relayable text) |
| 105 | ytdlp_installed: bool |
| 106 | ytdlp_action: already_installed | installed | install_failed | no_homebrew |
| 107 | digg_installed: bool (True when the engine can resolve digg-pp-cli on PATH) |
| 108 | digg_action: already_installed | installed | upgraded | installed_off_path | install_failed | no_npx |
| 109 | (install_failed / no_npx with digg_installed True: an older CLI on |
| 110 | PATH could not be upgraded and is still the one in use) |
| 111 | env_written: bool (always False here — caller writes config separately) |
| 112 | ytdlp_stderr: present when ytdlp_action is install_failed |
| 113 | digg_stderr: present when digg_action is install_failed |
| 114 | digg_path: present when digg_action is installed_off_path (binary on disk, not on PATH) |
| 115 | """ |
| 116 | from .env import COOKIE_DOMAINS, cookie_extraction_browsers, x_policy |
| 117 | |
| 118 | cookies_found: Dict[str, str] = {} |
| 119 | access_denied: dict[str, set[str]] = {} |
| 120 | cookie_note: Optional[str] = None |
| 121 | browsers: list[str] = [] |
| 122 | |
| 123 | # Official-only host (LAST30DAYS_HOST=grok-bot): the consented |
| 124 | # cookie scan is skipped for EVERY domain (X and Truth Social alike) and |
| 125 | # recorded as not attempted, with a neutral note the caller can relay. |
| 126 | # The free CLI installs below still run. A LAST30DAYS_X_BACKEND=bird pin |
| 127 | # is the one path that re-enables discovery, via x_policy. |
| 128 | if allow_browser_cookies and not x_policy(config).cookie_discovery: |
| 129 | allow_browser_cookies = False |
| 130 | cookie_note = OFFICIAL_HOST_COOKIE_NOTE |
| 131 | |
| 132 | if allow_browser_cookies: |
| 133 | from . import cookie_extract |
| 134 | |
| 135 | cookie_config = dict(config) |
| 136 | cookie_config["BROWSER_CONSENT"] = "true" |
| 137 | if not (cookie_config.get("FROM_BROWSER") or "").strip(): |
| 138 | # Chromium-first avoids Safari's usual Full Disk Access prompt. |
| 139 | # Browser-data permissions can still deny Chromium DB reads before |
| 140 | # the Keychain step, so a failed scan must report that separately. |
| 141 | # firefox/safari stay as the silent fallbacks. Note: an explicit |
| 142 | # comma list preserves this order (cookie_extraction_browsers); |
| 143 | # "auto" would put the silent browsers first, so do not use it here. |
| 144 | cookie_config["FROM_BROWSER"] = "chrome,brave,edge,vivaldi,opera,arc,dia,ardia,chromium,firefox,safari" |
| 145 | browsers = cookie_extraction_browsers(cookie_config) |
| 146 | |
| 147 | for source_name, spec in COOKIE_DOMAINS.items(): |
| 148 | if spec.get("consent_key"): |
| 149 | # The Reddit login has its own consent: setup --reddit-session. |
| 150 | continue |
| 151 | domain = spec["domain"] |
| 152 | cookie_names = spec["cookies"] |
| 153 | |
| 154 | for browser in browsers: |
| 155 | try: |
| 156 | result = cookie_extract.extract_cookies_with_source(browser, domain, cookie_names) |
| 157 | except PermissionError: |
| 158 | access_denied.setdefault(source_name, set()).add(browser) |
| 159 | continue |
| 160 | except Exception as exc: |
| 161 | logger.debug("Cookie extraction failed for %s via %s: %s", source_name, browser, exc) |
| 162 | continue |
| 163 | if result is not None and cookie_extract.has_complete_pair(result[0], cookie_names): |
| 164 | cookies_found[source_name] = result[1] |
| 165 | break # Complete pair found for this service, stop trying browsers |
| 166 | |
| 167 | # Check yt-dlp availability and install via Homebrew if missing. Windows |
| 168 | # has no Homebrew, and its working install path is `pip install yt-dlp` |
| 169 | # (see #904), so it gets its own no-op-install guidance branch instead of |
| 170 | # falling into the Homebrew-oriented no_homebrew outcome. |
| 171 | ytdlp_action: str |
| 172 | if shutil.which("yt-dlp") is not None: |
| 173 | ytdlp_installed = True |
| 174 | ytdlp_action = "already_installed" |
| 175 | elif os.name == "nt": |
| 176 | ytdlp_installed = False |
| 177 | ytdlp_action = "no_pip_windows" |
| 178 | elif shutil.which("brew") is not None: |
| 179 | brew_stderr = "" |
| 180 | try: |
| 181 | proc = subprocess.run( |
| 182 | ["brew", "install", "yt-dlp"], |
| 183 | capture_output=True, text=True, timeout=120, |
| 184 | ) |
| 185 | if proc.returncode == 0: |
| 186 | ytdlp_installed = True |
| 187 | ytdlp_action = "installed" |
| 188 | else: |
| 189 | ytdlp_installed = False |
| 190 | ytdlp_action = "install_failed" |
| 191 | brew_stderr = proc.stderr |
| 192 | logger.warning("brew install yt-dlp failed: %s", proc.stderr) |
| 193 | except Exception as exc: |
| 194 | ytdlp_installed = False |
| 195 | ytdlp_action = "install_failed" |
| 196 | brew_stderr = str(exc) |
| 197 | logger.warning("brew install yt-dlp exception: %s", exc) |
| 198 | else: |
| 199 | ytdlp_installed = False |
| 200 | ytdlp_action = "no_homebrew" |
| 201 | |
| 202 | digg_installed, digg_action, digg_stderr, digg_path = _install_digg_cli() |
| 203 | pp_sources = install_default_pp_sources() |
| 204 | rust_core = rust_accel.install_release_binary() |
| 205 | |
| 206 | scan_attempted = allow_browser_cookies and bool(browsers) |
| 207 | results: Dict[str, Any] = { |
| 208 | "cookies_found": cookies_found, |
| 209 | "x_cookie_access_denied": ( |
| 210 | [browser for browser in browsers if browser in access_denied.get("x", set())] |
| 211 | if scan_attempted and "x" not in cookies_found else [] |
| 212 | ), |
| 213 | "browser_cookie_scan_attempted": scan_attempted, |
| 214 | "firefox_scanned": scan_attempted and "firefox" in browsers, |
| 215 | "ytdlp_installed": ytdlp_installed, |
| 216 | "ytdlp_action": ytdlp_action, |
| 217 | "digg_installed": digg_installed, |
| 218 | "digg_action": digg_action, |
| 219 | # Per-CLI status for the additional default-on Printing Press sources |
| 220 | # (arxiv, techmeme, yahoo_finance): {source: {installed, action, ...}}. |
| 221 | "pp_sources": pp_sources, |
| 222 | "rust_core": rust_core, |
| 223 | # Reported, never installed: this CLI spends the user's own metered |
| 224 | # credits, so acquiring it stays their decision. Passing |
| 225 | # config matters: a user whose key lives in a .env file or the |
| 226 | # keychain (rather than a `brightdata login` credentials file) is |
| 227 | # active in the engine, and setup must not tell them otherwise. |
| 228 | "brightdata": brightdata_status(config), |
| 229 | "env_written": False, |
| 230 | } |
| 231 | if cookie_note: |
| 232 | results["cookie_note"] = cookie_note |
| 233 | if ytdlp_action == "install_failed": |
| 234 | results["ytdlp_stderr"] = brew_stderr |
| 235 | if digg_action == "install_failed": |
| 236 | results["digg_stderr"] = digg_stderr |
| 237 | if digg_path: |
| 238 | results["digg_path"] = digg_path |
| 239 | return results |
| 240 | |
| 241 | |
| 242 | # Generous timeout: the install shells out to `npx`, which may download the |
| 243 | # Printing Press package and build the Go binary over the network. |
| 244 | DIGG_INSTALL_TIMEOUT = 300 |
| 245 | DIGG_CLI_BIN = "digg-pp-cli" |
| 246 | # The pinned catalog installer lives in health so setup and doctor share it. |
| 247 | PRINTING_PRESS_NPM = health.PRINTING_PRESS_NPM |
| 248 | DIGG_INSTALL_CMD = health.helper_upgrade_cmd("digg") |
| 249 | |
| 250 | |
| 251 | def _digg_on_path() -> Optional[str]: |
| 252 | """Return digg-pp-cli when the engine would activate Digg (PATH-resolvable).""" |
| 253 | return shutil.which(DIGG_CLI_BIN) |
| 254 | |
| 255 | |
| 256 | def _digg_off_path_binary() -> Optional[str]: |
| 257 | return _pp_off_path_binary(DIGG_CLI_BIN) |
| 258 | |
| 259 | |
| 260 | def _digg_bin_dir_hint(digg_path: str) -> str: |
| 261 | """Return a copy-pasteable PATH directory for the given binary path.""" |
| 262 | parent = os.path.dirname(os.path.expanduser(digg_path)) |
| 263 | if os.name == "nt": |
| 264 | # Windows PATH edits use absolute dirs; $HOME is a Unix shell convention. |
| 265 | return parent |
| 266 | home = str(Path.home()) |
| 267 | if parent == home: |
| 268 | return "$HOME" |
| 269 | prefix = home + os.sep |
| 270 | if parent.startswith(prefix): |
| 271 | rel = parent[len(prefix):].replace(os.sep, "/") |
| 272 | return f"$HOME/{rel}" if rel else "$HOME" |
| 273 | return parent |
| 274 | |
| 275 | |
| 276 | def _run_npx_install(slug: str) -> Tuple[str, str]: |
| 277 | """Resolve ``npx`` and run the Printing Press catalog install for ``slug``. |
| 278 | |
| 279 | Shared by ``_install_digg_cli`` and ``_install_pp_cli`` -- this is only the |
| 280 | "resolve npx, run the install, interpret no_npx/exception/nonzero-rc" |
| 281 | slice. Each caller verifies the resulting binary. |
| 282 | |
| 283 | Fixes the Windows PATHEXT mismatch: ``shutil.which("npx")`` resolves |
| 284 | ``npx.CMD`` via PATHEXT, but ``subprocess.run`` given the bare string |
| 285 | ``"npx"`` as argv[0] does not do that resolution and fails with |
| 286 | ``WinError 2``. Passing the resolved path is a no-op on macOS/Linux, where |
| 287 | ``shutil.which`` already returns the exact path ``CreateProcess``/``execve`` |
| 288 | would resolve. |
| 289 | |
| 290 | Returns ``(action, stderr)``: ``action`` is ``"no_npx"``, |
| 291 | ``"install_failed"``, or ``""`` when the subprocess ran and returned |
| 292 | ``rc=0`` (in which case ``stderr`` carries any non-fatal stderr output for |
| 293 | the caller's own off-path logging). |
| 294 | """ |
| 295 | npx = shutil.which("npx") |
| 296 | if npx is None: |
| 297 | return "no_npx", "" |
| 298 | print( |
| 299 | f"Installing {slug} CLI via npx ({PRINTING_PRESS_NPM} --cli-only) ...", |
| 300 | file=sys.stderr, |
| 301 | flush=True, |
| 302 | ) |
| 303 | try: |
| 304 | proc = subprocess.run( |
| 305 | [npx, "-y", PRINTING_PRESS_NPM, "install", slug, "--cli-only"], |
| 306 | capture_output=True, text=True, timeout=DIGG_INSTALL_TIMEOUT, |
| 307 | ) |
| 308 | except Exception as exc: |
| 309 | logger.warning("npx install %s exception: %s", slug, exc) |
| 310 | return "install_failed", str(exc) |
| 311 | if proc.returncode != 0: |
| 312 | stderr = proc.stderr or f"npx install {slug} exited {proc.returncode}" |
| 313 | logger.warning("npx install %s failed (rc=%s): %s", slug, proc.returncode, stderr) |
| 314 | return "install_failed", stderr |
| 315 | # On a fresh Windows setup the managed Printing Press bin dir only exists |
| 316 | # now, so the engine's startup PATH append skipped it. Add it before the |
| 317 | # caller's shutil.which check, or setup asks for a PATH edit the next |
| 318 | # engine run would not need. |
| 319 | health.add_managed_bin_dir_to_path() |
| 320 | return "", (proc.stderr or "") |
| 321 | |
| 322 | |
| 323 | def _install_failed_line(name: str, install_cmd: str, stderr: str) -> str: |
| 324 | """Summary line for a failed Printing Press install. |
| 325 | |
| 326 | The installer names a missing prerequisite (Go) on stderr; re-running the |
| 327 | same command fails the same way, so lead with that cause (#1434). |
| 328 | """ |
| 329 | prereq = next( |
| 330 | (line.strip() for line in stderr.splitlines() if "Go is required" in line), |
| 331 | "", |
| 332 | ) |
| 333 | if prereq: |
| 334 | return f" - {name} CLI install failed: {prereq} Then run `{install_cmd}`" |
| 335 | return f" - {name} CLI install failed — run `{install_cmd}` manually" |
| 336 | |
| 337 | |
| 338 | def _upgrade_helper(slug: str, bin_name: str) -> Tuple[bool, str, str, str]: |
| 339 | """Re-run the catalog install over a helper on PATH that is too old. |
| 340 | |
| 341 | The older binary stays on PATH whatever happens, so ``engine_active`` |
| 342 | stays True on failure. Returns ``(engine_active, action, stderr, "")`` |
| 343 | with ``action`` one of: upgraded | install_failed | no_npx. ``upgraded`` |
| 344 | is claimed only when the helper PATH resolves afterwards reads at or above |
| 345 | its minimum; an older copy earlier on PATH would otherwise still answer. |
| 346 | """ |
| 347 | action, stderr = _run_npx_install(slug) |
| 348 | if action: |
| 349 | return True, action, stderr, "" |
| 350 | resolved = shutil.which(bin_name) |
| 351 | if resolved is None: |
| 352 | stderr_msg = stderr or f"upgrade completed but {bin_name} was not found" |
| 353 | logger.warning("npx upgrade %s failed verification: %s", slug, stderr_msg) |
| 354 | return False, "install_failed", stderr_msg, "" |
| 355 | outdated = health.helper_outdated(bin_name, resolved) |
| 356 | if outdated is not False: |
| 357 | stderr_msg = ( |
| 358 | f"upgrade completed but {resolved} is still older than the engine " |
| 359 | "needs; an older copy may sit earlier on PATH" |
| 360 | if outdated |
| 361 | else f"upgrade completed but the version of {resolved} could not be read" |
| 362 | ) |
| 363 | logger.warning("npx upgrade %s: %s", slug, stderr_msg) |
| 364 | return True, "install_failed", stderr_msg, "" |
| 365 | return True, "upgraded", "", "" |
| 366 | |
| 367 | |
| 368 | def _install_digg_cli() -> Tuple[bool, str, str, str]: |
| 369 | """Best-effort install of the digg-pp-cli binary. |
| 370 | |
| 371 | Mirrors the yt-dlp/brew auto-install: it never raises, and degrades to a |
| 372 | recommend-only outcome when the installer is unavailable. Uses |
| 373 | ``@mvanhorn/printing-press-library`` (``--cli-only``) — the same catalog |
| 374 | installer as pp-digg; Hermes/OpenClaw skill wiring is irrelevant here. |
| 375 | |
| 376 | Returns ``(engine_active, action, stderr, off_path_binary)`` where |
| 377 | ``engine_active`` is True only when ``shutil.which`` resolves the binary |
| 378 | (matching ``pipeline.available_sources()``). ``action`` is one of: |
| 379 | already_installed | installed | upgraded | installed_off_path | |
| 380 | install_failed | no_npx |
| 381 | ``upgraded`` means a binary on PATH older than |
| 382 | ``health.MIN_HELPER_VERSIONS`` allows was replaced; when that upgrade |
| 383 | fails (``install_failed``/``no_npx``) the older binary is still on PATH, |
| 384 | so ``engine_active`` stays True. ``stderr`` is populated on |
| 385 | ``install_failed``. ``off_path_binary`` is set when the binary exists on |
| 386 | disk but is not PATH-visible to this process. |
| 387 | """ |
| 388 | on_path = _digg_on_path() |
| 389 | if on_path: |
| 390 | if health.helper_outdated(DIGG_CLI_BIN, on_path): |
| 391 | return _upgrade_helper("digg", DIGG_CLI_BIN) |
| 392 | return True, "already_installed", "", "" |
| 393 | off_path = _digg_off_path_binary() |
| 394 | if off_path: |
| 395 | return False, "installed_off_path", "", off_path |
| 396 | action, stderr = _run_npx_install("digg") |
| 397 | if action: |
| 398 | return False, action, stderr, "" |
| 399 | on_path = _digg_on_path() |
| 400 | if on_path: |
| 401 | return True, "installed", "", "" |
| 402 | off_path = _digg_off_path_binary() |
| 403 | if off_path: |
| 404 | combined = stderr.strip() |
| 405 | if combined: |
| 406 | logger.warning("digg-pp-cli installed off PATH: %s", combined) |
| 407 | return False, "installed_off_path", combined, off_path |
| 408 | stderr_msg = stderr or "install completed but digg-pp-cli was not found" |
| 409 | logger.warning("npx install digg failed verification: %s", stderr_msg) |
| 410 | return False, "install_failed", stderr_msg, "" |
| 411 | |
| 412 | |
| 413 | # Additional default-on Printing Press sources installed the same way as Digg: |
| 414 | # (engine source key, slug for `install <slug>`, binary name). These activate in |
| 415 | # ``pipeline.available_sources()`` when ``shutil.which`` resolves the binary. |
| 416 | # Trustpilot is intentionally NOT here: it is opt-in (INCLUDE_SOURCES=trustpilot) |
| 417 | # because of its headless-Chrome cookie harvest, so auto-installing its binary |
| 418 | # for a source that stays off by default would be wasted work. Opting in installs |
| 419 | # it on demand via `npx ... install trustpilot --cli-only` (see CONFIGURATION.md). |
| 420 | PP_DEFAULT_SOURCES: list[tuple[str, str, str]] = [ |
| 421 | ("arxiv", "arxiv", "arxiv-pp-cli"), |
| 422 | ("techmeme", "techmeme", "techmeme-pp-cli"), |
| 423 | ("news_rss", "news-rss", "news-rss-pp-cli"), |
| 424 | # Not a search source: it adds the share-price line when a topic resolves |
| 425 | # to a listed company (lib/yahoo_finance.py gates on the same binary). |
| 426 | ("yahoo_finance", "yahoo-finance", "yahoo-finance-pp-cli"), |
| 427 | ] |
| 428 | |
| 429 | # Bright Data is deliberately absent from PP_DEFAULT_SOURCES: it is not a |
| 430 | # Printing Press CLI, it is opt-in like Trustpilot, and it spends the user's |
| 431 | # own metered credits. Setup reports its state and never installs it. |
| 432 | BRIGHTDATA_BIN = "brightdata" |
| 433 | |
| 434 | |
| 435 | def _brightdata_off_path_binary() -> Optional[str]: |
| 436 | """Locate a brightdata binary that exists on disk but not on PATH. |
| 437 | |
| 438 | Covers the common npm global prefixes. The distinction matters because |
| 439 | Hermes and OpenClaw gateways routinely run the engine with a PATH that |
| 440 | excludes the user's npm bin directory, so "installed" and "the engine |
| 441 | can see it" are different questions. |
| 442 | """ |
| 443 | launcher = health.windows_npm_launcher(BRIGHTDATA_BIN) |
| 444 | if launcher is not None: |
| 445 | return str(launcher) |
| 446 | home = Path.home() |
| 447 | candidates = [ |
| 448 | home / ".local" / "bin" / BRIGHTDATA_BIN, |
| 449 | home / ".npm-global" / "bin" / BRIGHTDATA_BIN, |
| 450 | Path("/opt/homebrew/bin") / BRIGHTDATA_BIN, |
| 451 | Path("/usr/local/bin") / BRIGHTDATA_BIN, |
| 452 | ] |
| 453 | npm_prefix = os.environ.get("NPM_CONFIG_PREFIX") |
| 454 | if npm_prefix: |
| 455 | candidates.insert(0, Path(npm_prefix) / "bin" / BRIGHTDATA_BIN) |
| 456 | for candidate in candidates: |
| 457 | try: |
| 458 | if candidate.is_file() and os.access(candidate, os.X_OK): |
| 459 | return str(candidate) |
| 460 | except OSError: |
| 461 | continue |
| 462 | return None |
| 463 | |
| 464 | |
| 465 | def brightdata_status(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: |
| 466 | """Report the Bright Data install and auth state honestly. |
| 467 | |
| 468 | Deliberately never claims the source is active unless the engine's own |
| 469 | gate would pass -- ``brightdata.is_available`` is the single predicate, |
| 470 | so setup and the engine cannot drift apart. Three states matter: |
| 471 | |
| 472 | * ``already_installed`` -- on PATH; ``authenticated`` says whether the |
| 473 | amazon lane will actually run. |
| 474 | * ``installed_off_path`` -- on disk but invisible to the engine, which |
| 475 | is the Hermes/OpenClaw failure mode. Carries the path so the user can |
| 476 | fix their PATH. |
| 477 | * ``not_installed`` -- nothing found. No auto-install: this CLI |
| 478 | spends the user's metered credits, so acquiring it is their call. |
| 479 | """ |
| 480 | installed = brightdata.is_installed() |
| 481 | authenticated = brightdata.has_credentials(config) |
| 482 | if installed: |
| 483 | action = "already_installed" |
| 484 | off_path = "" |
| 485 | else: |
| 486 | off_path = _brightdata_off_path_binary() or "" |
| 487 | action = "installed_off_path" if off_path else "not_installed" |
| 488 | |
| 489 | status: Dict[str, Any] = { |
| 490 | "installed": installed, |
| 491 | "action": action, |
| 492 | "authenticated": installed and authenticated, |
| 493 | # The engine gate, verbatim. Never report active on anything else. |
| 494 | "engine_active": brightdata.is_available(config), |
| 495 | } |
| 496 | if off_path: |
| 497 | status["path"] = off_path |
| 498 | status["hint"] = ( |
| 499 | f"brightdata found at {off_path} but not on PATH; add its directory " |
| 500 | "to PATH so the engine subprocess can see it" |
| 501 | ) |
| 502 | elif installed and not authenticated: |
| 503 | status["hint"] = "run `brightdata login` to activate the amazon source" |
| 504 | elif not installed: |
| 505 | status["hint"] = ( |
| 506 | "install with `npm i -g @brightdata/cli` then `brightdata login` " |
| 507 | "to enable the amazon source" |
| 508 | ) |
| 509 | return status |
| 510 | |
| 511 | |
| 512 | def _pp_off_path_binary(bin_name: str) -> Optional[str]: |
| 513 | binary = health.find_installed_binary(bin_name, health.installer_bin_dirs()) |
| 514 | return str(binary) if binary is not None else None |
| 515 | |
| 516 | |
| 517 | def _install_pp_cli(slug: str, bin_name: str) -> Tuple[bool, str, str, str]: |
| 518 | """Best-effort install of a Printing Press CLI binary. |
| 519 | |
| 520 | Slug-parameterized mirror of ``_install_digg_cli``: never raises, degrades |
| 521 | to recommend-only when the installer is unavailable. Returns |
| 522 | ``(engine_active, action, stderr, off_path_binary)`` with the same action |
| 523 | taxonomy: already_installed | installed | upgraded | installed_off_path | |
| 524 | install_failed | no_npx. |
| 525 | """ |
| 526 | on_path = shutil.which(bin_name) |
| 527 | if on_path: |
| 528 | if health.helper_outdated(bin_name, on_path): |
| 529 | return _upgrade_helper(slug, bin_name) |
| 530 | return True, "already_installed", "", "" |
| 531 | off_path = _pp_off_path_binary(bin_name) |
| 532 | if off_path: |
| 533 | return False, "installed_off_path", "", off_path |
| 534 | action, stderr = _run_npx_install(slug) |
| 535 | if action: |
| 536 | return False, action, stderr, "" |
| 537 | on_path = shutil.which(bin_name) |
| 538 | if on_path: |
| 539 | return True, "installed", "", "" |
| 540 | off_path = _pp_off_path_binary(bin_name) |
| 541 | if off_path: |
| 542 | combined = stderr.strip() |
| 543 | if combined: |
| 544 | logger.warning("%s installed off PATH: %s", bin_name, combined) |
| 545 | return False, "installed_off_path", combined, off_path |
| 546 | stderr_msg = stderr or f"install completed but {bin_name} was not found" |
| 547 | logger.warning("npx install %s failed verification: %s", slug, stderr_msg) |
| 548 | return False, "install_failed", stderr_msg, "" |
| 549 | |
| 550 | |
| 551 | def install_default_pp_sources() -> Dict[str, Dict[str, Any]]: |
| 552 | """Best-effort install of every additional default-on Printing Press source. |
| 553 | |
| 554 | Returns ``{source_key: {installed, action, stderr?, path?}}`` so the wizard |
| 555 | can report per-CLI status alongside Digg without raising on any single |
| 556 | failure. |
| 557 | """ |
| 558 | out: Dict[str, Dict[str, Any]] = {} |
| 559 | for source_key, slug, bin_name in PP_DEFAULT_SOURCES: |
| 560 | installed, action, stderr, off_path = _install_pp_cli(slug, bin_name) |
| 561 | entry: Dict[str, Any] = {"installed": installed, "action": action} |
| 562 | if action == "install_failed" and stderr: |
| 563 | entry["stderr"] = stderr |
| 564 | if off_path: |
| 565 | entry["path"] = off_path |
| 566 | out[source_key] = entry |
| 567 | return out |
| 568 | |
| 569 | |
| 570 | def _open_secret_append(path: Path): |
| 571 | """Open ``path`` for appending as a 0o600 secret file with no readable window. |
| 572 | |
| 573 | Uses ``O_NOFOLLOW`` and parent verification on POSIX (and junction/symlink |
| 574 | checks on Windows), tightens the open file descriptor with ``os.fchmod``, |
| 575 | and closes the descriptor if post-open setup or ``os.fdopen`` raises. |
| 576 | """ |
| 577 | path = Path(path) |
| 578 | flags = os.O_CREAT | os.O_WRONLY | os.O_APPEND |
| 579 | if os.name == "posix": |
| 580 | path = private_files._resolve_parent_only(path) |
| 581 | flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) |
| 582 | else: |
| 583 | private_files._reject_symlink_or_nonregular(path) |
| 584 | fd = os.open(path, flags, 0o600) |
| 585 | try: |
| 586 | st = os.fstat(fd) |
| 587 | if not stat.S_ISREG(st.st_mode): |
| 588 | raise OSError(f"Expected a regular private file: {path}") |
| 589 | if os.name == "posix" and hasattr(os, "fchmod"): |
| 590 | os.fchmod(fd, 0o600) |
| 591 | return os.fdopen(fd, "a", encoding="utf-8") |
| 592 | except BaseException: |
| 593 | os.close(fd) |
| 594 | raise |
| 595 | |
| 596 | |
| 597 | def _env_line_key(stripped: str) -> str: |
| 598 | """Return the key a stripped ``KEY=value`` line sets, as the loader reads it.""" |
| 599 | from . import env as _env |
| 600 | |
| 601 | return _env.env_line_key(stripped.split("=", 1)[0]) |
| 602 | |
| 603 | |
| 604 | _ENV_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") |
| 605 | # All characters that Python's str.splitlines() splits on. |
| 606 | _ENV_LINE_BREAKS_RE = re.compile(r"[\r\n\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]") |
| 607 | # Line breaks plus NUL are disallowed in persisted secret values. |
| 608 | _ENV_DISALLOWED_KEY_CHARS_RE = re.compile(r"[\x00\r\n\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]") |
| 609 | |
| 610 | |
| 611 | def _replace_env_line(env_path: Path, content: str, key_name: str, value: str) -> bool: |
| 612 | """Rewrite every ``key_name=`` line of ``content`` with ``value`` as a 0o600 secret. |
| 613 | |
| 614 | The new file is written to an owner-only sibling temp path and atomically |
| 615 | moved over the original, so the secret never has a readable window and a |
| 616 | crash mid-write leaves the old file intact. |
| 617 | """ |
| 618 | if not isinstance(key_name, str) or not _ENV_KEY_RE.fullmatch(key_name): |
| 619 | return False |
| 620 | |
| 621 | def _is_key(stripped: str) -> bool: |
| 622 | return bool( |
| 623 | stripped and not stripped.startswith("#") and "=" in stripped |
| 624 | and _env_line_key(stripped) == key_name |
| 625 | ) |
| 626 | |
| 627 | stripped_lines = [line.strip() for line in content.splitlines()] |
| 628 | # Keep a hand-written ``export`` -- on any of the duplicates being |
| 629 | # collapsed -- so a shell that sources the file still exports the key. |
| 630 | exported = any( |
| 631 | _is_key(s) and s.split("=", 1)[0].strip() != key_name for s in stripped_lines |
| 632 | ) |
| 633 | new_line = f"{key_name}={_format_env_value(value)}" |
| 634 | if exported: |
| 635 | new_line = f"export {new_line}" |
| 636 | lines = [] |
| 637 | replaced = False |
| 638 | for line, stripped in zip(content.splitlines(), stripped_lines): |
| 639 | if _is_key(stripped): |
| 640 | if not replaced: |
| 641 | lines.append(new_line) |
| 642 | replaced = True |
| 643 | continue |
| 644 | lines.append(line) |
| 645 | if not replaced: |
| 646 | lines.append(new_line) |
| 647 | replace_private_text(env_path, "\n".join(lines) + "\n") |
| 648 | if os.name != "posix": |
| 649 | try: |
| 650 | os.chmod(env_path, 0o600) |
| 651 | except OSError: |
| 652 | pass |
| 653 | return True |
| 654 | |
| 655 | |
| 656 | def _format_env_value(value: str) -> str: |
| 657 | """Quote a value so it round-trips through env.load_env_file. |
| 658 | |
| 659 | env.load_env_file strips a single layer of matching surrounding quotes but |
| 660 | does NOT process backslash escapes, so we wrap (never escape): |
| 661 | - plain tokens (no whitespace, no leading quote or ``#``): returned unchanged; |
| 662 | - values with whitespace/leading quote/``#`` and no double-quote: double-quoted; |
| 663 | - values containing a double-quote but no single-quote: single-quoted; |
| 664 | - values containing both quote types: returned as-is (best effort; no |
| 665 | wrapper round-trips through the loader, and tokens never hit this). |
| 666 | All characters split by ``str.splitlines()`` and NUL are removed/collapsed |
| 667 | so a single value can never inject a second ``KEY=value`` line. |
| 668 | """ |
| 669 | value = value.replace("\r", "").replace("\x00", "") |
| 670 | value = _ENV_LINE_BREAKS_RE.sub(" ", value) |
| 671 | needs_quoting = ( |
| 672 | (not value) |
| 673 | or value[0] in ("'", '"', "#") |
| 674 | or any(c.isspace() for c in value) |
| 675 | ) |
| 676 | if not needs_quoting: |
| 677 | return value |
| 678 | if '"' not in value: |
| 679 | return f'"{value}"' |
| 680 | if "'" not in value: |
| 681 | return f"'{value}'" |
| 682 | return value |
| 683 | |
| 684 | |
| 685 | def write_setup_config( |
| 686 | env_path: Optional[Path], |
| 687 | from_browser: str | None = None, |
| 688 | *, |
| 689 | browser_consent: bool | None = None, |
| 690 | x_cookie_access_denied: str | None = None, |
| 691 | ) -> bool: |
| 692 | """Write setup completion, browser selection, and consent to the .env file. |
| 693 | |
| 694 | Creates the file and parent directories if needed. |
| 695 | Appends without overwriting existing keys, except for an explicit consent |
| 696 | decision. |
| 697 | |
| 698 | Args: |
| 699 | env_path: Path to the .env file (e.g. ~/.config/last30days/.env) |
| 700 | from_browser: Browser or comma-separated browser list that actually |
| 701 | yielded cookies after consent (e.g. "chrome,firefox"). Pass None |
| 702 | (default) to leave FROM_BROWSER unchanged; when unset, future runs |
| 703 | do not read native browser stores. Avoid "auto", which would also probe |
| 704 | browsers that did not supply cookies during setup. |
| 705 | browser_consent: Record the user's current cookie-access decision. |
| 706 | None preserves any previous decision. |
| 707 | x_cookie_access_denied: Setup's non-secret last X denial observation. |
| 708 | Pass "none" to clear a prior denial after a new setup run. |
| 709 | |
| 710 | Returns: |
| 711 | True if config was written successfully, False on error. |
| 712 | """ |
| 713 | if not env_path or not isinstance(env_path, (str, os.PathLike)): |
| 714 | return False |
| 715 | try: |
| 716 | env_path = Path(env_path) |
| 717 | env_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 718 | private_files._reject_symlink_or_nonregular(env_path) |
| 719 | if browser_consent is not None: |
| 720 | if not write_api_key( |
| 721 | env_path, "true" if browser_consent else "false", |
| 722 | key_name="BROWSER_CONSENT", replace=True, |
| 723 | ): |
| 724 | return False |
| 725 | if x_cookie_access_denied is not None: |
| 726 | if not write_api_key( |
| 727 | env_path, x_cookie_access_denied, |
| 728 | key_name="LAST30DAYS_X_COOKIE_ACCESS_DENIED", replace=True, |
| 729 | ): |
| 730 | return False |
| 731 | |
| 732 | # Read existing content to avoid overwriting keys |
| 733 | existing_keys: set = set() |
| 734 | existing_content = "" |
| 735 | if env_path.exists(): |
| 736 | existing_content = env_path.read_text(encoding="utf-8-sig") |
| 737 | for line in existing_content.splitlines(): |
| 738 | stripped = line.strip() |
| 739 | if stripped and not stripped.startswith("#") and "=" in stripped: |
| 740 | key = _env_line_key(stripped) |
| 741 | existing_keys.add(key) |
| 742 | |
| 743 | lines_to_add = [] |
| 744 | if "SETUP_COMPLETE" not in existing_keys: |
| 745 | lines_to_add.append("SETUP_COMPLETE=true") |
| 746 | if from_browser and "FROM_BROWSER" not in existing_keys: |
| 747 | lines_to_add.append(f"FROM_BROWSER={_format_env_value(from_browser)}") |
| 748 | |
| 749 | if not lines_to_add: |
| 750 | return True # Nothing to write, already configured |
| 751 | |
| 752 | # Create/append as a 0o600 secret file: the .env holds tokens and keys, |
| 753 | # so it must never be created world-readable. |
| 754 | with _open_secret_append(env_path) as f: |
| 755 | if existing_content and not existing_content.endswith("\n"): |
| 756 | f.write("\n") |
| 757 | f.write("\n".join(lines_to_add) + "\n") |
| 758 | |
| 759 | return True |
| 760 | |
| 761 | except OSError as exc: |
| 762 | logger.error("Failed to write setup config to %s: %s", env_path, exc) |
| 763 | return False |
| 764 | |
| 765 | |
| 766 | def write_api_key( |
| 767 | env_path: Optional[Path], |
| 768 | api_key: str, |
| 769 | key_name: str = "SCRAPECREATORS_API_KEY", |
| 770 | *, |
| 771 | replace: bool = False, |
| 772 | ) -> bool: |
| 773 | """Append an API key to the .env file as a 0o600 secret. |
| 774 | |
| 775 | Reuses the same secret-safe write path as ``write_setup_config`` so the |
| 776 | value lands with restrictive permissions and round-trips through |
| 777 | ``env.load_env_file``. Idempotent by default: if ``key_name`` already has |
| 778 | a nonempty parsed value, nothing is written and the existing value is |
| 779 | preserved (we never clobber a key the user may have set by hand). With |
| 780 | ``replace=True`` an existing line is rewritten in place instead, so an |
| 781 | explicit ``setup --store-key`` can rotate a rejected credential. |
| 782 | Empty assignments are replaced so a signup key becomes usable. |
| 783 | |
| 784 | Args: |
| 785 | env_path: Path to the .env file (e.g. ~/.config/last30days/.env). |
| 786 | api_key: The raw key value to persist. |
| 787 | key_name: The env var name to write (default SCRAPECREATORS_API_KEY). |
| 788 | replace: Rewrite an existing ``key_name`` line instead of keeping it. |
| 789 | |
| 790 | Returns: |
| 791 | True if the key was written or already present, False on error or when |
| 792 | ``api_key`` is empty or malformed. |
| 793 | """ |
| 794 | if ( |
| 795 | not env_path |
| 796 | or not isinstance(env_path, (str, os.PathLike)) |
| 797 | or not api_key |
| 798 | or not isinstance(api_key, str) |
| 799 | or not isinstance(key_name, str) |
| 800 | or not _ENV_KEY_RE.fullmatch(key_name) |
| 801 | or _ENV_DISALLOWED_KEY_CHARS_RE.search(api_key) |
| 802 | ): |
| 803 | return False |
| 804 | try: |
| 805 | env_path = Path(env_path) |
| 806 | env_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 807 | private_files._reject_symlink_or_nonregular(env_path) |
| 808 | |
| 809 | existing_content = "" |
| 810 | if env_path.exists(): |
| 811 | existing_content = env_path.read_text(encoding="utf-8-sig") |
| 812 | for line in existing_content.splitlines(): |
| 813 | stripped = line.strip() |
| 814 | if stripped and not stripped.startswith("#") and "=" in stripped: |
| 815 | if _env_line_key(stripped) == key_name: |
| 816 | from .env import load_env_file |
| 817 | |
| 818 | if replace or not load_env_file(env_path).get(key_name): |
| 819 | return _replace_env_line(env_path, existing_content, key_name, api_key) |
| 820 | return True # Already configured; do not duplicate |
| 821 | |
| 822 | line = f"{key_name}={_format_env_value(api_key)}\n" |
| 823 | with _open_secret_append(env_path) as f: |
| 824 | if existing_content and not existing_content.endswith("\n"): |
| 825 | f.write("\n") |
| 826 | f.write(line) |
| 827 | |
| 828 | return True |
| 829 | |
| 830 | except OSError as exc: |
| 831 | logger.error("Failed to write API key to %s: %s", env_path, exc) |
| 832 | return False |
| 833 | |
| 834 | |
| 835 | def mask_api_key(api_key: str) -> str: |
| 836 | """Return a non-secret display form of an API key (prefix + last 4). |
| 837 | |
| 838 | Used so the key never appears verbatim in stdout the host model captures. |
| 839 | Short or empty keys collapse to a fixed placeholder. |
| 840 | """ |
| 841 | if not api_key or len(api_key) <= 8: |
| 842 | return "sc_…" |
| 843 | return f"{api_key[:3]}…{api_key[-4:]}" |
| 844 | |
| 845 | |
| 846 | def get_setup_status_text(results: Dict[str, Any]) -> str: |
| 847 | """Return a human-readable summary of auto-setup results. |
| 848 | |
| 849 | Args: |
| 850 | results: Dict from run_auto_setup() |
| 851 | |
| 852 | Returns: |
| 853 | Multi-line status text. |
| 854 | """ |
| 855 | from .env import X_COOKIE_ACCESS_FIX |
| 856 | |
| 857 | lines = [] |
| 858 | lines.append("Setup complete! Here's what I found:") |
| 859 | lines.append("") |
| 860 | |
| 861 | cookies_found = results.get("cookies_found", {}) |
| 862 | if results.get("browser_cookie_scan_attempted") and cookies_found: |
| 863 | for source, browser in cookies_found.items(): |
| 864 | lines.append(f" - {source.upper()} cookies found in {browser}") |
| 865 | denied_browsers = ( |
| 866 | results.get("x_cookie_access_denied") or [] |
| 867 | if results.get("browser_cookie_scan_attempted") else [] |
| 868 | ) |
| 869 | if denied_browsers: |
| 870 | lines.append( |
| 871 | " - X cookie access was permission denied in " |
| 872 | f"{', '.join(denied_browsers)}. {X_COOKIE_ACCESS_FIX}" |
| 873 | ) |
| 874 | |
| 875 | if (results.get("browser_cookie_scan_attempted") |
| 876 | and "x" not in cookies_found and not denied_browsers): |
| 877 | lines.append(" - No complete X login was found in the scanned browser profiles.") |
| 878 | if results.get("firefox_scanned"): |
| 879 | lines.append( |
| 880 | " Firefox permanent private browsing or clearing cookies on exit can " |
| 881 | "prevent saved cookies from being found." |
| 882 | ) |
| 883 | lines.append( |
| 884 | " Sign in with persistent browser cookies, or set AUTH_TOKEN and CT0 " |
| 885 | "manually in ~/.config/last30days/.env." |
| 886 | ) |
| 887 | |
| 888 | ytdlp_action = results.get("ytdlp_action", "") |
| 889 | if ytdlp_action == "installed": |
| 890 | lines.append(" - Installed yt-dlp via Homebrew") |
| 891 | elif ytdlp_action == "install_failed": |
| 892 | lines.append(" - yt-dlp install failed \u2014 run `brew install yt-dlp` manually") |
| 893 | elif ytdlp_action == "no_homebrew": |
| 894 | lines.append(" - yt-dlp not found. Install Homebrew first, then: brew install yt-dlp") |
| 895 | elif ytdlp_action == "no_pip_windows": |
| 896 | lines.append( |
| 897 | " - yt-dlp not found. Install with: pip install yt-dlp " |
| 898 | "(it may install to a Scripts directory not on PATH -- add it to PATH if YouTube search stays inactive)" |
| 899 | ) |
| 900 | elif ytdlp_action == "already_installed": |
| 901 | lines.append(" - yt-dlp already installed") |
| 902 | elif results.get("ytdlp_installed", False): |
| 903 | lines.append(" - yt-dlp is installed (YouTube search ready)") |
| 904 | else: |
| 905 | lines.append(" - yt-dlp not found (install with: brew install yt-dlp)") |
| 906 | |
| 907 | digg_action = results.get("digg_action", "") |
| 908 | if digg_action == "installed": |
| 909 | lines.append(" - Installed Digg CLI (free Digg story source now active)") |
| 910 | elif digg_action == "already_installed": |
| 911 | lines.append(" - Digg CLI already installed (Digg stories active)") |
| 912 | elif digg_action == "installed_off_path": |
| 913 | digg_path = results.get("digg_path", "") |
| 914 | if digg_path: |
| 915 | bin_dir = _digg_bin_dir_hint(digg_path) |
| 916 | lines.append( |
| 917 | f" - Digg CLI found at {digg_path} but not on PATH — add " |
| 918 | f"{bin_dir} to PATH and restart your agent session/gateway " |
| 919 | "for Digg to activate" |
| 920 | ) |
| 921 | else: |
| 922 | lines.append( |
| 923 | " - Digg CLI is installed but not on PATH — add its install " |
| 924 | "directory to PATH and restart your agent session/gateway for " |
| 925 | "Digg to activate" |
| 926 | ) |
| 927 | elif digg_action == "upgraded": |
| 928 | lines.append(" - Upgraded Digg CLI to a release the engine can call (Digg stories active)") |
| 929 | elif digg_action == "install_failed" and results.get("digg_installed"): |
| 930 | # The older CLI is still on PATH; its searches fail until upgraded. |
| 931 | lines.append( |
| 932 | " - Digg CLI upgrade failed; the older Digg CLI is still in use and " |
| 933 | f"its searches fail — run `{DIGG_INSTALL_CMD}` manually" |
| 934 | ) |
| 935 | elif digg_action == "install_failed": |
| 936 | lines.append(_install_failed_line("Digg", DIGG_INSTALL_CMD, results.get("digg_stderr", ""))) |
| 937 | elif digg_action == "no_npx" and results.get("digg_installed"): |
| 938 | lines.append( |
| 939 | " - Digg CLI is older than the engine can call. Install Node/npx, " |
| 940 | f"then upgrade it: {DIGG_INSTALL_CMD}" |
| 941 | ) |
| 942 | elif digg_action == "no_npx": |
| 943 | lines.append( |
| 944 | " - Digg CLI not installed (free, optional). Install Node/npx, then: " |
| 945 | f"{DIGG_INSTALL_CMD}" |
| 946 | ) |
| 947 | |
| 948 | pp_sources = results.get("pp_sources", {}) |
| 949 | pp_name: dict[str, str] = { |
| 950 | "arxiv": "arXiv", |
| 951 | "techmeme": "Techmeme", |
| 952 | "news_rss": "News RSS", |
| 953 | "yahoo_finance": "Yahoo Finance", |
| 954 | } |
| 955 | # The catalog install takes the slug, which is not always the source key |
| 956 | # (yahoo_finance installs as yahoo-finance). |
| 957 | pp_slug = {key: slug for key, slug, _bin in PP_DEFAULT_SOURCES} |
| 958 | for source_key, entry in sorted(pp_sources.items()): |
| 959 | name = pp_name.get(source_key, source_key.title()) |
| 960 | install_cmd = health.helper_upgrade_cmd(pp_slug.get(source_key, source_key)) |
| 961 | action = entry.get("action", "") |
| 962 | # install_failed / no_npx with the helper still on PATH: an older |
| 963 | # copy that could not be upgraded. |
| 964 | stale = bool(entry.get("installed")) |
| 965 | if action == "installed": |
| 966 | lines.append(f" - Installed {name} CLI ({name} source now active)") |
| 967 | elif action == "upgraded": |
| 968 | lines.append(f" - Upgraded {name} CLI to a release the engine can call ({name} active)") |
| 969 | elif action == "install_failed" and stale: |
| 970 | lines.append( |
| 971 | f" - {name} CLI upgrade failed; the older {name} CLI is still in " |
| 972 | f"use — run `{install_cmd}` manually" |
| 973 | ) |
| 974 | elif action == "no_npx" and stale: |
| 975 | lines.append( |
| 976 | f" - {name} CLI is older than the engine can call. Install " |
| 977 | f"Node/npx, then upgrade it: `{install_cmd}`" |
| 978 | ) |
| 979 | elif action == "already_installed": |
| 980 | lines.append(f" - {name} CLI already installed ({name} active)") |
| 981 | elif action == "installed_off_path": |
| 982 | path = entry.get("path", "") |
| 983 | if path: |
| 984 | lines.append( |
| 985 | f" - {name} CLI at {path} but not on PATH — add " |
| 986 | f"{os.path.dirname(os.path.expanduser(path))} to PATH and " |
| 987 | f"restart your agent session/gateway for {name} to activate" |
| 988 | ) |
| 989 | else: |
| 990 | lines.append( |
| 991 | f" - {name} CLI installed but not on PATH — add its install " |
| 992 | "directory to PATH and restart your agent session/gateway for " |
| 993 | f"{name} to activate" |
| 994 | ) |
| 995 | elif action == "install_failed": |
| 996 | lines.append(_install_failed_line(name, install_cmd, entry.get("stderr", ""))) |
| 997 | elif action == "no_npx": |
| 998 | lines.append( |
| 999 | f" - {name} CLI not installed (free, optional). Install Node/npx, " |
| 1000 | f"then: `{install_cmd}`" |
| 1001 | ) |
| 1002 | |
| 1003 | # Bright Data / Amazon. Reported but never installed (it spends the user's |
| 1004 | # own metered credits), so the only useful thing setup can do is say |
| 1005 | # precisely why the lane is or is not active -- the three states below are |
| 1006 | # otherwise invisible, since SKILL.md tells the model not to raise the |
| 1007 | # subject mid-run. |
| 1008 | brightdata_status_entry = results.get("brightdata") or {} |
| 1009 | bd_action = brightdata_status_entry.get("action", "") |
| 1010 | if brightdata_status_entry.get("engine_active"): |
| 1011 | lines.append(" - Bright Data CLI ready (Amazon buyer signals available)") |
| 1012 | elif bd_action == "already_installed": |
| 1013 | lines.append( |
| 1014 | " - Bright Data CLI installed but not logged in — run " |
| 1015 | "`brightdata login` to enable Amazon buyer signals (optional)" |
| 1016 | ) |
| 1017 | elif bd_action == "installed_off_path": |
| 1018 | bd_path = brightdata_status_entry.get("path", "") |
| 1019 | lines.append( |
| 1020 | f" - Bright Data CLI found at {bd_path} but not on PATH — add " |
| 1021 | f"{os.path.dirname(os.path.expanduser(bd_path))} to PATH and restart " |
| 1022 | "your agent session/gateway for Amazon buyer signals to activate" |
| 1023 | ) |
| 1024 | elif bd_action == "not_installed": |
| 1025 | lines.append( |
| 1026 | " - Amazon buyer signals not installed (optional; 5,000 free " |
| 1027 | "requests/month). Install with: npm i -g @brightdata/cli && brightdata login" |
| 1028 | ) |
| 1029 | |
| 1030 | rust_core = results.get("rust_core") or {} |
| 1031 | rc_action = rust_core.get("action", "") |
| 1032 | rc_version = rust_core.get("version") |
| 1033 | ver_suffix = f" (v{rc_version})" if rc_version else "" |
| 1034 | if rc_action == "installed": |
| 1035 | lines.append(f" - Installed native Rust core{ver_suffix} (default local compute active)") |
| 1036 | elif rc_action == "upgraded": |
| 1037 | lines.append(f" - Upgraded native Rust core{ver_suffix} (default local compute active)") |
| 1038 | elif rc_action == "already_installed": |
| 1039 | lines.append(f" - Native Rust core{ver_suffix} already installed") |
| 1040 | elif rc_action == "unsupported_platform": |
| 1041 | lines.append(" - Native Rust core has no prebuilt binary for this platform (using pure-Python fallback)") |
| 1042 | elif rc_action == "install_failed": |
| 1043 | detail = rust_core.get("detail") or "download failed" |
| 1044 | if rust_core.get("installed"): |
| 1045 | lines.append(f" - Native Rust core upgrade skipped ({detail}); keeping existing binary") |
| 1046 | else: |
| 1047 | lines.append(f" - Native Rust core install skipped ({detail}); using pure-Python fallback") |
| 1048 | |
| 1049 | cookie_note = results.get("cookie_note") |
| 1050 | if cookie_note: |
| 1051 | # Official-only host: relay the neutral note; say nothing about |
| 1052 | # browsers. The scan was not attempted, so nothing is "found". |
| 1053 | lines.append(f" - {cookie_note}") |
| 1054 | |
| 1055 | env_written = results.get("env_written", False) |
| 1056 | if env_written: |
| 1057 | lines.append("") |
| 1058 | if cookie_note: |
| 1059 | lines.append("Configuration saved.") |
| 1060 | elif denied_browsers: |
| 1061 | lines.append("Configuration saved. X browser cookie access remains unverified.") |
| 1062 | else: |
| 1063 | lines.append("Configuration saved. Future runs will auto-detect your browsers.") |
| 1064 | |
| 1065 | return "\n".join(lines) |
| 1066 | |
| 1067 | |
| 1068 | # --------------------------------------------------------------------------- |
| 1069 | # OpenClaw server-side setup (no browser, JSON output) |
| 1070 | # --------------------------------------------------------------------------- |
| 1071 | |
| 1072 | _OPENCLAW_KEY_NAMES = [ |
| 1073 | "SCRAPECREATORS_API_KEY", |
| 1074 | "XAI_API_KEY", |
| 1075 | "BRAVE_API_KEY", |
| 1076 | "EXA_API_KEY", |
| 1077 | "SERPER_API_KEY", |
| 1078 | "OPENAI_API_KEY", |
| 1079 | "AUTH_TOKEN", |
| 1080 | ] |
| 1081 | |
| 1082 | |
| 1083 | def run_openclaw_setup(config: Dict[str, Any]) -> Dict[str, Any]: |
| 1084 | """Server-side setup probe: no cookies, tool + key availability, Digg CLI. |
| 1085 | |
| 1086 | Best-effort installs digg-pp-cli when npx is available (same as desktop |
| 1087 | ``run_auto_setup``). Returns a dict suitable for JSON output to stdout so |
| 1088 | that SKILL.md can present appropriate options to the user. |
| 1089 | """ |
| 1090 | yt_dlp = shutil.which("yt-dlp") is not None |
| 1091 | node = shutil.which("node") is not None |
| 1092 | python3 = shutil.which("python3") is not None |
| 1093 | |
| 1094 | digg_installed, digg_action, digg_stderr, digg_path = _install_digg_cli() |
| 1095 | rust_core = rust_accel.install_release_binary() |
| 1096 | |
| 1097 | keys: Dict[str, bool] = {} |
| 1098 | for key_name in _OPENCLAW_KEY_NAMES: |
| 1099 | short = key_name.lower().replace("_api_key", "").replace("_key", "").replace("_token", "") |
| 1100 | # Normalize: AUTH_TOKEN -> auth, SCRAPECREATORS_API_KEY -> scrapecreators |
| 1101 | keys[short] = bool(config.get(key_name)) |
| 1102 | |
| 1103 | # Determine x_method |
| 1104 | if config.get("XAI_API_KEY"): |
| 1105 | x_method: Optional[str] = "xai" |
| 1106 | elif config.get("AUTH_TOKEN") and config.get("CT0"): |
| 1107 | x_method = "cookies" |
| 1108 | else: |
| 1109 | x_method = None |
| 1110 | |
| 1111 | payload: Dict[str, Any] = { |
| 1112 | "yt_dlp": yt_dlp, |
| 1113 | "node": node, |
| 1114 | "python3": python3, |
| 1115 | "digg_cli": digg_installed, |
| 1116 | "digg_action": digg_action, |
| 1117 | "rust_core": bool(rust_core.get("installed")), |
| 1118 | "rust_core_action": rust_core.get("action", ""), |
| 1119 | "keys": keys, |
| 1120 | "x_method": x_method, |
| 1121 | } |
| 1122 | if digg_path: |
| 1123 | payload["digg_path"] = digg_path |
| 1124 | if digg_action == "install_failed" and digg_stderr: |
| 1125 | payload["digg_stderr"] = digg_stderr |
| 1126 | return payload |
| 1127 | |
| 1128 | |
| 1129 | # --------------------------------------------------------------------------- |
| 1130 | # Device auth flow (GitHub OAuth via ScrapeCreators) |
| 1131 | # --------------------------------------------------------------------------- |
| 1132 | |
| 1133 | _DEVICE_BASE = "https://api.scrapecreators.com/v1/github/device" |
| 1134 | |
| 1135 | |
| 1136 | def _device_base() -> str: |
| 1137 | if _DEVICE_BASE != "https://api.scrapecreators.com/v1/github/device": |
| 1138 | return _DEVICE_BASE |
| 1139 | from . import env |
| 1140 | return f"{env.get_scrapecreators_base_url()}/v1/github/device" |
| 1141 | |
| 1142 | # A GitHub device code is always XXXX-XXXX (uppercase alphanumerics). We validate |
| 1143 | # user_code against this before copying, labeling, or emitting it so a malformed |
| 1144 | # or key-shaped value (e.g. a returning-account server response) is never |
| 1145 | # mislabeled as a device code or leaked to stdout/clipboard. |
| 1146 | _DEVICE_CODE_RE = re.compile(r"^[0-9A-Z]{4}-[0-9A-Z]{4}$") |
| 1147 | _AUTH_HEADER_RE = re.compile(r"\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+", re.IGNORECASE) |
| 1148 | _GITHUB_TOKEN_RE = re.compile( |
| 1149 | r"\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+)\b" |
| 1150 | ) |
| 1151 | _SECRET_FIELD_NAMES = frozenset( |
| 1152 | { |
| 1153 | "access_token", |
| 1154 | "refresh_token", |
| 1155 | "api_key", |
| 1156 | "apikey", |
| 1157 | "token", |
| 1158 | "secret", |
| 1159 | "authorization", |
| 1160 | "password", |
| 1161 | "cookie", |
| 1162 | } |
| 1163 | ) |
| 1164 | _SAFE_ERROR_SUMMARY_KEYS = ("error", "error_description", "message", "detail") |
| 1165 | _SECRET_FIELD_RE = re.compile( |
| 1166 | r"""(["']?(?:access_token|refresh_token|api_key|apikey|token|secret|authorization|password|cookie)["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,}&;]+)""", |
| 1167 | re.IGNORECASE, |
| 1168 | ) |
| 1169 | _UNCLOSED_SECRET_QUOTE_RE = re.compile( |
| 1170 | r"""["']?(?:access_token|refresh_token|api_key|apikey|token|secret|authorization|password|cookie)["']?\s*[:=]\s*(?:"(?:\\.|[^"\\])*\\?$|'(?:\\.|[^'\\])*\\?$)""", |
| 1171 | re.IGNORECASE, |
| 1172 | ) |
| 1173 | _URL_USERINFO_RE = re.compile(r"(https?://)[^\s/?#]+@", re.IGNORECASE) |
| 1174 | _MAX_DEVICE_RESPONSE_BYTES = 64 * 1024 |
| 1175 | |
| 1176 | |
| 1177 | class _DeviceNoRedirectHandler(HTTPRedirectHandler): |
| 1178 | def redirect_request(self, req, fp, code, msg, headers, newurl): |
| 1179 | if fp is not None: |
| 1180 | try: |
| 1181 | fp.close() |
| 1182 | except Exception: |
| 1183 | pass |
| 1184 | raise HTTPError( |
| 1185 | req.full_url, |
| 1186 | 403, |
| 1187 | "redirect refused for device auth endpoint", |
| 1188 | headers, |
| 1189 | None, |
| 1190 | ) |
| 1191 | |
| 1192 | |
| 1193 | def _build_device_opener(*, loopback_http: bool = False) -> OpenerDirector: |
| 1194 | """Build a no-redirect opener for device-auth endpoints. |
| 1195 | |
| 1196 | Omits FileHandler, FTPHandler, and DataHandler. Remote targets are HTTPS-only |
| 1197 | (honoring only the ``https`` proxy entry); loopback HTTP test targets bypass |
| 1198 | ambient proxies directly. |
| 1199 | """ |
| 1200 | opener = OpenerDirector() |
| 1201 | if loopback_http: |
| 1202 | handlers = [ |
| 1203 | ProxyHandler({}), |
| 1204 | UnknownHandler(), |
| 1205 | HTTPHandler(), |
| 1206 | HTTPDefaultErrorHandler(), |
| 1207 | _DeviceNoRedirectHandler(), |
| 1208 | HTTPErrorProcessor(), |
| 1209 | ] |
| 1210 | else: |
| 1211 | https_proxy = getproxies().get("https") |
| 1212 | proxies = {"https": https_proxy} if https_proxy else {} |
| 1213 | handlers = [ |
| 1214 | ProxyHandler(proxies), |
| 1215 | UnknownHandler(), |
| 1216 | HTTPSHandler(), |
| 1217 | HTTPDefaultErrorHandler(), |
| 1218 | _DeviceNoRedirectHandler(), |
| 1219 | HTTPErrorProcessor(), |
| 1220 | ] |
| 1221 | for handler in handlers: |
| 1222 | opener.add_handler(handler) |
| 1223 | return opener |
| 1224 | |
| 1225 | |
| 1226 | def _default_urlopen(req: Request, timeout: int = 15): |
| 1227 | url = getattr(req, "full_url", None) or str(req) |
| 1228 | if not isinstance(url, str) or not url or url != url.strip(): |
| 1229 | raise URLError("unsupported URL scheme: <empty>") |
| 1230 | if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in url): |
| 1231 | raise URLError("unsupported URL control characters") |
| 1232 | try: |
| 1233 | parts = urlsplit(url) |
| 1234 | except ValueError as exc: |
| 1235 | raise URLError(f"invalid URL: {exc}") from exc |
| 1236 | scheme = parts.scheme.lower() |
| 1237 | if scheme == "https" and parts.hostname: |
| 1238 | return _build_device_opener(loopback_http=False).open(req, timeout=timeout) |
| 1239 | if scheme == "http" and providers.is_loopback_http_endpoint(url): |
| 1240 | return _build_device_opener(loopback_http=True).open(req, timeout=timeout) |
| 1241 | raise URLError(f"unsupported URL scheme or non-loopback http: {scheme or '<empty>'}") |
| 1242 | |
| 1243 | |
| 1244 | # Sole test compatibility seam for patches targeting ``lib.setup_wizard.urlopen``; |
| 1245 | # production requests always use the dedicated no-redirect opener above and never |
| 1246 | # delegate to ``urllib.request.urlopen``. |
| 1247 | urlopen = _default_urlopen |
| 1248 | |
| 1249 | |
| 1250 | def _open_device_request(req: Request, *, timeout: int = 15): |
| 1251 | return urlopen(req, timeout=timeout) |
| 1252 | |
| 1253 | |
| 1254 | def _close_http_error(exc: HTTPError) -> None: |
| 1255 | close = getattr(exc, "close", None) |
| 1256 | if callable(close): |
| 1257 | try: |
| 1258 | close() |
| 1259 | except Exception: |
| 1260 | pass |
| 1261 | |
| 1262 | |
| 1263 | def _read_bounded_json_dict(resp: Any) -> Optional[Dict[str, Any]]: |
| 1264 | try: |
| 1265 | raw = resp.read(_MAX_DEVICE_RESPONSE_BYTES + 1) |
| 1266 | except TypeError: |
| 1267 | raw = resp.read() |
| 1268 | if not isinstance(raw, (bytes, bytearray)) or len(raw) > _MAX_DEVICE_RESPONSE_BYTES: |
| 1269 | return None |
| 1270 | try: |
| 1271 | parsed = json.loads(raw) |
| 1272 | except (json.JSONDecodeError, UnicodeDecodeError, RecursionError, ValueError, TypeError): |
| 1273 | return None |
| 1274 | return parsed if isinstance(parsed, dict) else None |
| 1275 | |
| 1276 | |
| 1277 | def _is_valid_verification_uri(uri: Any) -> bool: |
| 1278 | """Return True only for exact HTTPS ``github.com`` device-login verification URIs.""" |
| 1279 | if not isinstance(uri, str) or not uri: |
| 1280 | return False |
| 1281 | if "\\" in uri or any(ord(ch) <= 0x20 or ord(ch) >= 0x7F for ch in uri): |
| 1282 | return False |
| 1283 | try: |
| 1284 | parts = urlsplit(uri) |
| 1285 | port = parts.port |
| 1286 | except ValueError: |
| 1287 | return False |
| 1288 | if parts.scheme != "https": |
| 1289 | return False |
| 1290 | if parts.username is not None or parts.password is not None or "@" in parts.netloc: |
| 1291 | return False |
| 1292 | if port not in (None, 443): |
| 1293 | return False |
| 1294 | if (parts.hostname or "").lower() != "github.com": |
| 1295 | return False |
| 1296 | if parts.query or parts.fragment or "?" in uri or "#" in uri: |
| 1297 | return False |
| 1298 | path = parts.path |
| 1299 | if path != "/login/device" and not path.startswith("/login/device/"): |
| 1300 | return False |
| 1301 | lowered_path = path.lower() |
| 1302 | if ".." in path.split("/") or "%2e" in lowered_path or "%2f" in lowered_path or "%5c" in lowered_path: |
| 1303 | return False |
| 1304 | return True |
| 1305 | |
| 1306 | |
| 1307 | def _scrub_error_text(text: str, *, secrets: Tuple[str, ...] = ()) -> str: |
| 1308 | """Redact known secrets, bearer tokens, and URL credentials from error text.""" |
| 1309 | scrubbed = text |
| 1310 | for secret in secrets: |
| 1311 | if not isinstance(secret, str): |
| 1312 | continue |
| 1313 | for candidate in {secret, secret.strip()}: |
| 1314 | if candidate and candidate.strip(): |
| 1315 | scrubbed = scrubbed.replace(candidate, "[REDACTED]") |
| 1316 | scrubbed = _URL_USERINFO_RE.sub(r"\1", scrubbed) |
| 1317 | scrubbed = _AUTH_HEADER_RE.sub(r"\1 [REDACTED]", scrubbed) |
| 1318 | scrubbed = _GITHUB_TOKEN_RE.sub("[REDACTED]", scrubbed) |
| 1319 | scrubbed = _SECRET_FIELD_RE.sub(r'\1"[REDACTED]"', scrubbed) |
| 1320 | return scrubbed |
| 1321 | |
| 1322 | |
| 1323 | def _existing_scrapecreators_key() -> Optional[str]: |
| 1324 | """Return the SCRAPECREATORS_API_KEY already saved in the .env, if any.""" |
| 1325 | try: |
| 1326 | from . import env as _env |
| 1327 | |
| 1328 | if _env.CONFIG_FILE and _env.CONFIG_FILE.exists(): |
| 1329 | return _env.load_env_file(_env.CONFIG_FILE).get("SCRAPECREATORS_API_KEY") or None |
| 1330 | except Exception as exc: # never let a config-read failure block auth |
| 1331 | logger.debug("Could not read existing ScrapeCreators key: %s", exc) |
| 1332 | return None |
| 1333 | |
| 1334 | |
| 1335 | def _clamp_device_interval(interval: Any) -> int: |
| 1336 | """Clamp a server-provided device-flow poll interval to [1, 30] seconds. |
| 1337 | |
| 1338 | The ``interval`` comes from the server (device/code response or the |
| 1339 | persisted poll handle), so 0 would hot-loop ``time.sleep``, a negative |
| 1340 | would crash it, a huge value would sail past the poll timeout, and a |
| 1341 | non-numeric value would raise. Defaults to 5 on missing/garbled input. |
| 1342 | """ |
| 1343 | try: |
| 1344 | value = int(interval or 5) |
| 1345 | except (TypeError, ValueError): |
| 1346 | return 5 |
| 1347 | return min(max(value, 1), 30) |
| 1348 | |
| 1349 | |
| 1350 | def run_device_auth() -> Optional[Tuple[str, str, str, int]]: |
| 1351 | """Start the device authorization flow. |
| 1352 | |
| 1353 | POSTs to the ScrapeCreators device/code endpoint. |
| 1354 | |
| 1355 | Returns: |
| 1356 | (device_code, user_code, verification_uri, interval) on success, |
| 1357 | None on failure. |
| 1358 | """ |
| 1359 | try: |
| 1360 | body = json.dumps({}).encode() |
| 1361 | req = Request(f"{_device_base()}/code", data=body, method="POST") |
| 1362 | req.add_header("Content-Type", "application/json") |
| 1363 | with _open_device_request(req, timeout=15) as resp: |
| 1364 | data = _read_bounded_json_dict(resp) |
| 1365 | except HTTPError as exc: |
| 1366 | try: |
| 1367 | logger.warning("Device auth code request failed: %s", _scrub_error_text(str(exc))) |
| 1368 | finally: |
| 1369 | _close_http_error(exc) |
| 1370 | return None |
| 1371 | except (URLError, OSError) as exc: |
| 1372 | logger.warning("Device auth code request failed: %s", _scrub_error_text(str(exc))) |
| 1373 | return None |
| 1374 | |
| 1375 | if data is None: |
| 1376 | logger.warning("Device auth code request returned invalid or oversized JSON.") |
| 1377 | return None |
| 1378 | |
| 1379 | device_code = data.get("device_code") |
| 1380 | user_code = data.get("user_code") |
| 1381 | verification_uri = data.get("verification_uri") |
| 1382 | interval = _clamp_device_interval(data.get("interval", 5)) |
| 1383 | |
| 1384 | if not device_code or not user_code: |
| 1385 | # Log only the response's key names, never its values — a returning |
| 1386 | # account's response could carry a raw API key we must not write to logs. |
| 1387 | logger.warning( |
| 1388 | "Device auth returned incomplete response (keys: %s)", sorted(data.keys()) |
| 1389 | ) |
| 1390 | return None |
| 1391 | |
| 1392 | if verification_uri is None: |
| 1393 | verification_uri = "" |
| 1394 | elif verification_uri != "" and not _is_valid_verification_uri(verification_uri): |
| 1395 | logger.warning("Device auth returned an untrusted verification_uri; aborting.") |
| 1396 | return None |
| 1397 | |
| 1398 | return (device_code, user_code, verification_uri, interval) |
| 1399 | |
| 1400 | |
| 1401 | def poll_device_auth( |
| 1402 | device_code: str, |
| 1403 | interval: int, |
| 1404 | timeout: int = 300, |
| 1405 | user_code: str = "", |
| 1406 | clipboard_ok: bool = False, |
| 1407 | ) -> Optional[str]: |
| 1408 | """Poll for an access token after the user authorizes the device. |
| 1409 | |
| 1410 | Args: |
| 1411 | device_code: The device_code from run_device_auth(). |
| 1412 | interval: Polling interval in seconds. |
| 1413 | timeout: Maximum time to poll in seconds. |
| 1414 | user_code: The user code to remind about during polling. |
| 1415 | clipboard_ok: Whether the code was copied to clipboard. |
| 1416 | |
| 1417 | Returns: |
| 1418 | access_token on success, None on timeout or failure. |
| 1419 | """ |
| 1420 | import sys |
| 1421 | |
| 1422 | interval = _clamp_device_interval(interval) |
| 1423 | started_at = time.time() |
| 1424 | deadline = started_at + timeout |
| 1425 | last_reminder = started_at |
| 1426 | reminder_count = 0 |
| 1427 | max_reminders = 4 |
| 1428 | reminder_interval = 30 # seconds between reminders |
| 1429 | |
| 1430 | while time.time() < deadline: |
| 1431 | time.sleep(interval) |
| 1432 | |
| 1433 | # Periodic reminder of the code while waiting |
| 1434 | if ( |
| 1435 | user_code |
| 1436 | and reminder_count < max_reminders |
| 1437 | and time.time() - last_reminder >= reminder_interval |
| 1438 | ): |
| 1439 | clipboard_hint = " (on your clipboard)" if clipboard_ok else "" |
| 1440 | print( |
| 1441 | f" Still waiting... Your code: {user_code}{clipboard_hint}", |
| 1442 | file=sys.stderr, |
| 1443 | flush=True, |
| 1444 | ) |
| 1445 | last_reminder = time.time() |
| 1446 | reminder_count += 1 |
| 1447 | |
| 1448 | try: |
| 1449 | body = json.dumps({"device_code": device_code}).encode() |
| 1450 | req = Request(f"{_device_base()}/token", data=body, method="POST") |
| 1451 | req.add_header("Content-Type", "application/json") |
| 1452 | with _open_device_request(req, timeout=15) as resp: |
| 1453 | data = _read_bounded_json_dict(resp) |
| 1454 | except HTTPError as exc: |
| 1455 | try: |
| 1456 | reason = str(getattr(exc, "reason", "") or "").lower() |
| 1457 | if exc.code in (400, 403, 428) and "redirect refused" not in reason: |
| 1458 | continue |
| 1459 | logger.warning( |
| 1460 | "Device auth poll error: %s", |
| 1461 | _scrub_error_text(str(exc), secrets=(device_code,)), |
| 1462 | ) |
| 1463 | return None |
| 1464 | finally: |
| 1465 | _close_http_error(exc) |
| 1466 | except (URLError, OSError): |
| 1467 | continue |
| 1468 | |
| 1469 | if data is None: |
| 1470 | logger.warning("Device auth poll returned invalid or oversized JSON.") |
| 1471 | return None |
| 1472 | |
| 1473 | if data.get("access_token"): |
| 1474 | return data["access_token"] |
| 1475 | |
| 1476 | error = data.get("error") |
| 1477 | if error == "slow_down": |
| 1478 | interval = min(interval + 2, 30) |
| 1479 | continue |
| 1480 | if error == "authorization_pending": |
| 1481 | continue |
| 1482 | if error in ("expired_token", "access_denied"): |
| 1483 | logger.warning("Device auth failed: %s", error) |
| 1484 | return None |
| 1485 | |
| 1486 | return None |
| 1487 | |
| 1488 | |
| 1489 | # Bounded retries for transient ScrapeCreators /profile 5xx (see #882). |
| 1490 | _PROFILE_FETCH_ATTEMPTS = 3 |
| 1491 | _PROFILE_FETCH_RETRY_SLEEP_S = 1.0 |
| 1492 | _PROFILE_ERROR_BODY_LIMIT = 200 |
| 1493 | |
| 1494 | |
| 1495 | _PROFILE_ERROR_READ_LIMIT = 65536 |
| 1496 | |
| 1497 | |
| 1498 | _MAX_JSON_REDACT_DEPTH = 8 |
| 1499 | |
| 1500 | |
| 1501 | def _redact_json_value( |
| 1502 | value: Any, |
| 1503 | *, |
| 1504 | secrets: Tuple[str, ...] = (), |
| 1505 | depth: int = 0, |
| 1506 | ) -> Any: |
| 1507 | """Recursively redact sensitive keys/names and scrub string values in parsed JSON.""" |
| 1508 | if depth >= _MAX_JSON_REDACT_DEPTH: |
| 1509 | return "[REDACTED]" |
| 1510 | if isinstance(value, dict): |
| 1511 | redacted: Dict[str, Any] = {} |
| 1512 | for k, v in value.items(): |
| 1513 | is_secret_key = isinstance(k, str) and k.strip().lower() in _SECRET_FIELD_NAMES |
| 1514 | safe_key = _scrub_error_text(str(k), secrets=secrets) |
| 1515 | redacted[safe_key] = ( |
| 1516 | "[REDACTED]" |
| 1517 | if is_secret_key |
| 1518 | else _redact_json_value(v, secrets=secrets, depth=depth + 1) |
| 1519 | ) |
| 1520 | return redacted |
| 1521 | if isinstance(value, list): |
| 1522 | return [_redact_json_value(item, secrets=secrets, depth=depth + 1) for item in value] |
| 1523 | if isinstance(value, str): |
| 1524 | return _scrub_error_text(value, secrets=secrets) |
| 1525 | return value |
| 1526 | |
| 1527 | |
| 1528 | def _http_error_detail( |
| 1529 | exc: HTTPError, |
| 1530 | *, |
| 1531 | body_limit: int = _PROFILE_ERROR_BODY_LIMIT, |
| 1532 | secrets: Tuple[str, ...] = (), |
| 1533 | ) -> str: |
| 1534 | """Build a diagnosable HTTPError string including a scrubbed, truncated body. |
| 1535 | |
| 1536 | JSON dict bodies are parsed, recursively redacted (keys and values), and |
| 1537 | reduced to safe summary fields before serialization. Deeply nested JSON |
| 1538 | that triggers ``RecursionError`` or non-JSON bodies with unclosed secret |
| 1539 | quotes fall back to the scrubbed HTTP status/reason alone. |
| 1540 | """ |
| 1541 | base = _scrub_error_text( |
| 1542 | f"HTTP Error {exc.code}: {getattr(exc, 'reason', '') or ''}".rstrip(": "), |
| 1543 | secrets=secrets, |
| 1544 | ) |
| 1545 | try: |
| 1546 | try: |
| 1547 | raw = exc.read(_PROFILE_ERROR_READ_LIMIT) or b"" |
| 1548 | except TypeError: |
| 1549 | raw = exc.read() or b"" |
| 1550 | except Exception: |
| 1551 | return base |
| 1552 | finally: |
| 1553 | _close_http_error(exc) |
| 1554 | if not raw: |
| 1555 | return base |
| 1556 | text = raw.decode("utf-8", errors="replace").strip() |
| 1557 | if not text: |
| 1558 | return base |
| 1559 | try: |
| 1560 | parsed = json.loads(text) |
| 1561 | except RecursionError: |
| 1562 | return base |
| 1563 | except (json.JSONDecodeError, ValueError, TypeError): |
| 1564 | parsed = None |
| 1565 | if isinstance(parsed, (dict, list)): |
| 1566 | try: |
| 1567 | redacted = _redact_json_value(parsed, secrets=secrets) |
| 1568 | if isinstance(redacted, dict): |
| 1569 | summary = { |
| 1570 | key: redacted[key] |
| 1571 | for key in _SAFE_ERROR_SUMMARY_KEYS |
| 1572 | if key in redacted |
| 1573 | } |
| 1574 | payload = summary or redacted |
| 1575 | else: |
| 1576 | payload = redacted |
| 1577 | text = _scrub_error_text( |
| 1578 | json.dumps(payload, ensure_ascii=False), |
| 1579 | secrets=secrets, |
| 1580 | ) |
| 1581 | except (RecursionError, ValueError, TypeError): |
| 1582 | return base |
| 1583 | else: |
| 1584 | if _UNCLOSED_SECRET_QUOTE_RE.search(text): |
| 1585 | return base |
| 1586 | text = _scrub_error_text(text, secrets=secrets) |
| 1587 | if len(text) > body_limit: |
| 1588 | text = text[:body_limit] + "…" |
| 1589 | return f"{base} body={text!r}" |
| 1590 | |
| 1591 | |
| 1592 | def fetch_api_key(access_token: str) -> Dict[str, Any]: |
| 1593 | """Fetch the ScrapeCreators API key using the GitHub access token. |
| 1594 | |
| 1595 | GETs the device/profile endpoint with Bearer auth. Distinguishes outcomes |
| 1596 | so callers (and SKILL.md) do not collapse a server 5xx into the |
| 1597 | already-linked guidance (#882). |
| 1598 | |
| 1599 | Returns a result dict: |
| 1600 | - ``{"ok": True, "api_key": str}`` on success |
| 1601 | - ``{"ok": False, "reason": "no_api_key"}`` when /profile is 2xx but has |
| 1602 | no ``api_key`` field (typical already-linked account) |
| 1603 | - ``{"ok": False, "reason": "upstream_error", "http_status": int, |
| 1604 | "detail": str}`` on 5xx after bounded retries |
| 1605 | - ``{"ok": False, "reason": "http_error", "http_status": int, |
| 1606 | "detail": str}`` on other HTTP errors (e.g. 401) |
| 1607 | - ``{"ok": False, "reason": "request_failed", "detail": str}`` on |
| 1608 | network/OS failures |
| 1609 | """ |
| 1610 | if ( |
| 1611 | not isinstance(access_token, str) |
| 1612 | or not access_token.strip() |
| 1613 | or any(ord(ch) < 0x20 or ord(ch) >= 0x7F for ch in access_token) |
| 1614 | ): |
| 1615 | logger.warning("Failed to fetch API key: invalid access token") |
| 1616 | return { |
| 1617 | "ok": False, |
| 1618 | "reason": "request_failed", |
| 1619 | "detail": "Invalid access token", |
| 1620 | } |
| 1621 | |
| 1622 | data: Optional[Dict[str, Any]] = None |
| 1623 | last_upstream: Optional[Dict[str, Any]] = None |
| 1624 | |
| 1625 | for attempt in range(_PROFILE_FETCH_ATTEMPTS): |
| 1626 | try: |
| 1627 | req = Request(f"{_device_base()}/profile") |
| 1628 | req.add_header("Authorization", f"Bearer {access_token}") |
| 1629 | with _open_device_request(req, timeout=15) as resp: |
| 1630 | data = _read_bounded_json_dict(resp) |
| 1631 | if data is None: |
| 1632 | logger.warning("Failed to fetch API key: invalid or oversized JSON response") |
| 1633 | return { |
| 1634 | "ok": False, |
| 1635 | "reason": "request_failed", |
| 1636 | "detail": "Invalid or oversized profile response", |
| 1637 | } |
| 1638 | break |
| 1639 | except HTTPError as exc: |
| 1640 | try: |
| 1641 | detail = _http_error_detail(exc, secrets=(access_token,)) |
| 1642 | status_code = int(exc.code) |
| 1643 | finally: |
| 1644 | _close_http_error(exc) |
| 1645 | if 500 <= status_code <= 599: |
| 1646 | logger.warning( |
| 1647 | "Device auth /profile upstream error (attempt %s/%s): %s", |
| 1648 | attempt + 1, |
| 1649 | _PROFILE_FETCH_ATTEMPTS, |
| 1650 | detail, |
| 1651 | ) |
| 1652 | last_upstream = { |
| 1653 | "ok": False, |
| 1654 | "reason": "upstream_error", |
| 1655 | "http_status": status_code, |
| 1656 | "detail": detail, |
| 1657 | } |
| 1658 | if attempt + 1 < _PROFILE_FETCH_ATTEMPTS: |
| 1659 | time.sleep(_PROFILE_FETCH_RETRY_SLEEP_S) |
| 1660 | continue |
| 1661 | return last_upstream |
| 1662 | logger.warning("Failed to fetch API key: %s", detail) |
| 1663 | return { |
| 1664 | "ok": False, |
| 1665 | "reason": "http_error", |
| 1666 | "http_status": status_code, |
| 1667 | "detail": detail, |
| 1668 | } |
| 1669 | except (URLError, OSError) as exc: |
| 1670 | detail = _scrub_error_text(str(exc), secrets=(access_token,)) |
| 1671 | logger.warning("Failed to fetch API key: %s", detail) |
| 1672 | return {"ok": False, "reason": "request_failed", "detail": detail} |
| 1673 | except ValueError: |
| 1674 | logger.warning("Failed to fetch API key: invalid request configuration") |
| 1675 | return { |
| 1676 | "ok": False, |
| 1677 | "reason": "request_failed", |
| 1678 | "detail": "Invalid request configuration", |
| 1679 | } |
| 1680 | |
| 1681 | if data is None: |
| 1682 | # Defensive: loop exited without success or an explicit return. |
| 1683 | return last_upstream or { |
| 1684 | "ok": False, |
| 1685 | "reason": "request_failed", |
| 1686 | "detail": "No profile response", |
| 1687 | } |
| 1688 | |
| 1689 | api_key = data.get("api_key") |
| 1690 | if not api_key: |
| 1691 | # The /profile response parsed but carried no api_key — the common case |
| 1692 | # for a GitHub account already linked to a ScrapeCreators account. Log |
| 1693 | # the response's FIELD NAMES only (never values — the body may contain a |
| 1694 | # key under a different field) so the already-registered response shape |
| 1695 | # can be handled in a follow-up (see plan OQ1). |
| 1696 | logger.warning( |
| 1697 | "Device auth /profile returned no api_key (fields: %s)", sorted(data.keys()) |
| 1698 | ) |
| 1699 | return {"ok": False, "reason": "no_api_key"} |
| 1700 | return {"ok": True, "api_key": api_key} |
| 1701 | |
| 1702 | |
| 1703 | def _device_handle_fallback_dir() -> Path: |
| 1704 | """Return a per-user private fallback directory for the GitHub device handle.""" |
| 1705 | if os.name == "posix": |
| 1706 | uid = os.geteuid() if hasattr(os, "geteuid") else os.getuid() |
| 1707 | return Path(tempfile.gettempdir()) / f"last30days-{uid}" |
| 1708 | local_app_data = os.environ.get("LOCALAPPDATA") |
| 1709 | if local_app_data: |
| 1710 | return Path(local_app_data) / "last30days" |
| 1711 | raw_user = os.environ.get("USERNAME") or os.environ.get("USER") or "user" |
| 1712 | safe_user = re.sub(r"[^A-Za-z0-9._-]", "_", raw_user).strip("._-") or "user" |
| 1713 | return Path(tempfile.gettempdir()) / f"last30days-{safe_user}" |
| 1714 | |
| 1715 | |
| 1716 | def _device_handle_path() -> Path: |
| 1717 | """Where run_github_start persists the device_code/interval for run_github_poll. |
| 1718 | |
| 1719 | Kept next to the .env in the config dir; falls back to a per-user private |
| 1720 | directory when no config dir is resolvable (clean/no-config mode). |
| 1721 | """ |
| 1722 | try: |
| 1723 | from . import env as _env |
| 1724 | |
| 1725 | if _env.CONFIG_FILE: |
| 1726 | return _env.CONFIG_FILE.parent / ".github-device-handle.json" |
| 1727 | except Exception: |
| 1728 | pass |
| 1729 | return _device_handle_fallback_dir() / "github-device-handle.json" |
| 1730 | |
| 1731 | |
| 1732 | def _ensure_private_handle_dir(directory: Path) -> None: |
| 1733 | """Create and verify a private directory for persisting the device handle.""" |
| 1734 | directory = Path(directory) |
| 1735 | is_junction = getattr(os.path, "isjunction", None) |
| 1736 | if is_junction is not None and is_junction(directory): |
| 1737 | raise OSError(f"Refusing to use junction directory: {directory}") |
| 1738 | try: |
| 1739 | st = os.lstat(directory) |
| 1740 | except FileNotFoundError: |
| 1741 | directory.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 1742 | st = os.lstat(directory) |
| 1743 | if stat.S_ISLNK(st.st_mode): |
| 1744 | raise OSError(f"Refusing to use symlink directory: {directory}") |
| 1745 | if not stat.S_ISDIR(st.st_mode): |
| 1746 | raise OSError(f"Expected a directory for device handle: {directory}") |
| 1747 | if os.name == "posix": |
| 1748 | euid = os.geteuid() if hasattr(os, "geteuid") else os.getuid() |
| 1749 | if st.st_uid != euid: |
| 1750 | raise OSError(f"Refusing to use device handle directory owned by another user: {directory}") |
| 1751 | if directory == _device_handle_fallback_dir() and stat.S_IMODE(st.st_mode) != 0o700: |
| 1752 | flags = ( |
| 1753 | os.O_RDONLY |
| 1754 | | getattr(os, "O_DIRECTORY", 0) |
| 1755 | | getattr(os, "O_NOFOLLOW", 0) |
| 1756 | | getattr(os, "O_CLOEXEC", 0) |
| 1757 | ) |
| 1758 | fd = os.open(directory, flags) |
| 1759 | try: |
| 1760 | fd_st = os.fstat(fd) |
| 1761 | if not stat.S_ISDIR(fd_st.st_mode) or fd_st.st_uid != euid: |
| 1762 | raise OSError(f"Refusing to tighten untrusted device handle directory: {directory}") |
| 1763 | if hasattr(os, "fchmod"): |
| 1764 | os.fchmod(fd, 0o700) |
| 1765 | finally: |
| 1766 | os.close(fd) |
| 1767 | |
| 1768 | |
| 1769 | def _persist_device_handle(handle: Dict[str, Any]) -> Path: |
| 1770 | """Atomically persist the private GitHub device-flow handle with 0o600 permissions.""" |
| 1771 | path = _device_handle_path() |
| 1772 | _ensure_private_handle_dir(path.parent) |
| 1773 | replace_private_text(path, json.dumps(handle)) |
| 1774 | if os.name != "posix": |
| 1775 | try: |
| 1776 | os.chmod(path, 0o600) |
| 1777 | except OSError: |
| 1778 | pass |
| 1779 | return path |
| 1780 | |
| 1781 | |
| 1782 | def _read_device_handle(path: Path) -> Dict[str, Any]: |
| 1783 | """Read a persisted device handle without following symlinks or trusting foreign files.""" |
| 1784 | path = Path(path) |
| 1785 | if os.name == "posix": |
| 1786 | path = private_files._resolve_parent_only(path) |
| 1787 | flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) |
| 1788 | fd = os.open(path, flags) |
| 1789 | try: |
| 1790 | st = os.fstat(fd) |
| 1791 | if not stat.S_ISREG(st.st_mode): |
| 1792 | raise OSError(f"Expected a regular device handle file: {path}") |
| 1793 | euid = os.geteuid() if hasattr(os, "geteuid") else os.getuid() |
| 1794 | if st.st_uid != euid: |
| 1795 | raise OSError(f"Refusing device handle owned by another user: {path}") |
| 1796 | if private_files._is_writable_by_others(st, euid): |
| 1797 | raise OSError(f"Refusing device handle writable by other users: {path}") |
| 1798 | with os.fdopen(fd, "r", encoding="utf-8") as stream: |
| 1799 | fd = -1 |
| 1800 | raw = stream.read(65536) |
| 1801 | finally: |
| 1802 | if fd != -1: |
| 1803 | os.close(fd) |
| 1804 | else: |
| 1805 | private_files._reject_symlink_or_nonregular(path) |
| 1806 | raw = path.read_text(encoding="utf-8") |
| 1807 | data = json.loads(raw) |
| 1808 | if not isinstance(data, dict) or not data.get("device_code"): |
| 1809 | raise ValueError("Invalid device handle payload") |
| 1810 | return data |
| 1811 | |
| 1812 | |
| 1813 | def _start_device_flow( |
| 1814 | *, |
| 1815 | persist_handle: Optional[Callable[[Dict[str, Any]], None]] = None, |
| 1816 | ) -> "Tuple[Dict[str, Any], Optional[Dict[str, Any]]]": |
| 1817 | """Submit the GitHub device flow and surface the code, without polling. |
| 1818 | |
| 1819 | Returns ``(public_result, handle)``. ``handle`` is None for the |
| 1820 | already-registered and error cases (nothing to poll); otherwise it carries |
| 1821 | the private poll state (``device_code``/``interval``/``user_code``/ |
| 1822 | ``clipboard_ok``) that never belongs in the public, stdout-printed result. |
| 1823 | Callers either supply ``persist_handle`` (``run_github_start``, persisting |
| 1824 | before printing the code or opening the browser so a write failure never |
| 1825 | strands ``--github-poll``) or hand the handle straight to ``run_github_poll`` |
| 1826 | in-memory (``run_full_device_auth``). |
| 1827 | """ |
| 1828 | import sys |
| 1829 | import webbrowser |
| 1830 | |
| 1831 | # Already-registered short-circuit: a saved key means no device dance. The |
| 1832 | # key is returned raw here and masked at the CLI boundary before print. |
| 1833 | existing = _existing_scrapecreators_key() |
| 1834 | if existing: |
| 1835 | return ( |
| 1836 | { |
| 1837 | "status": "already_registered", |
| 1838 | "method": "existing", |
| 1839 | "api_key": existing, |
| 1840 | "persisted": True, |
| 1841 | }, |
| 1842 | None, |
| 1843 | ) |
| 1844 | |
| 1845 | result = run_device_auth() |
| 1846 | if result is None: |
| 1847 | return ({"status": "error", "message": "Failed to start device auth flow"}, None) |
| 1848 | |
| 1849 | device_code, user_code, verification_uri, interval = result |
| 1850 | |
| 1851 | # Validate the code shape BEFORE copying, labeling, or emitting it. A |
| 1852 | # non-conforming user_code (e.g. a key-shaped value) is never surfaced as a |
| 1853 | # GitHub device code; we stop rather than instruct the user to paste garbage. |
| 1854 | if not isinstance(user_code, str) or not _DEVICE_CODE_RE.match(user_code): |
| 1855 | logger.warning("Device auth returned a non-device-shaped user_code; aborting.") |
| 1856 | return ( |
| 1857 | { |
| 1858 | "status": "error", |
| 1859 | "message": "ScrapeCreators returned an unexpected device-code format.", |
| 1860 | }, |
| 1861 | None, |
| 1862 | ) |
| 1863 | |
| 1864 | if verification_uri is None: |
| 1865 | verification_uri = "" |
| 1866 | if verification_uri != "" and not _is_valid_verification_uri(verification_uri): |
| 1867 | logger.warning("Device auth returned an untrusted verification_uri; aborting.") |
| 1868 | return ( |
| 1869 | { |
| 1870 | "status": "error", |
| 1871 | "message": "ScrapeCreators returned an unexpected verification URI.", |
| 1872 | }, |
| 1873 | None, |
| 1874 | ) |
| 1875 | |
| 1876 | # Copy the code to the clipboard BEFORE opening the browser. |
| 1877 | clipboard_ok = False |
| 1878 | if sys.platform == "darwin": |
| 1879 | try: |
| 1880 | subprocess.run(["pbcopy"], input=user_code.encode(), check=True, timeout=5) |
| 1881 | clipboard_ok = True |
| 1882 | except Exception: |
| 1883 | pass # pbcopy unavailable or failed, fall through |
| 1884 | |
| 1885 | public = { |
| 1886 | "status": "awaiting_authorization", |
| 1887 | "user_code": user_code, |
| 1888 | "verification_uri": verification_uri, |
| 1889 | "clipboard_ok": clipboard_ok, |
| 1890 | } |
| 1891 | handle = { |
| 1892 | "device_code": device_code, |
| 1893 | "interval": interval, |
| 1894 | "user_code": user_code, |
| 1895 | "clipboard_ok": clipboard_ok, |
| 1896 | } |
| 1897 | if persist_handle is not None: |
| 1898 | try: |
| 1899 | persist_handle(handle) |
| 1900 | except Exception as exc: |
| 1901 | logger.warning("Could not persist device handle: %s", exc) |
| 1902 | return ( |
| 1903 | { |
| 1904 | "status": "error", |
| 1905 | "message": "Could not persist GitHub device flow handle.", |
| 1906 | }, |
| 1907 | None, |
| 1908 | ) |
| 1909 | |
| 1910 | # Structured stdout line for machine consumers. |
| 1911 | print( |
| 1912 | json.dumps( |
| 1913 | { |
| 1914 | "event": "device_code_ready", |
| 1915 | "user_code": user_code, |
| 1916 | "verification_uri": verification_uri, |
| 1917 | } |
| 1918 | ), |
| 1919 | flush=True, |
| 1920 | ) |
| 1921 | |
| 1922 | # Print the code as a plain HUMAN line on stdout too, so a foreground caller |
| 1923 | # sees it in the returned output even without reading the JSON. The clipboard |
| 1924 | # claim is only made when pbcopy actually succeeded (else: type it). |
| 1925 | if clipboard_ok: |
| 1926 | print( |
| 1927 | f"Your GitHub code: {user_code} (already on your clipboard - just paste it, Cmd+V)", |
| 1928 | flush=True, |
| 1929 | ) |
| 1930 | else: |
| 1931 | print(f"Your GitHub code: {user_code} (type it on the GitHub page)", flush=True) |
| 1932 | |
| 1933 | # Human box on stderr for direct-terminal users. |
| 1934 | clipboard_hint = " (copied to clipboard)" if clipboard_ok else "" |
| 1935 | code_line = f" Your code: {user_code}{clipboard_hint}" |
| 1936 | action_line = " Paste it on the GitHub page that just opened" |
| 1937 | width = max(len(code_line), len(action_line)) + 2 |
| 1938 | border = "-" * width |
| 1939 | print(f"\n+{border}+", file=sys.stderr) |
| 1940 | print(f"|{code_line.ljust(width)}|", file=sys.stderr) |
| 1941 | print(f"|{action_line.ljust(width)}|", file=sys.stderr) |
| 1942 | print(f"+{border}+", file=sys.stderr) |
| 1943 | |
| 1944 | if verification_uri: |
| 1945 | try: |
| 1946 | webbrowser.open(verification_uri) |
| 1947 | except Exception: |
| 1948 | print(f"Open: {verification_uri}", file=sys.stderr) |
| 1949 | |
| 1950 | return (public, handle) |
| 1951 | |
| 1952 | |
| 1953 | def run_github_start() -> Dict[str, Any]: |
| 1954 | """Start the device flow and persist the poll handle for a later |
| 1955 | ``run_github_poll`` process. Returns the public result (never the private |
| 1956 | device_code). Fails closed with ``status="error"`` if handle persistence |
| 1957 | fails so ``--github-poll`` is never stranded.""" |
| 1958 | persisted = False |
| 1959 | |
| 1960 | def _persist(handle: Dict[str, Any]) -> None: |
| 1961 | nonlocal persisted |
| 1962 | _persist_device_handle(handle) |
| 1963 | persisted = True |
| 1964 | |
| 1965 | public, handle = _start_device_flow(persist_handle=_persist) |
| 1966 | if handle is not None and not persisted: |
| 1967 | try: |
| 1968 | _persist_device_handle(handle) |
| 1969 | except Exception as exc: |
| 1970 | logger.warning("Could not persist device handle: %s", exc) |
| 1971 | return { |
| 1972 | "status": "error", |
| 1973 | "message": "Could not persist GitHub device flow handle.", |
| 1974 | } |
| 1975 | return public |
| 1976 | |
| 1977 | |
| 1978 | def run_github_poll(timeout: int = 300, *, _handle: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: |
| 1979 | """Poll for authorization using the handle from start. |
| 1980 | |
| 1981 | ``_handle`` (in-memory, from the one-shot) takes precedence over the |
| 1982 | persisted handle file. Returns success (with the fetched key), timeout, or |
| 1983 | the honest "Authorized but failed to fetch API key" branch. Deletes the |
| 1984 | persisted handle when the flow terminates. |
| 1985 | """ |
| 1986 | import sys |
| 1987 | |
| 1988 | if _handle is not None: |
| 1989 | data = _handle |
| 1990 | else: |
| 1991 | try: |
| 1992 | data = _read_device_handle(_device_handle_path()) |
| 1993 | except Exception: |
| 1994 | return { |
| 1995 | "status": "error", |
| 1996 | "message": "No pending GitHub device flow; run setup --github-start first.", |
| 1997 | } |
| 1998 | |
| 1999 | device_code = data["device_code"] |
| 2000 | interval = _clamp_device_interval(data.get("interval", 5)) |
| 2001 | user_code = data.get("user_code", "") |
| 2002 | # Read the real clipboard state so the polling reminder never falsely claims |
| 2003 | # the code is on the clipboard (non-macOS, or a failed pbcopy). Missing key |
| 2004 | # (older handle) defaults to False -- don't overstate. |
| 2005 | clipboard_ok = bool(data.get("clipboard_ok", False)) |
| 2006 | |
| 2007 | print("Waiting for authorization...", file=sys.stderr, flush=True) |
| 2008 | access_token = poll_device_auth( |
| 2009 | device_code, interval, timeout=timeout, user_code=user_code, clipboard_ok=clipboard_ok |
| 2010 | ) |
| 2011 | |
| 2012 | def _cleanup() -> None: |
| 2013 | if _handle is not None: |
| 2014 | return |
| 2015 | try: |
| 2016 | target = _device_handle_path() |
| 2017 | if os.name == "posix": |
| 2018 | target = private_files._resolve_parent_only(target) |
| 2019 | else: |
| 2020 | private_files._reject_symlink_or_nonregular(target) |
| 2021 | target.unlink() |
| 2022 | except Exception: |
| 2023 | pass |
| 2024 | |
| 2025 | if access_token is None: |
| 2026 | _cleanup() |
| 2027 | return {"status": "timeout", "user_code": user_code} |
| 2028 | |
| 2029 | fetched = fetch_api_key(access_token) |
| 2030 | _cleanup() |
| 2031 | if fetched.get("ok") and fetched.get("api_key"): |
| 2032 | return { |
| 2033 | "status": "success", |
| 2034 | "method": "device", |
| 2035 | "api_key": fetched["api_key"], |
| 2036 | "user_code": user_code, |
| 2037 | } |
| 2038 | |
| 2039 | # Discriminate failure modes so SKILL.md does not misdiagnose a 5xx as |
| 2040 | # "GitHub already linked" (#882). Keep the historical message only for the |
| 2041 | # 2xx-without-api_key / already-linked case. |
| 2042 | reason = fetched.get("reason") or "request_failed" |
| 2043 | if reason == "no_api_key": |
| 2044 | return { |
| 2045 | "status": "error", |
| 2046 | "message": "Authorized but failed to fetch API key", |
| 2047 | "reason": "no_api_key", |
| 2048 | } |
| 2049 | if reason == "upstream_error": |
| 2050 | http_status = fetched.get("http_status") |
| 2051 | return { |
| 2052 | "status": "error", |
| 2053 | "message": f"Authorized but ScrapeCreators profile failed (HTTP {http_status})", |
| 2054 | "reason": "upstream_error", |
| 2055 | "http_status": http_status, |
| 2056 | "detail": fetched.get("detail"), |
| 2057 | } |
| 2058 | if reason == "http_error": |
| 2059 | http_status = fetched.get("http_status") |
| 2060 | return { |
| 2061 | "status": "error", |
| 2062 | "message": f"Authorized but failed to fetch API key (HTTP {http_status})", |
| 2063 | "reason": "http_error", |
| 2064 | "http_status": http_status, |
| 2065 | "detail": fetched.get("detail"), |
| 2066 | } |
| 2067 | return { |
| 2068 | "status": "error", |
| 2069 | "message": "Authorized but failed to fetch API key", |
| 2070 | "reason": reason, |
| 2071 | "detail": fetched.get("detail"), |
| 2072 | } |
| 2073 | |
| 2074 | |
| 2075 | def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]: |
| 2076 | """Back-compat one-shot: start the device flow, then poll to completion. |
| 2077 | |
| 2078 | Passes the poll handle to ``run_github_poll`` IN MEMORY, so a failed handle- |
| 2079 | file write can't strand the one-shot. Kept so callers of ``setup --github`` / |
| 2080 | ``--device-auth`` still work; the model-driven wizard uses the two-command |
| 2081 | split (start then poll) instead. |
| 2082 | """ |
| 2083 | public, handle = _start_device_flow() |
| 2084 | if handle is None: |
| 2085 | return public # already_registered or error |
| 2086 | return run_github_poll(timeout=timeout, _handle=handle) |
| 2087 | |
| 2088 | |
| 2089 | # --------------------------------------------------------------------------- |
| 2090 | # Unified GitHub auth |
| 2091 | # --------------------------------------------------------------------------- |
| 2092 | |
| 2093 | |
| 2094 | def run_github_auth(timeout: int = 300) -> Dict[str, Any]: |
| 2095 | """Run the --github setup path via device auth (one-shot, back-compat). |
| 2096 | |
| 2097 | The existing-key short-circuit now lives in run_github_start; this delegates |
| 2098 | to the start+poll chain. This path must not read or forward local GitHub CLI |
| 2099 | tokens. |
| 2100 | """ |
| 2101 | return run_full_device_auth(timeout=timeout) |
| 2102 | |
| 2103 | |
| 2104 | # --------------------------------------------------------------------------- |
| 2105 | # Opt-in logged-in Reddit session (setup --reddit-session / --no-reddit-session) |
| 2106 | # --------------------------------------------------------------------------- |
| 2107 | |
| 2108 | REDDIT_SESSION_NOTE = ( |
| 2109 | "With a Reddit login, research reads Reddit as your own account (search, " |
| 2110 | "comment search, communities, threads; never posts, votes, your feed, inbox " |
| 2111 | "or saved items). Automated use of a logged-in account may breach Reddit's " |
| 2112 | "terms and puts that account at risk." |
| 2113 | ) |
| 2114 | |
| 2115 | |
| 2116 | def _reddit_scan_order(config: Dict[str, Any]) -> list[str]: |
| 2117 | from . import env as _env |
| 2118 | |
| 2119 | recorded = str(config.get(_env.REDDIT_FROM_BROWSER_VAR) or "").strip().lower() |
| 2120 | order = [recorded] if recorded in _env.COOKIE_BROWSER_NAMES else [] |
| 2121 | return order + [b for b in _env.REDDIT_SETUP_BROWSERS if b not in order] |
| 2122 | |
| 2123 | |
| 2124 | def run_reddit_session_setup( |
| 2125 | config: Dict[str, Any], |
| 2126 | env_path: Optional[Path], |
| 2127 | *, |
| 2128 | consent: bool, |
| 2129 | reader: Optional[Any] = None, |
| 2130 | ) -> Dict[str, Any]: |
| 2131 | """Record the user's Reddit-session answer and, on yes, find the login. |
| 2132 | |
| 2133 | The answer itself is the consent, so this is the one place that reads the |
| 2134 | reddit.com cookie outside a research run, and only on a yes. It reads |
| 2135 | browsers in order (the recorded one, then Chrome, then the rest), stops at |
| 2136 | the first with a ``reddit_session`` cookie, records that browser as |
| 2137 | ``REDDIT_FROM_BROWSER`` and never prints or saves the cookie. |
| 2138 | ``FROM_BROWSER=off`` and a Grok Bot host read nothing; a |
| 2139 | ``BROWSER_CONSENT=false`` saved for X does not block this explicit yes. Either answer writes ``REDDIT_SESSION_OFFERED=true`` |
| 2140 | so a returning user is asked once. |
| 2141 | """ |
| 2142 | from . import env as _env |
| 2143 | |
| 2144 | host = str(config.get(_env.X_HOST_VAR) or os.environ.get(_env.X_HOST_VAR) or "").strip().lower() |
| 2145 | if host == _env.GROK_BOT_HOST: |
| 2146 | return {"status": "unavailable", "note": "The Reddit session is never used on a Grok Bot host."} |
| 2147 | if env_path: |
| 2148 | written = write_api_key(env_path, "true", key_name=_env.REDDIT_OFFERED_VAR, replace=True) |
| 2149 | written = write_api_key( |
| 2150 | env_path, "true" if consent else "false", key_name=_env.REDDIT_CONSENT_VAR, replace=True, |
| 2151 | ) and written |
| 2152 | else: |
| 2153 | written = False |
| 2154 | if not consent: |
| 2155 | return {"status": "declined", "consent": False, "env_written": written} |
| 2156 | result: Dict[str, Any] = {"consent": True, "env_written": written, "note": REDDIT_SESSION_NOTE} |
| 2157 | probe = dict(config) |
| 2158 | probe["_BROWSER_COOKIE_MODE"] = "read" |
| 2159 | # This setup call is the Reddit yes itself, so only FROM_BROWSER=off vetoes it. |
| 2160 | refusal = _env.global_cookie_refusal(probe, reddit_consent=True) |
| 2161 | if refusal: |
| 2162 | result.update(status="vetoed", reason=refusal, checked=[]) |
| 2163 | return result |
| 2164 | checked = [] |
| 2165 | for browser in _reddit_scan_order(config): |
| 2166 | cookie, state = (reader or _env.read_reddit_session_cookie)(config, browser) |
| 2167 | checked.append({"browser": browser, "result": state}) |
| 2168 | if cookie: |
| 2169 | result["env_written"] = bool( |
| 2170 | env_path |
| 2171 | and write_api_key( |
| 2172 | env_path, browser, key_name=_env.REDDIT_FROM_BROWSER_VAR, replace=True, |
| 2173 | ) |
| 2174 | and written |
| 2175 | ) |
| 2176 | result.update(status="found", browser=browser, checked=checked) |
| 2177 | return result |
| 2178 | result.update(status="not-found", checked=checked) |
| 2179 | return result |
| 2180 |