| 1 | """Browser cookie extraction for last30days. |
| 2 | |
| 3 | Extracts cookies from local browser databases (Firefox, Chrome, Brave, Safari) |
| 4 | to enable zero-config authentication for services like X/Twitter. |
| 5 | Note: Chrome/Brave extraction is macOS-only; Windows Chrome/Edge use |
| 6 | DPAPI-encrypted stores that are not yet supported. |
| 7 | |
| 8 | Only uses Python stdlib — no external dependencies. |
| 9 | """ |
| 10 | |
| 11 | import configparser |
| 12 | import functools |
| 13 | import logging |
| 14 | import os |
| 15 | import platform |
| 16 | import sqlite3 |
| 17 | import tempfile |
| 18 | import time |
| 19 | from pathlib import Path |
| 20 | from typing import Any, Dict, List, Optional |
| 21 | |
| 22 | from .cookie_paths import path_is_dir, path_is_file |
| 23 | from .sqlite_snapshot import copy_snapshot |
| 24 | |
| 25 | logger = logging.getLogger(__name__) |
| 26 | _SQLITE_TEMP_SIDECARS = ("", "-wal", "-shm", "-journal") |
| 27 | |
| 28 | |
| 29 | class CookieDatabaseReadError(RuntimeError): |
| 30 | """A browser database could not be read to check for a login.""" |
| 31 | |
| 32 | |
| 33 | def has_complete_pair(result: Optional[Dict[str, str]], cookie_names) -> bool: |
| 34 | """Return True when ``result`` holds every requested cookie with a value. |
| 35 | |
| 36 | Shared by the Firefox profile scan, ``env.extract_browser_credentials``, |
| 37 | and the setup wizard so a partial pair (e.g. a lone ``ct0`` from a |
| 38 | logged-out session) never shadows a complete one. Empty values do not |
| 39 | count: ``{"auth_token": "", "ct0": ""}`` is incomplete. ``cookie_names`` |
| 40 | is the spec's cookie list (a spec dict with a ``"cookies"`` key also |
| 41 | works). |
| 42 | """ |
| 43 | if not result: |
| 44 | return False |
| 45 | if isinstance(cookie_names, dict): |
| 46 | cookie_names = cookie_names.get("cookies", []) |
| 47 | return all(result.get(name) for name in cookie_names) |
| 48 | |
| 49 | |
| 50 | def _lock_temp_cookie_copy(path: str) -> None: |
| 51 | """Restrict copied cookie DB temp files to the current user on POSIX.""" |
| 52 | if os.name == "nt": |
| 53 | return |
| 54 | Path(path).chmod(0o600) |
| 55 | |
| 56 | |
| 57 | @functools.lru_cache(maxsize=1) |
| 58 | def _is_wsl() -> bool: |
| 59 | """Detect if running under Windows Subsystem for Linux. |
| 60 | |
| 61 | Cached after the first call since /proc/version doesn't change at runtime. |
| 62 | """ |
| 63 | try: |
| 64 | return "microsoft" in Path("/proc/version").read_text().lower() |
| 65 | except OSError: |
| 66 | return False |
| 67 | |
| 68 | |
| 69 | def _get_wsl_firefox_profiles_dir() -> Optional[Path]: |
| 70 | """Find Firefox profiles directory on the Windows host from WSL. |
| 71 | |
| 72 | Scans /mnt/c/Users/*/AppData/Roaming/Mozilla/Firefox for real user |
| 73 | directories (skips Public, Default, etc.). |
| 74 | """ |
| 75 | mnt_users = Path("/mnt/c/Users") |
| 76 | if not path_is_dir(mnt_users): |
| 77 | return None |
| 78 | skip = {"Public", "Default", "Default User", "All Users"} |
| 79 | denied = None |
| 80 | try: |
| 81 | for user_dir in sorted(mnt_users.iterdir()): |
| 82 | if user_dir.name in skip: |
| 83 | continue |
| 84 | try: |
| 85 | if not path_is_dir(user_dir): |
| 86 | continue |
| 87 | ff_dir = user_dir / "AppData" / "Roaming" / "Mozilla" / "Firefox" |
| 88 | if path_is_dir(ff_dir): |
| 89 | return ff_dir |
| 90 | except PermissionError as exc: |
| 91 | if denied is None: |
| 92 | denied = exc |
| 93 | except PermissionError as exc: |
| 94 | if denied is None: |
| 95 | denied = exc |
| 96 | except OSError: |
| 97 | pass |
| 98 | if denied is not None: |
| 99 | raise denied |
| 100 | return None |
| 101 | |
| 102 | |
| 103 | def _get_firefox_profiles_dir() -> Optional[Path]: |
| 104 | """Return the Firefox profiles directory for the current platform, or None.""" |
| 105 | system = platform.system() |
| 106 | if system == "Darwin": |
| 107 | path = Path.home() / "Library" / "Application Support" / "Firefox" |
| 108 | elif system == "Linux": |
| 109 | # Default location for most distros |
| 110 | path = Path.home() / ".mozilla" / "firefox" |
| 111 | denied = None |
| 112 | try: |
| 113 | if path_is_dir(path): |
| 114 | return path |
| 115 | except PermissionError as exc: |
| 116 | denied = exc |
| 117 | # Some distros (e.g. Fedora) honour $XDG_CONFIG_HOME |
| 118 | xdg_config = os.environ.get("XDG_CONFIG_HOME") |
| 119 | if xdg_config and os.path.isabs(xdg_config): |
| 120 | path = Path(xdg_config) / "mozilla" / "firefox" |
| 121 | else: |
| 122 | path = Path.home() / ".config" / "mozilla" / "firefox" |
| 123 | else: |
| 124 | # Windows: %APPDATA%\Mozilla\Firefox — best-effort |
| 125 | appdata = Path.home() / "AppData" / "Roaming" / "Mozilla" / "Firefox" |
| 126 | path = appdata |
| 127 | if path_is_dir(path): |
| 128 | return path |
| 129 | if system == "Linux" and denied is not None: |
| 130 | raise denied |
| 131 | return None |
| 132 | |
| 133 | |
| 134 | def _load_profiles_ini(ini_path: Path) -> configparser.ConfigParser: |
| 135 | """Parse Firefox profiles.ini, retrying UTF-16 LE used on Windows (#1067).""" |
| 136 | config = configparser.ConfigParser() |
| 137 | try: |
| 138 | config.read(str(ini_path), encoding="utf-8") |
| 139 | except UnicodeDecodeError: |
| 140 | config.read(str(ini_path), encoding="utf-16") |
| 141 | return config |
| 142 | |
| 143 | |
| 144 | def _find_default_profile( |
| 145 | profiles_dir: Path, denials: Optional[list[PermissionError]] = None |
| 146 | ) -> Optional[Path]: |
| 147 | """Parse profiles.ini to find the default profile directory. |
| 148 | |
| 149 | Looks for a section with Default=1. Falls back to the first profile |
| 150 | directory found on disk if profiles.ini is missing or malformed. |
| 151 | """ |
| 152 | ini_path = profiles_dir / "profiles.ini" |
| 153 | denied: list[PermissionError] = [] |
| 154 | |
| 155 | try: |
| 156 | has_ini = path_is_file(ini_path) |
| 157 | except PermissionError as exc: |
| 158 | denied.append(exc) |
| 159 | has_ini = False |
| 160 | if has_ini: |
| 161 | try: |
| 162 | config = _load_profiles_ini(ini_path) |
| 163 | |
| 164 | # First pass: Install* section (Firefox >= 67 format, takes priority) |
| 165 | for section in config.sections(): |
| 166 | if section.startswith("Install") and config.has_option(section, "Default"): |
| 167 | raw = config.get(section, "Default") |
| 168 | candidate = profiles_dir / raw |
| 169 | try: |
| 170 | found = path_is_dir(candidate) |
| 171 | except PermissionError as exc: |
| 172 | denied.append(exc) |
| 173 | continue |
| 174 | if found: |
| 175 | if denials is not None: |
| 176 | denials.extend(denied) |
| 177 | return candidate |
| 178 | |
| 179 | # Second pass: Profile section with Default=1 |
| 180 | for section in config.sections(): |
| 181 | if section.startswith("Profile") and config.has_option(section, "Default") and config.get(section, "Default") == "1": |
| 182 | try: |
| 183 | resolved = _resolve_profile_path(profiles_dir, config, section) |
| 184 | except PermissionError as exc: |
| 185 | denied.append(exc) |
| 186 | continue |
| 187 | if resolved is not None: |
| 188 | if denials is not None: |
| 189 | denials.extend(denied) |
| 190 | return resolved |
| 191 | |
| 192 | # Third pass: first Profile section that exists on disk |
| 193 | for section in config.sections(): |
| 194 | if section.startswith("Profile"): |
| 195 | try: |
| 196 | resolved = _resolve_profile_path(profiles_dir, config, section) |
| 197 | except PermissionError as exc: |
| 198 | denied.append(exc) |
| 199 | continue |
| 200 | if resolved: |
| 201 | if denials is not None: |
| 202 | denials.extend(denied) |
| 203 | return resolved |
| 204 | except PermissionError as exc: |
| 205 | denied.append(exc) |
| 206 | except (configparser.Error, OSError, UnicodeDecodeError) as exc: |
| 207 | logger.debug("Failed to parse profiles.ini: %s", exc) |
| 208 | |
| 209 | # Fallback: scan directory for anything that looks like a profile |
| 210 | profile = _fallback_find_profile(profiles_dir, denied) |
| 211 | if denials is not None: |
| 212 | denials.extend(denied) |
| 213 | elif denied and profile is None: |
| 214 | raise denied[0] |
| 215 | return profile |
| 216 | |
| 217 | |
| 218 | def _resolve_profile_path( |
| 219 | profiles_dir: Path, config: configparser.ConfigParser, section: str |
| 220 | ) -> Optional[Path]: |
| 221 | """Resolve a profile path from a ConfigParser section.""" |
| 222 | if not config.has_option(section, "Path"): |
| 223 | return None |
| 224 | raw_path = config.get(section, "Path") |
| 225 | is_relative = config.has_option(section, "IsRelative") and config.get(section, "IsRelative") == "1" |
| 226 | if is_relative: |
| 227 | candidate = profiles_dir / raw_path |
| 228 | else: |
| 229 | candidate = Path(raw_path) |
| 230 | return candidate if path_is_dir(candidate) else None |
| 231 | |
| 232 | |
| 233 | def _fallback_find_profile( |
| 234 | profiles_dir: Path, denials: Optional[list[PermissionError]] = None |
| 235 | ) -> Optional[Path]: |
| 236 | """Find the first directory that contains cookies.sqlite.""" |
| 237 | denied: list[PermissionError] = [] |
| 238 | try: |
| 239 | for child in sorted(profiles_dir.iterdir()): |
| 240 | try: |
| 241 | if path_is_dir(child) and path_is_file(child / "cookies.sqlite"): |
| 242 | if denials is not None: |
| 243 | denials.extend(denied) |
| 244 | return child |
| 245 | except PermissionError as exc: |
| 246 | denied.append(exc) |
| 247 | except PermissionError as exc: |
| 248 | denied.append(exc) |
| 249 | except OSError: |
| 250 | pass |
| 251 | if denials is not None: |
| 252 | denials.extend(denied) |
| 253 | elif denied: |
| 254 | raise denied[0] |
| 255 | return None |
| 256 | |
| 257 | |
| 258 | def _unlink_sqlite_temp_files(path: Optional[str]) -> None: |
| 259 | """Remove a temporary SQLite copy and any WAL/SHM/journal sidecars.""" |
| 260 | if not path: |
| 261 | return |
| 262 | for suffix in _SQLITE_TEMP_SIDECARS: |
| 263 | try: |
| 264 | Path(path + suffix).unlink(missing_ok=True) |
| 265 | except OSError: |
| 266 | pass |
| 267 | |
| 268 | |
| 269 | def _select_scoped_firefox_cookies( |
| 270 | rows: List[tuple[Any, ...]], |
| 271 | wanted: str, |
| 272 | preferred_host: str, |
| 273 | cookie_names: List[str], |
| 274 | now_unix: int, |
| 275 | *, |
| 276 | schema_version: int = 0, |
| 277 | ) -> Optional[Dict[str, str]]: |
| 278 | """Select cookie values from a single non-expired Firefox scope without mixing.""" |
| 279 | allowed_hosts = (wanted, f".{wanted}") |
| 280 | scopes: Dict[tuple[str, str, str], Dict[str, List[tuple[int, int, bool, int, str]]]] = {} |
| 281 | for name, value, host, path, expiry, is_secure, is_httponly, origin_attrs in rows: |
| 282 | if not isinstance(value, str) or not value: |
| 283 | continue |
| 284 | try: |
| 285 | expiry_val = int(expiry) if expiry is not None else 0 |
| 286 | except (TypeError, ValueError): |
| 287 | continue |
| 288 | if expiry_val != 0: |
| 289 | # Firefox 142+ (PRAGMA user_version >= 16) stores moz_cookies.expiry |
| 290 | # in Unix milliseconds instead of Unix seconds. |
| 291 | if schema_version >= 16 or (schema_version == 0 and expiry_val >= 10**11): |
| 292 | expiry_val //= 1000 |
| 293 | if expiry_val <= now_unix: |
| 294 | continue |
| 295 | host_norm = str(host or "").strip().lower() |
| 296 | if host_norm not in allowed_hosts: |
| 297 | continue |
| 298 | path_norm = path if isinstance(path, str) and path else "/" |
| 299 | partition_norm = str(origin_attrs or "").strip() |
| 300 | secure_flag = 1 if is_secure else 0 |
| 301 | httponly_flag = 1 if is_httponly else 0 |
| 302 | # Host-only (x.com) and domain (.x.com) cookies apply to the same apex |
| 303 | # origin per RFC 6265; pair them within one (path, partition). |
| 304 | scope_key = (host_norm.lstrip("."), path_norm, partition_norm) |
| 305 | scopes.setdefault(scope_key, {}).setdefault(str(name), []).append( |
| 306 | (secure_flag, httponly_flag, host_norm == preferred_host, expiry_val, value) |
| 307 | ) |
| 308 | |
| 309 | if not scopes: |
| 310 | return None |
| 311 | |
| 312 | requested = list(dict.fromkeys(cookie_names)) |
| 313 | resolved_scopes: List[tuple[tuple[Any, ...], Dict[str, str]]] = [] |
| 314 | for scope_key, by_name in scopes.items(): |
| 315 | host_base, path_norm, partition_norm = scope_key |
| 316 | jar: Dict[str, str] = {} |
| 317 | all_secure = True |
| 318 | all_httponly = True |
| 319 | for name, candidates in by_name.items(): |
| 320 | candidates.sort( |
| 321 | key=lambda item: ( |
| 322 | item[0] == 0, |
| 323 | item[1] == 0, |
| 324 | not item[2], |
| 325 | 0 if item[3] == 0 else -item[3], |
| 326 | ) |
| 327 | ) |
| 328 | best = candidates[0] |
| 329 | jar[name] = best[4] |
| 330 | if best[0] == 0: |
| 331 | all_secure = False |
| 332 | if best[1] == 0: |
| 333 | all_httponly = False |
| 334 | if not jar: |
| 335 | continue |
| 336 | complete = all(name in jar for name in requested) |
| 337 | rank = ( |
| 338 | not complete, |
| 339 | partition_norm != "", |
| 340 | path_norm != "/", |
| 341 | not all_secure, |
| 342 | not all_httponly, |
| 343 | path_norm, |
| 344 | host_base, |
| 345 | partition_norm, |
| 346 | ) |
| 347 | resolved_scopes.append((rank, jar)) |
| 348 | |
| 349 | if not resolved_scopes: |
| 350 | return None |
| 351 | resolved_scopes.sort(key=lambda item: item[0]) |
| 352 | return resolved_scopes[0][1] |
| 353 | |
| 354 | |
| 355 | def _query_cookies_db( |
| 356 | db_path: Path, domain: str, cookie_names: List[str], *, windows_wsl: bool = False, |
| 357 | ) -> Optional[Dict[str, str]]: |
| 358 | """Snapshot the cookies database to a private temp dir and query it. |
| 359 | |
| 360 | The snapshot includes committed WAL updates while Firefox is running. |
| 361 | Returns {name: value} dict from a single non-expired scope, or None if no |
| 362 | matching cookies are found. |
| 363 | """ |
| 364 | if not path_is_file(db_path): |
| 365 | return None |
| 366 | wanted = domain.strip().lstrip(".").lower() |
| 367 | if not wanted or not cookie_names: |
| 368 | return None |
| 369 | preferred_host = domain.strip().lower() |
| 370 | if preferred_host not in (wanted, f".{wanted}"): |
| 371 | preferred_host = f".{wanted}" |
| 372 | |
| 373 | try: |
| 374 | with tempfile.TemporaryDirectory(prefix="last30days-cookies-") as tmp_dir: |
| 375 | if os.name != "nt": |
| 376 | os.chmod(tmp_dir, 0o700) |
| 377 | tmp_path = str(Path(tmp_dir) / "cookies.sqlite") |
| 378 | # Pre-create with 0600 on POSIX and close the fd immediately so |
| 379 | # Windows never holds an open descriptor when SQLite writes or |
| 380 | # cleanup unlinks the temp database and its WAL/SHM sidecars. |
| 381 | tmp_fd = os.open(tmp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) |
| 382 | os.close(tmp_fd) |
| 383 | conn: Optional[sqlite3.Connection] = None |
| 384 | schema_version = 0 |
| 385 | try: |
| 386 | if windows_wsl: |
| 387 | copy_snapshot(db_path, tmp_path, wsl_wal_fallback=True) |
| 388 | else: |
| 389 | copy_snapshot(db_path, tmp_path) |
| 390 | _lock_temp_cookie_copy(tmp_path) |
| 391 | |
| 392 | conn = sqlite3.connect(tmp_path) |
| 393 | uv_row = conn.execute("PRAGMA user_version").fetchone() |
| 394 | schema_version = int((uv_row or (0,))[0] or 0) |
| 395 | col_rows = conn.execute("PRAGMA table_info(moz_cookies)").fetchall() |
| 396 | col_map = {str(row[1]).lower(): str(row[1]) for row in col_rows} |
| 397 | if not {"name", "value", "host"}.issubset(col_map): |
| 398 | return None |
| 399 | |
| 400 | path_expr = col_map["path"] if "path" in col_map else "'/'" |
| 401 | expiry_expr = col_map["expiry"] if "expiry" in col_map else "0" |
| 402 | secure_expr = col_map["issecure"] if "issecure" in col_map else "1" |
| 403 | httponly_expr = col_map["ishttponly"] if "ishttponly" in col_map else "1" |
| 404 | partition_expr = ( |
| 405 | col_map["originattributes"] if "originattributes" in col_map else "''" |
| 406 | ) |
| 407 | |
| 408 | placeholders = ",".join("?" for _ in cookie_names) |
| 409 | query = ( |
| 410 | f"SELECT name, value, host, {path_expr}, {expiry_expr}, " |
| 411 | f"{secure_expr}, {httponly_expr}, {partition_expr} " |
| 412 | f"FROM moz_cookies " |
| 413 | f"WHERE LOWER(host) IN (?, ?) AND name IN ({placeholders})" |
| 414 | ) |
| 415 | params = [wanted, f".{wanted}"] + list(cookie_names) |
| 416 | rows = conn.execute(query, params).fetchall() |
| 417 | finally: |
| 418 | if conn is not None: |
| 419 | conn.close() |
| 420 | _unlink_sqlite_temp_files(tmp_path) |
| 421 | |
| 422 | if not rows: |
| 423 | return None |
| 424 | return _select_scoped_firefox_cookies( |
| 425 | rows, |
| 426 | wanted, |
| 427 | preferred_host, |
| 428 | cookie_names, |
| 429 | int(time.time()), |
| 430 | schema_version=schema_version, |
| 431 | ) |
| 432 | |
| 433 | except (sqlite3.Error, OSError) as exc: |
| 434 | if isinstance(exc, PermissionError): |
| 435 | if exc.filename == str(db_path): |
| 436 | raise |
| 437 | if windows_wsl: |
| 438 | source = db_path.resolve() |
| 439 | if exc.filename in (str(source), f"{source}-wal"): |
| 440 | raise |
| 441 | logger.debug("Failed to query cookies database %s: %s", db_path, exc) |
| 442 | if windows_wsl: |
| 443 | raise CookieDatabaseReadError("Could not read Windows Firefox cookies") from exc |
| 444 | return None |
| 445 | |
| 446 | |
| 447 | def _try_firefox_dir( |
| 448 | profiles_dir: Path, domain: str, cookie_names: List[str], *, windows_wsl: bool = False, |
| 449 | ) -> Optional[Dict[str, str]]: |
| 450 | """Try to extract cookies from a Firefox profiles directory. |
| 451 | |
| 452 | Tries the default profile first, then falls back to scanning all |
| 453 | profiles for matching cookies. This handles multi-profile setups |
| 454 | where the user is logged into x.com on a non-default profile. |
| 455 | A complete match (all ``cookie_names``) always wins: a partial |
| 456 | default-profile result is kept only as a fallback. |
| 457 | """ |
| 458 | denials: list[PermissionError] = [] |
| 459 | read_errors: list[CookieDatabaseReadError] = [] |
| 460 | |
| 461 | def query(db: Path) -> Optional[Dict[str, str]]: |
| 462 | try: |
| 463 | return _query_cookies_db(db, domain, cookie_names, windows_wsl=windows_wsl) |
| 464 | except PermissionError as exc: |
| 465 | denials.append(exc) |
| 466 | except CookieDatabaseReadError as exc: |
| 467 | read_errors.append(exc) |
| 468 | return None |
| 469 | |
| 470 | default_profile = _find_default_profile(profiles_dir, denials) |
| 471 | profiles_tried = 0 |
| 472 | fallback: Optional[Dict[str, str]] = None |
| 473 | if default_profile is not None: |
| 474 | result = query(default_profile / "cookies.sqlite") |
| 475 | if result is not None: |
| 476 | if has_complete_pair(result, cookie_names): |
| 477 | return result |
| 478 | fallback = result |
| 479 | profiles_tried = 1 |
| 480 | # Fallback: scan every profile directory for matching cookies |
| 481 | try: |
| 482 | for child in sorted(profiles_dir.iterdir()): |
| 483 | try: |
| 484 | if not path_is_dir(child): |
| 485 | continue |
| 486 | if default_profile is not None and child == default_profile: |
| 487 | continue |
| 488 | db = child / "cookies.sqlite" |
| 489 | if path_is_file(db): |
| 490 | result = query(db) |
| 491 | if result is not None: |
| 492 | if has_complete_pair(result, cookie_names): |
| 493 | return result |
| 494 | if fallback is None: |
| 495 | fallback = result |
| 496 | profiles_tried += 1 |
| 497 | except PermissionError as exc: |
| 498 | denials.append(exc) |
| 499 | except PermissionError as exc: |
| 500 | denials.append(exc) |
| 501 | except OSError: |
| 502 | pass |
| 503 | if denials: |
| 504 | raise denials[0] |
| 505 | if fallback is not None: |
| 506 | return fallback |
| 507 | if read_errors: |
| 508 | raise read_errors[0] |
| 509 | logger.debug("No matching cookies found in %d Firefox profile(s)", profiles_tried) |
| 510 | return None |
| 511 | |
| 512 | |
| 513 | def extract_firefox_cookies( |
| 514 | domain: str, cookie_names: List[str] |
| 515 | ) -> Optional[Dict[str, str]]: |
| 516 | """Extract cookies from Firefox for the given domain and cookie names. |
| 517 | |
| 518 | Finds the default Firefox profile, copies cookies.sqlite to a temp file |
| 519 | (to avoid lock conflicts), and queries for the requested cookies. |
| 520 | |
| 521 | On WSL2, falls back to Windows Firefox if native Linux Firefox has no |
| 522 | matching cookies. If that database cannot be read, raises |
| 523 | CookieDatabaseReadError so callers can distinguish failure from no match. |
| 524 | |
| 525 | Args: |
| 526 | domain: The cookie domain to match (e.g. ".x.com"). Matched with LIKE %domain. |
| 527 | cookie_names: List of cookie names to extract (e.g. ["auth_token", "ct0"]). |
| 528 | |
| 529 | Returns: |
| 530 | Dict of {cookie_name: cookie_value} or None if no match. |
| 531 | """ |
| 532 | result = _extract_firefox_with_source(domain, cookie_names) |
| 533 | return result[0] if result is not None else None |
| 534 | |
| 535 | |
| 536 | def extract_chrome_cookies( |
| 537 | domain: str, cookie_names: List[str] |
| 538 | ) -> Optional[Dict[str, str]]: |
| 539 | """Extract cookies from Chrome for the given domain and cookie names. |
| 540 | |
| 541 | macOS only — uses Keychain + system openssl for AES-128-CBC decryption. |
| 542 | Linux/Windows not supported (Chrome uses platform-specific encryption). |
| 543 | |
| 544 | Returns: |
| 545 | Dict of {cookie_name: cookie_value} or None if extraction fails. |
| 546 | """ |
| 547 | if platform.system() != "Darwin": |
| 548 | logger.debug("Chrome cookie extraction only supported on macOS") |
| 549 | return None |
| 550 | try: |
| 551 | from .chrome_cookies import extract_chrome_cookies_macos |
| 552 | return extract_chrome_cookies_macos(domain, cookie_names) |
| 553 | except PermissionError: |
| 554 | raise |
| 555 | except Exception as exc: |
| 556 | logger.debug("Chrome cookie extraction failed: %s", exc) |
| 557 | return None |
| 558 | |
| 559 | |
| 560 | def extract_brave_cookies( |
| 561 | domain: str, cookie_names: List[str] |
| 562 | ) -> Optional[Dict[str, str]]: |
| 563 | """Extract cookies from Brave for the given domain and cookie names. |
| 564 | |
| 565 | macOS only — Brave uses the same v10 AES-128-CBC encryption as Chrome, |
| 566 | with a different DB path and Keychain service name ("Brave Safe Storage"). |
| 567 | Tries the Default profile first, then scans numbered Profile directories. |
| 568 | |
| 569 | Returns: |
| 570 | Dict of {cookie_name: cookie_value} or None if extraction fails. |
| 571 | """ |
| 572 | if platform.system() != "Darwin": |
| 573 | logger.debug("Brave cookie extraction only supported on macOS") |
| 574 | return None |
| 575 | try: |
| 576 | from .chrome_cookies import extract_brave_cookies_macos |
| 577 | return extract_brave_cookies_macos(domain, cookie_names) |
| 578 | except PermissionError: |
| 579 | raise |
| 580 | except Exception as exc: |
| 581 | logger.debug("Brave cookie extraction failed: %s", exc) |
| 582 | return None |
| 583 | |
| 584 | |
| 585 | def _extract_chromium_family_cookies( |
| 586 | browser: str, domain: str, cookie_names: List[str] |
| 587 | ) -> Optional[Dict[str, str]]: |
| 588 | """Extract cookies from a non-Chrome/Brave Chromium browser on macOS. |
| 589 | |
| 590 | macOS only — Edge, Vivaldi, Opera, Arc, Dia, and Chromium all reuse Chrome's |
| 591 | v10 AES-128-CBC encryption, with their own profile path and Keychain |
| 592 | service name (see chrome_cookies.CHROMIUM_BROWSER_PROFILES). |
| 593 | """ |
| 594 | if platform.system() != "Darwin": |
| 595 | logger.debug("%s cookie extraction only supported on macOS", browser) |
| 596 | return None |
| 597 | try: |
| 598 | from .chrome_cookies import extract_chromium_browser_cookies_macos |
| 599 | return extract_chromium_browser_cookies_macos(browser, domain, cookie_names) |
| 600 | except PermissionError: |
| 601 | raise |
| 602 | except Exception as exc: |
| 603 | logger.debug("%s cookie extraction failed: %s", browser, exc) |
| 604 | return None |
| 605 | |
| 606 | |
| 607 | def extract_edge_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]: |
| 608 | """Extract cookies from Microsoft Edge for the given domain (macOS only).""" |
| 609 | return _extract_chromium_family_cookies("edge", domain, cookie_names) |
| 610 | |
| 611 | |
| 612 | def extract_vivaldi_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]: |
| 613 | """Extract cookies from Vivaldi for the given domain (macOS only).""" |
| 614 | return _extract_chromium_family_cookies("vivaldi", domain, cookie_names) |
| 615 | |
| 616 | |
| 617 | def extract_opera_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]: |
| 618 | """Extract cookies from Opera for the given domain (macOS only).""" |
| 619 | return _extract_chromium_family_cookies("opera", domain, cookie_names) |
| 620 | |
| 621 | |
| 622 | def extract_arc_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]: |
| 623 | """Extract cookies from Arc for the given domain (macOS only).""" |
| 624 | return _extract_chromium_family_cookies("arc", domain, cookie_names) |
| 625 | |
| 626 | |
| 627 | def extract_dia_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]: |
| 628 | """Extract cookies from Dia for the given domain (macOS only).""" |
| 629 | return _extract_chromium_family_cookies("dia", domain, cookie_names) |
| 630 | |
| 631 | |
| 632 | def extract_ardia_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]: |
| 633 | """Extract cookies from Ardia (Chromium-based).""" |
| 634 | return _extract_chromium_family_cookies("ardia", domain, cookie_names) |
| 635 | |
| 636 | |
| 637 | def extract_chromium_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]: |
| 638 | """Extract cookies from open-source Chromium for the given domain (macOS only).""" |
| 639 | return _extract_chromium_family_cookies("chromium", domain, cookie_names) |
| 640 | |
| 641 | |
| 642 | def extract_safari_cookies( |
| 643 | domain: str, cookie_names: List[str] |
| 644 | ) -> Optional[Dict[str, str]]: |
| 645 | """Extract cookies from Safari for the given domain and cookie names. |
| 646 | |
| 647 | macOS only — parses the unencrypted binary cookie file. |
| 648 | |
| 649 | Returns: |
| 650 | Dict of {cookie_name: cookie_value} or None if extraction fails. |
| 651 | """ |
| 652 | if platform.system() != "Darwin": |
| 653 | logger.debug("Safari cookie extraction only supported on macOS") |
| 654 | return None |
| 655 | try: |
| 656 | from .safari_cookies import extract_safari_cookies_macos |
| 657 | return extract_safari_cookies_macos(domain, cookie_names) |
| 658 | except PermissionError: |
| 659 | raise |
| 660 | except Exception as exc: |
| 661 | logger.debug("Safari cookie extraction failed: %s", exc) |
| 662 | return None |
| 663 | |
| 664 | |
| 665 | def extract_cookies( |
| 666 | browser: str, domain: str, cookie_names: list[str] |
| 667 | ) -> Optional[dict[str, str]]: |
| 668 | """Extract cookies from the specified browser. |
| 669 | |
| 670 | See extract_cookies_with_source() for selection and permission-error behavior. |
| 671 | |
| 672 | Args: |
| 673 | browser: One of 'firefox', 'chrome', 'brave', 'edge', 'vivaldi', |
| 674 | 'opera', 'arc', 'dia', 'ardia', 'chromium', 'safari', or 'auto'. |
| 675 | 'auto' tries browsers in platform-appropriate order: |
| 676 | - macOS: Chrome -> Brave -> Edge -> Vivaldi -> Opera -> Arc -> Dia -> Ardia -> Chromium -> Firefox -> Safari |
| 677 | - Linux: Firefox only |
| 678 | domain: The cookie domain to match (e.g. ".x.com"). |
| 679 | cookie_names: List of cookie names to extract. |
| 680 | |
| 681 | Returns: |
| 682 | Dict of {cookie_name: cookie_value} or None if extraction fails. |
| 683 | """ |
| 684 | result = extract_cookies_with_source(browser, domain, cookie_names) |
| 685 | if result is None: |
| 686 | return None |
| 687 | cookies, _browser_name = result |
| 688 | return cookies |
| 689 | |
| 690 | |
| 691 | def _extract_firefox_with_source( |
| 692 | domain: str, cookie_names: List[str] |
| 693 | ) -> Optional[tuple[Dict[str, str], str]]: |
| 694 | """Extract Firefox cookies and report whether they came from native or WSL. |
| 695 | |
| 696 | Returns (cookies, "firefox") for native Linux/macOS Firefox, or |
| 697 | (cookies, "firefox-wsl") for Windows Firefox accessed via WSL2. |
| 698 | """ |
| 699 | denied = None |
| 700 | try: |
| 701 | profiles_dir = _get_firefox_profiles_dir() |
| 702 | except PermissionError as exc: |
| 703 | denied = exc |
| 704 | profiles_dir = None |
| 705 | if profiles_dir is not None: |
| 706 | try: |
| 707 | result = _try_firefox_dir(profiles_dir, domain, cookie_names) |
| 708 | except PermissionError as exc: |
| 709 | denied = exc |
| 710 | result = None |
| 711 | if result is not None: |
| 712 | return (result, "firefox") |
| 713 | |
| 714 | if platform.system() == "Linux" and _is_wsl(): |
| 715 | try: |
| 716 | wsl_dir = _get_wsl_firefox_profiles_dir() |
| 717 | except PermissionError as exc: |
| 718 | if denied is None: |
| 719 | denied = exc |
| 720 | wsl_dir = None |
| 721 | if wsl_dir is not None: |
| 722 | logger.debug("Trying Windows Firefox via WSL: %s", wsl_dir) |
| 723 | try: |
| 724 | result = _try_firefox_dir(wsl_dir, domain, cookie_names, windows_wsl=True) |
| 725 | except PermissionError as exc: |
| 726 | if denied is None: |
| 727 | denied = exc |
| 728 | result = None |
| 729 | except CookieDatabaseReadError: |
| 730 | if denied is not None: |
| 731 | raise denied from None |
| 732 | raise |
| 733 | if result is not None: |
| 734 | return (result, "firefox-wsl") |
| 735 | |
| 736 | if denied is not None: |
| 737 | raise denied |
| 738 | if profiles_dir is None: |
| 739 | logger.debug("Firefox profiles directory not found") |
| 740 | return None |
| 741 | |
| 742 | |
| 743 | def extract_cookies_with_source( |
| 744 | browser: str, domain: str, cookie_names: list[str] |
| 745 | ) -> Optional[tuple[dict[str, str], str]]: |
| 746 | """Extract cookies and report which browser they came from. |
| 747 | |
| 748 | Same as extract_cookies() but returns a (cookies, browser_name) tuple |
| 749 | so callers can track the source. |
| 750 | |
| 751 | Auto mode tries browsers in platform order until one supplies every requested |
| 752 | cookie with a nonempty value. If none does, it returns the first partial |
| 753 | result without combining cookies from different browsers. A browser's |
| 754 | access or database read error does not stop later candidates from being tried. |
| 755 | |
| 756 | Args: |
| 757 | browser: One of 'firefox', 'chrome', 'brave', 'edge', 'vivaldi', |
| 758 | 'opera', 'arc', 'dia', 'ardia', 'chromium', 'safari', or 'auto'. |
| 759 | domain: Bare or dot-prefixed cookie domain (e.g. "x.com" or ".x.com"). |
| 760 | cookie_names: List of cookie names to extract. |
| 761 | |
| 762 | Returns: |
| 763 | Tuple of ({cookie_name: cookie_value}, browser_name) or None. |
| 764 | browser_name is "firefox-wsl" when cookies came from Windows Firefox via WSL2. |
| 765 | |
| 766 | Raises: |
| 767 | PermissionError: The explicitly selected browser denies access, or auto |
| 768 | mode encounters a denial and no browser returns even a partial result. |
| 769 | CookieDatabaseReadError: Windows Firefox cannot be read and no other |
| 770 | candidate supplies cookies or reports a permission denial. |
| 771 | """ |
| 772 | extractors = { |
| 773 | "firefox": extract_firefox_cookies, |
| 774 | "chrome": extract_chrome_cookies, |
| 775 | "brave": extract_brave_cookies, |
| 776 | "edge": extract_edge_cookies, |
| 777 | "vivaldi": extract_vivaldi_cookies, |
| 778 | "opera": extract_opera_cookies, |
| 779 | "arc": extract_arc_cookies, |
| 780 | "dia": extract_dia_cookies, |
| 781 | "ardia": extract_ardia_cookies, |
| 782 | "chromium": extract_chromium_cookies, |
| 783 | "safari": extract_safari_cookies, |
| 784 | } |
| 785 | |
| 786 | if browser != "auto": |
| 787 | if browser == "firefox": |
| 788 | return _extract_firefox_with_source(domain, cookie_names) |
| 789 | extractor = extractors.get(browser) |
| 790 | if extractor is None: |
| 791 | logger.warning("Unknown browser: %s", browser) |
| 792 | return None |
| 793 | result = extractor(domain, cookie_names) |
| 794 | return (result, browser) if result is not None else None |
| 795 | |
| 796 | # Auto mode: try browsers in platform-appropriate order. |
| 797 | # Note: the skill's own entry point (env.extract_browser_credentials) builds |
| 798 | # its own list that tries the SILENT browsers (Firefox, Safari) first to |
| 799 | # avoid macOS Keychain prompts. This standalone "auto" is Chromium-first; the |
| 800 | # two orderings are intentional for their respective callers. |
| 801 | system = platform.system() |
| 802 | if system == "Darwin": |
| 803 | order = ["chrome", "brave", "edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium", "firefox", "safari"] |
| 804 | elif system == "Linux": |
| 805 | order = ["firefox"] |
| 806 | else: |
| 807 | order = ["firefox"] |
| 808 | |
| 809 | fallback = None |
| 810 | first_denial = None |
| 811 | first_read_error = None |
| 812 | for name in order: |
| 813 | try: |
| 814 | if name == "firefox": |
| 815 | result = _extract_firefox_with_source(domain, cookie_names) |
| 816 | else: |
| 817 | cookies = extractors[name](domain, cookie_names) |
| 818 | result = (cookies, name) if cookies is not None else None |
| 819 | except PermissionError as exc: |
| 820 | if first_denial is None: |
| 821 | first_denial = exc |
| 822 | continue |
| 823 | except CookieDatabaseReadError as exc: |
| 824 | if first_read_error is None: |
| 825 | first_read_error = exc |
| 826 | continue |
| 827 | |
| 828 | if result is not None: |
| 829 | if has_complete_pair(result[0], cookie_names): |
| 830 | return result |
| 831 | if fallback is None: |
| 832 | fallback = result |
| 833 | |
| 834 | if fallback is not None: |
| 835 | return fallback |
| 836 | if first_denial is not None: |
| 837 | raise first_denial |
| 838 | if first_read_error is not None: |
| 839 | raise first_read_error |
| 840 | |
| 841 | return None |
| 842 |