返回 last30days-skill
brightdata.py
根目录 / skills / last30days / scripts / lib / brightdata.py
1 """Bright Data CLI adapter for last30days.
2
3 Shells out to the ``brightdata`` CLI (``@brightdata/cli``) to run Bright
4 Data Pipelines. The CLI owns authentication end to end -- ``brightdata
5 login`` does a gh-style zero-click browser flow and stores credentials in
6 a platform config directory -- so this module never handles a login, and
7 never reads credential *contents*: the auth probe is presence-only.
8
9 Activation gate: two-way, mirroring the digg CLI-gated precedent but with
10 an auth dimension the digg source does not have.
11
12 1. ``shutil.which("brightdata")`` must resolve on the **agent subprocess
13 PATH** (not merely exist on disk -- Hermes/OpenClaw gateways often drop
14 ``~/.local/bin``).
15 2. A credential signal must be present: either ``BRIGHTDATA_API_KEY``
16 resolved through the normal config layering, or the CLI's own
17 credentials file in the platform config dir.
18
19 The second check is deliberately offline. A stale token passes it and
20 then 401s fast at call time; that path degrades to empty results with the
21 CLI's own error line preserved in the envelope, which is the AE2 contract.
22
23 Metering note (R13): no pricing logic lives here. One pipeline request
24 costs one credit against the account's monthly free tier regardless of how
25 many records come back, so caps in the calling adapter bound *records*
26 (paid-tier cost), not credits. Credit and auth warnings from the CLI are
27 passed through verbatim rather than interpreted.
28 """
29
30 from __future__ import annotations
31
32 import json
33 import os
34 import re
35 import shutil
36 import sys
37 from pathlib import Path
38 from typing import Any, Dict, List, Optional, Sequence
39 from urllib.parse import quote as _url_quote
40
41 from . import log, subproc, usage
42
43
44 CLI_BIN = "brightdata"
45
46 # Env var carrying an explicit API key. Registered in env.py so `.env` file
47 # and keychain users pass the gate the same way process-env users do; when
48 # it resolves from a non-process-env layer we pass it in the child environment.
49 API_KEY_ENV = "BRIGHTDATA_API_KEY"
50
51 # Keep only runtime, credential-file location and network configuration.
52 # In particular, do not inherit other providers' secrets or NODE_OPTIONS.
53 _CHILD_ENV_ALLOWLIST = frozenset({
54 "PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA",
55 "LOCALAPPDATA", "XDG_CONFIG_HOME", "SYSTEMROOT", "WINDIR", "SYSTEMDRIVE",
56 "COMSPEC", "PATHEXT", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "LC_CTYPE",
57 "NODE_EXTRA_CA_CERTS", "NODE_USE_ENV_PROXY", "SSL_CERT_FILE", "SSL_CERT_DIR",
58 "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
59 })
60
61 # Credentials filename written by `brightdata login`. Probed for existence
62 # only -- never opened, parsed, or logged.
63 _CREDENTIALS_FILENAME = "credentials.json"
64 _CONFIG_DIRNAME = "brightdata-cli"
65
66 # The CLI's own polling timeout sits below our subprocess timeout so the CLI
67 # exits cleanly with its own error rather than being SIGTERM'd mid-poll. Its
68 # timeout path throws with zero records (verified in its polling module --
69 # never partial output), so a timed-out pull is a clean parseable failure.
70 _CLI_TIMEOUT_MARGIN = 10
71
72 _METHOD = "collect_by_url"
73
74 # Printed by pre-0.4 CLIs, which have no `pipelines run` or `--input`.
75 _OLD_CLI_MARKERS = ("unknown option '--input'", "Unknown pipeline type")
76 _UPGRADE_HINT = "brightdata CLI is older than 0.4.0; upgrade with: npm i -g @brightdata/cli@latest"
77
78
79 def _log(msg: str) -> None:
80 log.source_log("BrightData", msg, tty_only=False)
81
82
83 def _config_dir() -> Path:
84 """Platform config directory the Bright Data CLI stores credentials in.
85
86 Mirrors the CLI's own credentials module: APPDATA on Windows, the
87 Application Support tree on macOS, XDG_CONFIG_HOME (or ~/.config) on
88 everything else.
89 """
90 if sys.platform == "win32":
91 base = os.environ.get("APPDATA")
92 root = Path(base) if base else Path.home() / "AppData" / "Roaming"
93 elif sys.platform == "darwin":
94 root = Path.home() / "Library" / "Application Support"
95 else:
96 base = os.environ.get("XDG_CONFIG_HOME")
97 root = Path(base) if base else Path.home() / ".config"
98 return root / _CONFIG_DIRNAME
99
100
101 def is_installed() -> bool:
102 """True when the brightdata binary resolves on the agent subprocess PATH."""
103 return shutil.which(CLI_BIN) is not None
104
105
106 # Pattern-based redaction for credentials echoed by the CLI on stderr even
107 # when authenticated via credentials.json rather than BRIGHTDATA_API_KEY.
108 _URL_USERINFO_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]{0,15}://)[^\s/?#]+@")
109 _BEARER_RE = re.compile(r"(?i)\b(Bearer)\s+[^\s,;\"']+")
110 _BASIC_AUTH_RE = re.compile(r"(?i)\b(Authorization\s*:\s*Basic)\s+[^\s,;\"']+")
111 _JSON_SECRET_RE = re.compile(
112 r'(?i)(["\'](?:[A-Za-z0-9_-]*[_-])?(?:api[_-]?key|access[_-]?token|auth[_-]?token|token|authorization)["\']\s*:\s*)'
113 r'(?:"(?:[^"\\\r\n]|\\.)*"|\'(?:[^\'\\\r\n]|\\.)*\')'
114 )
115 _KV_SECRET_RE = re.compile(
116 r'(?i)((?<![A-Za-z0-9])(?:api[_-]?key|access[_-]?token|auth[_-]?token|token)\s*[:=]\s*)'
117 r'(?:"(?:[^"\\\r\n]|\\.)*"|\'(?:[^\'\\\r\n]|\\.)*\'|[^\s,;\"\']+)'
118 )
119 _SPACED_SECRET_RE = re.compile(
120 r"(?i)((?<![A-Za-z0-9-])(?:api[_-]?key|access[_-]?token|auth[_-]?token|token)\s+)"
121 r"(?!(?:is|was|are|has|have|expired|invalid|missing|required|rejected|"
122 r"denied|failed|error|not|for|from|in|to|of)\b)"
123 r"(?:\"(?:[^\"\\\r\n]|\\.){4,}\"|'(?:[^'\\\r\n]|\\.){4,}'|[^\s,;\"']{6,})"
124 )
125
126 # Windows batch shims (.cmd/.bat) trigger cmd.exe via CreateProcessW even with
127 # shell=False (CVE-2024-24576). Unwrap @brightdata/cli to [node, entry.js] and
128 # fail closed whenever a batch shim would receive cmd.exe metacharacters.
129 _BATCH_SUFFIXES = (".cmd", ".bat")
130 _UNSAFE_CMD_ARG_RE = re.compile(r'[\s"&|%^\<\>\(\)!\r\n]')
131
132
133 def _api_key(config: Optional[Dict[str, Any]]) -> str:
134 if config:
135 explicit = str(config.get(API_KEY_ENV) or "").strip()
136 if explicit:
137 return explicit
138 return str(os.environ.get(API_KEY_ENV) or "").strip()
139
140
141 def has_credentials(config: Optional[Dict[str, Any]] = None) -> bool:
142 """True when some credential signal exists, without reading any secret.
143
144 Presence-only by design: an explicit API key resolved through config
145 layering, or the existence of the CLI's credentials file. The file is
146 never opened. This cannot distinguish a live token from an expired one
147 -- that is what the fast 401 at call time is for.
148 """
149 if _api_key(config):
150 return True
151 try:
152 return (_config_dir() / _CREDENTIALS_FILENAME).exists()
153 except OSError:
154 return False
155
156
157 def is_available(config: Optional[Dict[str, Any]] = None) -> bool:
158 """The full activation gate: binary on PATH *and* a credential signal."""
159 return is_installed() and has_credentials(config)
160
161
162 def gate_status(config: Optional[Dict[str, Any]] = None) -> Dict[str, bool]:
163 """Two-field probe for ``pipeline.diagnose`` (bird_installed precedent).
164
165 Network-free, so it is safe on the ``--diagnose`` / doctor path.
166 """
167 installed = is_installed()
168 return {
169 "brightdata_installed": installed,
170 "brightdata_authenticated": installed and has_credentials(config),
171 }
172
173
174 def _find_node_entrypoint(shim_path: Path) -> Optional[Path]:
175 """Locate @brightdata/cli's JS entrypoint relative to a Windows .cmd/.bat shim."""
176 candidate_roots = (
177 shim_path.parent / "node_modules" / "@brightdata" / "cli",
178 shim_path.parent.parent / "lib" / "node_modules" / "@brightdata" / "cli",
179 )
180 for pkg_dir in candidate_roots:
181 if not pkg_dir.is_dir():
182 continue
183 try:
184 pkg_root = pkg_dir.resolve()
185 except OSError:
186 continue
187 rel_candidates: List[str] = []
188 pkg_json = pkg_root / "package.json"
189 if pkg_json.is_file():
190 try:
191 manifest = json.loads(pkg_json.read_text(encoding="utf-8"))
192 except (OSError, json.JSONDecodeError, ValueError):
193 manifest = {}
194 bin_field = manifest.get("bin") if isinstance(manifest, dict) else None
195 if isinstance(bin_field, str) and bin_field.strip():
196 rel_candidates.append(bin_field.strip())
197 elif isinstance(bin_field, dict):
198 entry = bin_field.get(CLI_BIN)
199 if isinstance(entry, str) and entry.strip():
200 rel_candidates.append(entry.strip())
201 rel_candidates.append("dist/index.js")
202 for rel in rel_candidates:
203 rel_norm = rel.replace("\\", "/")
204 if not rel_norm or "\x00" in rel_norm or Path(rel_norm).is_absolute():
205 continue
206 try:
207 candidate = (pkg_root / rel_norm).resolve()
208 except OSError:
209 continue
210 if (
211 candidate.is_relative_to(pkg_root)
212 and candidate.is_file()
213 and candidate.suffix.lower() not in _BATCH_SUFFIXES
214 ):
215 return candidate
216 return None
217
218
219 def _find_node_binary(shim_dir: Path) -> Optional[str]:
220 """Locate a direct (non-batch) Node.js executable for running a JS entrypoint."""
221 for name in ("node.exe", "node"):
222 sibling = shim_dir / name
223 if sibling.is_file() and (
224 name == "node.exe" or os.name == "nt" or os.access(sibling, os.X_OK)
225 ):
226 return str(sibling)
227 node_bin = shutil.which("node")
228 if node_bin and not node_bin.lower().endswith(_BATCH_SUFFIXES):
229 return node_bin
230 return None
231
232
233 def _resolve_cli_command(binary: str) -> List[str]:
234 """Return the argv prefix for invoking ``binary`` without cmd.exe when possible."""
235 if not binary.lower().endswith(_BATCH_SUFFIXES):
236 return [binary]
237 shim_path = Path(binary)
238 entry = _find_node_entrypoint(shim_path)
239 if entry is not None:
240 node_bin = _find_node_binary(shim_path.parent)
241 if node_bin is not None:
242 return [node_bin, str(entry)]
243 return [binary]
244
245
246 def _has_unsafe_cmd_args(args: Sequence[str]) -> bool:
247 """True if any argument contains whitespace or cmd.exe metacharacters."""
248 return any(_UNSAFE_CMD_ARG_RE.search(arg) for arg in args)
249
250
251 def _build_args(
252 dataset_id: str,
253 record: Dict[str, Any],
254 *,
255 cli_timeout: int,
256 binary: str = CLI_BIN,
257 command_prefix: Optional[Sequence[str]] = None,
258 ) -> List[str]:
259 """Assemble a ``pipelines run`` invocation (CLI >= 0.4.0).
260
261 The API key is deliberately **absent** here -- it travels in the child's
262 environment instead (see ``_child_env``). Process arguments are not a
263 secret channel: ``/proc/<pid>/cmdline`` is world-readable under the
264 default ``hidepid=0``, and a review pull lives for up to 180s, so a key
265 on the command line is readable by any other local user and is captured
266 verbatim by execve auditing, process accounting, and any monitoring
267 agent that snapshots ``ps``. Mirrors the ``bird_x`` cookie-injection
268 precedent.
269
270 The record goes in as ``--input`` JSON so numbers keep their type: the
271 API rejects ``"1"`` for a number field.
272 """
273 prefix = list(command_prefix) if command_prefix is not None else [binary]
274 return [
275 *prefix,
276 "pipelines",
277 "run",
278 dataset_id,
279 _METHOD,
280 "--input",
281 json.dumps([record]),
282 "--json",
283 "--timeout",
284 str(cli_timeout),
285 ]
286
287
288 def _child_env(api_key: str) -> Dict[str, str]:
289 """Allowlisted child environment, even when the CLI uses its login file.
290
291 An explicit key takes precedence over an exported Bright Data key.
292 Always return a mapping: None would inherit every parent credential.
293 """
294 child_env = {
295 name: value for name, value in os.environ.items()
296 if name.upper() in _CHILD_ENV_ALLOWLIST
297 }
298 key = str(api_key or "").strip() or str(os.environ.get(API_KEY_ENV) or "").strip()
299 return {**child_env, API_KEY_ENV: key} if key else child_env
300
301
302 def _scrub(text: str, secret: str = "") -> str:
303 """Remove secrets and auth tokens from text before it is logged or returned.
304
305 Defense in depth for the passthrough paths: the stderr lines this
306 module deliberately surfaces are auth and quota failures, which are
307 exactly the messages a CLI is most likely to echo the rejected
308 credential back in.
309 """
310 if not text:
311 return text
312 scrubbed = text
313 ambient = os.environ.get(API_KEY_ENV) or ""
314 raw_candidates = {
315 candidate
316 for raw in (secret, ambient)
317 if isinstance(raw, str)
318 for candidate in (raw, raw.strip())
319 if candidate and candidate.strip()
320 }
321 candidates = set(raw_candidates)
322 for candidate in raw_candidates:
323 encoded = _url_quote(candidate, safe="")
324 if encoded:
325 candidates.add(encoded)
326 for candidate in sorted(candidates, key=len, reverse=True):
327 scrubbed = scrubbed.replace(candidate, "***")
328 scrubbed = _URL_USERINFO_RE.sub(r"\1***@", scrubbed)
329 scrubbed = _BEARER_RE.sub(r"\1 ***", scrubbed)
330 scrubbed = _BASIC_AUTH_RE.sub(r"\1 ***", scrubbed)
331 scrubbed = _JSON_SECRET_RE.sub(r'\1"***"', scrubbed)
332 scrubbed = _KV_SECRET_RE.sub(r"\1***", scrubbed)
333 scrubbed = _SPACED_SECRET_RE.sub(r"\1***", scrubbed)
334 return scrubbed
335
336
337 def _extract_records(payload: Any) -> List[Dict[str, Any]]:
338 """Pull the record list out of a parsed CLI payload.
339
340 Verified live (2026-08-13): both amazon pipelines return a **bare JSON
341 array** of flat record dicts, not the ``{"results": [...]}`` envelope the
342 digg CLI uses. The dict branches below are defensive against CLI churn,
343 which is a live risk on a package this young.
344 """
345 if isinstance(payload, list):
346 return [r for r in payload if isinstance(r, dict)]
347 if isinstance(payload, dict):
348 for key in ("records", "results", "data"):
349 value = payload.get(key)
350 if isinstance(value, list):
351 return [r for r in value if isinstance(r, dict)]
352 return []
353
354
355 def run_pipeline(
356 dataset_id: str,
357 record: Dict[str, Any],
358 *,
359 timeout: int,
360 config: Optional[Dict[str, Any]] = None,
361 ) -> Dict[str, Any]:
362 """Run one Bright Data scraper on one input and return ``{"records", "error"}``.
363
364 Never raises. Every failure mode -- missing binary, spawn failure,
365 subprocess timeout, non-zero exit, unparseable stdout -- returns empty
366 records plus a one-line ``error`` string, so callers can record the
367 failure in ``errors_by_source`` without branching on exception types.
368
369 The CLI's first stderr line is preserved verbatim as the error (auth
370 401s and low-credit warnings are the cases that matter), and also
371 mirrored to ``source_log`` so the failure is visible in non-TTY hosts.
372
373 Args:
374 dataset_id: scraper ID, e.g. ``gd_lwdb4vjm1ehb499uxs``.
375 record: input fields for that scraper, with JSON-native types.
376 timeout: subprocess timeout in seconds. The CLI's own polling
377 timeout is set just below this so it can fail cleanly first.
378 config: resolved config dict, consulted only for the API key.
379
380 Returns:
381 ``{"records": [...]}`` on success, else ``{"records": [], "error": str}``.
382 """
383 resolved = shutil.which(CLI_BIN)
384 if resolved is None:
385 return {"records": [], "error": f"{CLI_BIN} not on PATH"}
386
387 cli_timeout = max(5, int(timeout) - _CLI_TIMEOUT_MARGIN)
388 key = _api_key(config)
389 command_prefix = _resolve_cli_command(resolved)
390 cmd = _build_args(
391 dataset_id,
392 record,
393 cli_timeout=cli_timeout,
394 command_prefix=command_prefix,
395 )
396 if cmd and cmd[0].lower().endswith(_BATCH_SUFFIXES) and _has_unsafe_cmd_args(cmd[1:]):
397 err = (
398 f"cannot safely invoke {CLI_BIN} via Windows batch shim without "
399 "the @brightdata/cli Node entrypoint"
400 )
401 _log(err)
402 return {"records": [], "error": err}
403
404 try:
405 usage.begin("brightdata")
406 result = subproc.run_with_timeout(cmd, timeout=timeout, env=_child_env(key))
407 except subproc.SubprocTimeout as exc:
408 msg = _scrub(str(exc), key)
409 _log(f"Timeout: {msg}")
410 return {"records": [], "error": msg}
411 except FileNotFoundError as exc:
412 msg = _scrub(str(exc), key)
413 _log(f"Binary missing: {msg}")
414 return {"records": [], "error": msg}
415 except OSError as exc:
416 msg = _scrub(str(exc), key)
417 _log(f"Spawn failed: {msg}")
418 return {"records": [], "error": msg}
419
420 stderr = _scrub(result.stderr or "", key)
421 _passthrough_warnings(stderr)
422
423 if result.returncode != 0:
424 lines = [ln.strip() for ln in stderr.strip().splitlines() if ln.strip()]
425 # The CLI narrates polling progress on stderr, so the *last* line is
426 # the actual failure, not the "Snapshot ... started" narration.
427 first = lines[-1] if lines else f"exit {result.returncode}"
428 if any(marker in stderr for marker in _OLD_CLI_MARKERS):
429 first = _UPGRADE_HINT
430 _log(f"CLI exit {result.returncode}: {first}")
431 return {"records": [], "error": first}
432
433 stdout = result.stdout or ""
434 if not stdout.strip():
435 return {"records": []}
436 try:
437 payload = json.loads(stdout)
438 except json.JSONDecodeError as exc:
439 msg = _scrub(str(exc), key)
440 _log(f"JSON decode failed: {msg}")
441 return {"records": [], "error": f"json decode: {msg}"}
442
443 return {"records": _extract_records(payload)}
444
445
446 # Substrings that mark a stderr line worth surfacing even on a successful
447 # run -- credit exhaustion and auth trouble are the two the user must see.
448 # Matched case-insensitively against the CLI's own wording, and echoed
449 # verbatim rather than reworded (R13: no pricing logic, no interpretation).
450 _WARNING_MARKERS = ("credit", "quota", "balance", "unauthor", "401", "expired", "login")
451
452
453 def _passthrough_warnings(stderr: str) -> None:
454 """Echo credit/auth warning lines from the CLI verbatim.
455
456 Skips the routine polling narration so a normal run stays quiet.
457 """
458 for line in (stderr or "").splitlines():
459 text = line.strip()
460 if not text or text.lower().startswith(("status:", "triggering", "triggered", "data received")):
461 continue
462 lowered = text.lower()
463 if any(marker in lowered for marker in _WARNING_MARKERS):
464 _log(text)
465
465 lines PYTHON