Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat(cookies): support the full Chromium browser family on macOS (Brave/Edge/Vivaldi/Opera/Arc/Chromium) (#572)

Andrey Esipova86c8a162b4c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a1618c8..aed9a4b9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+### Added
+
+- Browser-cookie auth for X/Twitter now covers the full Chromium family on macOS - Brave, Microsoft Edge, Vivaldi, Opera, Arc, and Chromium - alongside the existing Chrome, Firefox, and Safari. They all share Chrome's v10 AES-128-CBC decryption, differing only in profile path and Keychain service name, so they run through one shared decryption core. The profile finder probes both the modern `Default/Network/Cookies` layout (Chromium >= 96) and the legacy flat `Default/Cookies`, and Chrome now resolves through that same finder so it picks up the modern layout too. Set `FROM_BROWSER=auto` to try every browser, or `FROM_BROWSER=<name>` (e.g. `brave`, `edge`, `arc`) to target one. Verified end-to-end on real Brave and Edge installs ([#572](https://github.com/mvanhorn/last30days-skill/pull/572)).
- **First-party positioning research + pitch-vs-pulse synthesis (company / product / service topics).** A new mandatory research step captures each entity's current stated positioning from first-party sources (homepage, docs, pricing) rather than from memory. The fetched pitch grounds `What it is` descriptions (entities described as they pitch themselves today), helps reject unrelated brand-name noise, and feeds an evidence-triggered prose beat: when the month's conversation directly supports a specific claim, cuts against one, or is squarely about the pitched ground, the synthesis says so anchored to the top thread — and stays silent when the pulse is orthogonal to the pitch, because a manufactured connection is worse than omission. Claims are tested at matched altitude (specific claims against specific threads; broad taglines are never graded against individual items), and statements stay windowed to the 30 days — no trend verdicts. Scoped to entities with an identifiable first party: people are always excluded (even founders whose companies qualify), as are events, abstract concepts, and ownerless topics like Bitcoin; the beat requires positioning fetched during the run, never from memory.
### Changed
@@ -17,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `extract_browser_credentials()` silently ignored Brave even though the lower-level `cookie_extract` layer already supported it: `FROM_BROWSER=brave` fell back to Firefox/Safari and `FROM_BROWSER=auto` never tried Brave. The env wiring now passes Brave - and the rest of the Chromium family - through to the extractor ([#572](https://github.com/mvanhorn/last30days-skill/pull/572)).
+- Chromium cookie extraction now fetches the macOS Keychain key lazily - only when an encrypted cookie actually needs decrypting. Previously the key was fetched as soon as the cookie DB existed, so `FROM_BROWSER=auto` could trigger a Keychain prompt for every installed Chromium browser. Now only the browser that actually holds the requested cookie prompts ([#572](https://github.com/mvanhorn/last30days-skill/pull/572)).
- YouTube transcript budget prioritises recent videos (by a combination of views and recency) instead of views alone, preventing transcript slots from being consumed by old high-view-count videos that would be discarded by strict_recent freshness pruning ([#531](https://github.com/mvanhorn/last30days-skill/issues/531))
- YouTube items with successfully extracted transcripts are no longer pruned by title-only relevance scoring; the transcript content proves substantive topical coverage even when the video title has low lexical overlap with the query ([#468](https://github.com/mvanhorn/last30days-skill/issues/468))
- First-run setup wizard in SKILL.md now references the existing Python setup wizard (`last30days.py setup`) instead of the missing `nux-wizard.md` file, so first-run setup actually runs on new installs. ([#574](https://github.com/mvanhorn/last30days-skill/issues/574))
@@ -29,6 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Entity-grounding rerank demotion now keys on the head token of the primary entity instead of requiring the full multi-word phrase as a contiguous substring. A high-engagement on-entity item (e.g. a 323-pt HN thread titled "Stripe is friendly to 'friendly fraud'") is no longer demoted to score 0 on a `Stripe payments` query just because it lacks the trailing search-hint word. The intended demotion still fires for items that never name the brand at all. The keyless Reddit comment-enrichment slot selection (`_slot_priority`), which mirrors this signal, was updated to the same head-token grounding so the two paths stay consistent.
- `--plan` / `--competitors-plan` file reads now specify `encoding="utf-8"` and catch `UnicodeDecodeError`, preventing crashes on non-ASCII content like accented entity names on Windows (cp1252). `check_perms()` in `check-config.sh` now skips the POSIX 600-permission check on MSYS/MinGW/Cygwin where `stat` runs in noacl mode. `skill_meta.py` `read_skill_version()` now passes `encoding="utf-8"` so SKILL.md emoji doesn't break version detection on Windows. ([#549](https://github.com/mvanhorn/last30days-skill/issues/549))
+
## [3.3.2] - 2026-06-06
### Fixed
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 5b1cf7df..d1ac0df5 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -86,7 +86,11 @@ AUTH_TOKEN=<your-auth-token>
CT0=<your-ct0-token>
# OR xAI API key (paid)
# XAI_API_KEY=<your-xai-key>
-# OR cookie-jar (free; logs in via your browser session)
+# OR cookie-jar (free; logs in via your browser session).
+# Unset = Firefox + Safari (silent). FROM_BROWSER=auto also tries the Chromium
+# family (Chrome, Brave, Edge, Vivaldi, Opera, Arc, Chromium); it only prompts
+# for macOS Keychain access on the browser that actually holds your X cookies.
+# Or name a single browser, e.g. brave/edge. On Windows only Firefox is supported.
# FROM_BROWSER=firefox
# Bluesky
diff --git a/skills/last30days/scripts/lib/chrome_cookies.py b/skills/last30days/scripts/lib/chrome_cookies.py
index a415025b..ea414d2b 100644
--- a/skills/last30days/scripts/lib/chrome_cookies.py
+++ b/skills/last30days/scripts/lib/chrome_cookies.py
@@ -1,12 +1,13 @@
-"""Chrome and Brave cookie extraction for macOS.
+"""Chromium-family cookie extraction for macOS.
Extracts cookies from Chromium-based browser SQLite databases using only
stdlib modules and the system openssl CLI (ships with macOS). Zero pip
dependencies.
Chromium on macOS uses v10 encryption (AES-128-CBC with Keychain-stored key).
-Chrome and Brave share the same algorithm; only the DB path and Keychain
-service name differ.
+Every Chromium-based browser (Chrome, Brave, Edge, Vivaldi, Opera, Arc,
+Chromium) shares the same algorithm; only the profile directory and Keychain
+service name differ, so they all run through the same decryption core.
This is NOT affected by Windows App-Bound Encryption (v20).
"""
@@ -30,8 +31,25 @@ def _lock_temp_cookie_copy(path: str) -> None:
Path(path).chmod(0o600)
# Cookie DB locations on macOS
-CHROME_COOKIES_DB = Path.home() / "Library" / "Application Support" / "Google" / "Chrome" / "Default" / "Cookies"
-BRAVE_BASE_DIR = Path.home() / "Library" / "Application Support" / "BraveSoftware" / "Brave-Browser"
+_APP_SUPPORT = Path.home() / "Library" / "Application Support"
+CHROME_BASE_DIR = _APP_SUPPORT / "Google" / "Chrome"
+# Kept for backward compatibility; resolution now goes through the profile
+# finder (which also handles the modern Network/Cookies layout).
+CHROME_COOKIES_DB = CHROME_BASE_DIR / "Default" / "Cookies"
+BRAVE_BASE_DIR = _APP_SUPPORT / "BraveSoftware" / "Brave-Browser"
+
+# Other Chromium-based browsers, keyed by FROM_BROWSER name. Each maps to
+# (profile base directory, macOS Keychain service name). Chrome and Brave keep
+# their dedicated helpers below for backward compatibility; everything here is
+# resolved generically by extract_chromium_browser_cookies_macos(). Keychain
+# service names follow Chromium's "<Browser> Safe Storage" convention.
+CHROMIUM_BROWSER_PROFILES: dict[str, tuple[Path, str]] = {
+ "edge": (_APP_SUPPORT / "Microsoft Edge", "Microsoft Edge Safe Storage"),
+ "vivaldi": (_APP_SUPPORT / "Vivaldi", "Vivaldi Safe Storage"),
+ "opera": (_APP_SUPPORT / "com.operasoftware.Opera", "Opera Safe Storage"),
+ "arc": (_APP_SUPPORT / "Arc" / "User Data", "Arc Safe Storage"),
+ "chromium": (_APP_SUPPORT / "Chromium", "Chromium Safe Storage"),
+}
# Chromium v10 encryption constants (shared by Chrome and Brave)
CHROME_SALT = b"saltysalt"
@@ -206,9 +224,6 @@ def _extract_chromium_cookies_macos(
logger.info("%s cookies database not found at %s", keychain_service, db_path)
return None
- passphrase = _get_chromium_encryption_key(keychain_service)
- aes_key = _derive_aes_key(passphrase) if passphrase else None
-
# Copy DB to temp file (browser locks the original while running)
tmp_fd = None
tmp_path = None
@@ -245,12 +260,23 @@ def _extract_chromium_cookies_macos(
cursor.execute(query, params)
results: dict[str, str] = {}
+ aes_key = None
+ key_fetched = False
for name, value, encrypted_value in cursor.fetchall():
if value:
results[name] = value
continue
if encrypted_value and encrypted_value[:3] == b"v10":
+ if not key_fetched:
+ # Fetch the Keychain key lazily — only once we actually have
+ # an encrypted cookie to decrypt. This avoids a macOS
+ # Keychain prompt for browsers that don't hold the requested
+ # cookie, which matters for FROM_BROWSER=auto across several
+ # installed Chromium browsers.
+ passphrase = _get_chromium_encryption_key(keychain_service)
+ aes_key = _derive_aes_key(passphrase) if passphrase else None
+ key_fetched = True
if aes_key is None:
logger.debug("Skipping encrypted cookie %s — no Keychain access", name)
continue
@@ -284,40 +310,76 @@ def _extract_chromium_cookies_macos(
def extract_chrome_cookies_macos(domain: str, cookie_names: list[str]) -> Optional[dict[str, str]]:
- """Extract cookies from Chrome on macOS."""
+ """Extract cookies from Chrome on macOS.
+
+ Resolves the cookie DB through the shared profile finder so Chrome gets the
+ same modern ``Default/Network/Cookies`` (Chromium >= 96) and legacy
+ ``Default/Cookies`` probing as the rest of the Chromium family.
+ """
+ db_path = _find_chromium_cookies_db(CHROME_BASE_DIR)
+ if db_path is None:
+ logger.info("Chrome cookies database not found under %s", CHROME_BASE_DIR)
+ return None
return _extract_chromium_cookies_macos(
- CHROME_COOKIES_DB, "Chrome Safe Storage", domain, cookie_names
+ db_path, "Chrome Safe Storage", domain, cookie_names
)
-def _find_brave_cookies_db() -> Optional[Path]:
- """Find Brave's Cookies database on macOS.
+def _profile_cookie_db(profile_dir: Path) -> Optional[Path]:
+ """Return the Cookies DB inside a profile dir, or None.
- Tries the Default profile first, then scans numbered Profile directories
- by most-recently-modified. Brave creates extra profiles as "Profile 1",
- "Profile 2", etc. alongside Default; the most recently used one is the
- likeliest to hold current cookies. Lexicographic sort would visit
- "Profile 10" before "Profile 2", which can return the wrong profile.
+ Prefers the modern ``Network/Cookies`` location (Chromium >= 96 moved the
+ cookie store into a per-profile ``Network/`` subdirectory) and falls back
+ to the legacy flat ``Cookies`` file. Different browsers and versions use
+ different layouts, so both are probed.
"""
- default = BRAVE_BASE_DIR / "Default" / "Cookies"
- if default.exists():
- return default
+ for rel in ("Network/Cookies", "Cookies"):
+ candidate = profile_dir / rel
+ if candidate.exists():
+ return candidate
+ return None
+
+
+def _find_chromium_cookies_db(base_dir: Path) -> Optional[Path]:
+ """Find a Chromium-based browser's Cookies database under base_dir.
+
+ Checks the Default profile first, then the base dir itself (Opera's flat
+ layout), then numbered "Profile N" directories by most-recently-modified.
+ Each location is probed for both the modern ``Network/Cookies`` and legacy
+ ``Cookies`` paths (see _profile_cookie_db). Chromium browsers create extra
+ profiles as "Profile 1", "Profile 2", etc. alongside Default; the most
+ recently used one is the likeliest to hold current cookies. Lexicographic
+ sort would visit "Profile 10" before "Profile 2", which can return the
+ wrong profile, so we sort by mtime.
+ """
+ found = _profile_cookie_db(base_dir / "Default")
+ if found:
+ return found
+
+ found = _profile_cookie_db(base_dir)
+ if found:
+ return found
try:
candidates = [
- child for child in BRAVE_BASE_DIR.iterdir()
+ child for child in base_dir.iterdir()
if child.is_dir() and child.name.startswith("Profile ")
]
for child in sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True):
- candidate = child / "Cookies"
- if candidate.exists():
- return candidate
+ found = _profile_cookie_db(child)
+ if found:
+ return found
except OSError:
pass
return None
+def _find_brave_cookies_db() -> Optional[Path]:
+ """Find Brave's Cookies database on macOS (Default, then Profile N)."""
+ return _find_chromium_cookies_db(BRAVE_BASE_DIR)
+
+
def extract_brave_cookies_macos(domain: str, cookie_names: list[str]) -> Optional[dict[str, str]]:
"""Extract cookies from Brave on macOS.
@@ -329,3 +391,24 @@ def extract_brave_cookies_macos(domain: str, cookie_names: list[str]) -> Optiona
logger.info("Brave cookies database not found under %s", BRAVE_BASE_DIR)
return None
return _extract_chromium_cookies_macos(db_path, "Brave Safe Storage", domain, cookie_names)
+
+
+def extract_chromium_browser_cookies_macos(
+ browser: str, domain: str, cookie_names: list[str]
+) -> Optional[dict[str, str]]:
+ """Extract cookies from a registry-defined Chromium browser on macOS.
+
+ Covers every browser in CHROMIUM_BROWSER_PROFILES (Edge, Vivaldi, Opera,
+ Arc, Chromium). They all reuse Chrome's v10 AES-128-CBC encryption; only
+ the profile directory and Keychain service name differ.
+ """
+ spec = CHROMIUM_BROWSER_PROFILES.get(browser)
+ if spec is None:
+ logger.debug("Unknown Chromium browser: %s", browser)
+ return None
+ base_dir, keychain_service = spec
+ db_path = _find_chromium_cookies_db(base_dir)
+ if db_path is None:
+ logger.info("%s cookies database not found under %s", keychain_service, base_dir)
+ return None
+ return _extract_chromium_cookies_macos(db_path, keychain_service, domain, cookie_names)
diff --git a/skills/last30days/scripts/lib/cookie_extract.py b/skills/last30days/scripts/lib/cookie_extract.py
index 806c81af..5cc244e5 100644
--- a/skills/last30days/scripts/lib/cookie_extract.py
+++ b/skills/last30days/scripts/lib/cookie_extract.py
@@ -313,6 +313,51 @@ def extract_brave_cookies(
return None
+def _extract_chromium_family_cookies(
+ browser: str, domain: str, cookie_names: List[str]
+) -> Optional[Dict[str, str]]:
+ """Extract cookies from a non-Chrome/Brave Chromium browser on macOS.
+
+ macOS only — Edge, Vivaldi, Opera, Arc, and Chromium all reuse Chrome's
+ v10 AES-128-CBC encryption, with their own profile path and Keychain
+ service name (see chrome_cookies.CHROMIUM_BROWSER_PROFILES).
+ """
+ if platform.system() != "Darwin":
+ logger.debug("%s cookie extraction only supported on macOS", browser)
+ return None
+ try:
+ from .chrome_cookies import extract_chromium_browser_cookies_macos
+ return extract_chromium_browser_cookies_macos(browser, domain, cookie_names)
+ except Exception as exc:
+ logger.debug("%s cookie extraction failed: %s", browser, exc)
+ return None
+
+
+def extract_edge_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]:
+ """Extract cookies from Microsoft Edge for the given domain (macOS only)."""
+ return _extract_chromium_family_cookies("edge", domain, cookie_names)
+
+
+def extract_vivaldi_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]:
+ """Extract cookies from Vivaldi for the given domain (macOS only)."""
+ return _extract_chromium_family_cookies("vivaldi", domain, cookie_names)
+
+
+def extract_opera_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]:
+ """Extract cookies from Opera for the given domain (macOS only)."""
+ return _extract_chromium_family_cookies("opera", domain, cookie_names)
+
+
+def extract_arc_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]:
+ """Extract cookies from Arc for the given domain (macOS only)."""
+ return _extract_chromium_family_cookies("arc", domain, cookie_names)
+
+
+def extract_chromium_cookies(domain: str, cookie_names: List[str]) -> Optional[Dict[str, str]]:
+ """Extract cookies from open-source Chromium for the given domain (macOS only)."""
+ return _extract_chromium_family_cookies("chromium", domain, cookie_names)
+
+
def extract_safari_cookies(
domain: str, cookie_names: List[str]
) -> Optional[Dict[str, str]]:
@@ -340,9 +385,10 @@ def extract_cookies(
"""Extract cookies from the specified browser.
Args:
- browser: One of 'firefox', 'chrome', 'brave', 'safari', or 'auto'.
+ browser: One of 'firefox', 'chrome', 'brave', 'edge', 'vivaldi',
+ 'opera', 'arc', 'chromium', 'safari', or 'auto'.
'auto' tries browsers in platform-appropriate order:
- - macOS: Chrome -> Brave -> Firefox -> Safari
+ - macOS: Chrome -> Brave -> Edge -> Vivaldi -> Opera -> Arc -> Chromium -> Firefox -> Safari
- Linux: Firefox only
domain: The cookie domain to match (e.g. ".x.com").
cookie_names: List of cookie names to extract.
@@ -391,7 +437,8 @@ def extract_cookies_with_source(
so callers can track the source.
Args:
- browser: One of 'firefox', 'chrome', 'brave', 'safari', or 'auto'.
+ browser: One of 'firefox', 'chrome', 'brave', 'edge', 'vivaldi',
+ 'opera', 'arc', 'chromium', 'safari', or 'auto'.
domain: The cookie domain to match (e.g. ".x.com").
cookie_names: List of cookie names to extract.
@@ -403,6 +450,11 @@ def extract_cookies_with_source(
"firefox": extract_firefox_cookies,
"chrome": extract_chrome_cookies,
"brave": extract_brave_cookies,
+ "edge": extract_edge_cookies,
+ "vivaldi": extract_vivaldi_cookies,
+ "opera": extract_opera_cookies,
+ "arc": extract_arc_cookies,
+ "chromium": extract_chromium_cookies,
"safari": extract_safari_cookies,
}
@@ -416,10 +468,14 @@ def extract_cookies_with_source(
result = extractor(domain, cookie_names)
return (result, browser) if result is not None else None
- # Auto mode: try browsers in platform-appropriate order
+ # Auto mode: try browsers in platform-appropriate order.
+ # Note: the skill's own entry point (env.extract_browser_credentials) builds
+ # its own list that tries the SILENT browsers (Firefox, Safari) first to
+ # avoid macOS Keychain prompts. This standalone "auto" is Chromium-first; the
+ # two orderings are intentional for their respective callers.
system = platform.system()
if system == "Darwin":
- order = ["chrome", "brave", "firefox", "safari"]
+ order = ["chrome", "brave", "edge", "vivaldi", "opera", "arc", "chromium", "firefox", "safari"]
elif system == "Linux":
order = ["firefox"]
else:
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index e11b0903..225fbe56 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -482,28 +482,34 @@ def cookie_extraction_browsers(config: dict[str, Any]) -> list[str]:
"""Browsers to try for cookie extraction, honoring FROM_BROWSER.
Default (FROM_BROWSER unset): Firefox and Safari only. These read local
- files silently with no system dialogs. Chrome/Brave are skipped because
- reading their cookies on macOS requires the "Chrome Safe Storage" Keychain
- key, which triggers a system password prompt that cannot be reliably
- suppressed. On Windows only Firefox cookie extraction is supported; Chrome
- and Edge use DPAPI-encrypted cookie stores that are not yet supported.
-
- - ``FROM_BROWSER=firefox|chrome|safari`` - that single browser.
- - ``FROM_BROWSER=auto`` - also try Chrome (the user has accepted the dialog).
+ files silently with no system dialogs. The Chromium family (Chrome, Brave,
+ Edge, Vivaldi, Opera, Arc, Chromium) is skipped because reading their
+ cookies on macOS requires the browser's Safe Storage Keychain key, which
+ triggers a system password prompt that cannot be reliably suppressed. On
+ Windows only Firefox cookie extraction is supported; Chrome and Edge use
+ DPAPI-encrypted cookie stores that are not yet supported.
+
+ - ``FROM_BROWSER=<name>`` - a single browser (e.g. ``firefox``, ``brave``,
+ ``edge``, ``arc``).
+ - ``FROM_BROWSER=auto`` - also try every Chromium browser (user accepts the
+ Keychain dialog when needed).
- ``FROM_BROWSER=off`` - returns [] (extraction disabled).
Returning the browser list from one place keeps the setup wizard and the
steady-state path on the same policy, so neither surprises the user with an
unrequested Keychain prompt.
"""
+ silent_browsers = ["firefox", "safari"]
+ chromium_browsers = ["chrome", "brave", "edge", "vivaldi", "opera", "arc", "chromium"]
from_browser = (config.get("FROM_BROWSER") or "").strip().lower()
if from_browser == "off":
return []
- if from_browser in ("firefox", "chrome", "safari"):
+ if from_browser in silent_browsers or from_browser in chromium_browsers:
return [from_browser]
if from_browser == "auto":
- return ["firefox", "safari", "chrome"]
- return ["firefox", "safari"]
+ return silent_browsers + chromium_browsers
+ return list(silent_browsers)
+
def extract_browser_credentials(config: dict[str, Any]) -> dict[str, str]:
diff --git a/skills/last30days/scripts/lib/ui.py b/skills/last30days/scripts/lib/ui.py
index a797295a..f68ff14e 100644
--- a/skills/last30days/scripts/lib/ui.py
+++ b/skills/last30days/scripts/lib/ui.py
@@ -203,8 +203,8 @@ PROMO_SINGLE_KEY = {
"reddit": "\n💡 Unlock TikTok and Instagram with SCRAPECREATORS_API_KEY - 100 free credits, no CC - scrapecreators.com\n",
"x": "\n💡 Unlock X: log into x.com in your browser, then re-run. "
"Firefox works on all platforms. Safari works on macOS (detected automatically). "
- "Chrome on macOS requires FROM_BROWSER=auto in .env (Keychain dialog). "
- "On Windows only Firefox is supported. "
+ "Chrome, Brave, Edge, Arc, Vivaldi, Opera, or Chromium on macOS require "
+ "FROM_BROWSER=auto in .env (Keychain dialog). On Windows only Firefox is supported. "
"Or add AUTH_TOKEN/CT0 or XAI_API_KEY.\n",
"web": "\n💡 You can unlock native grounded web search with BRAVE_API_KEY or SERPER_API_KEY.\n",
}
diff --git a/tests/test_chrome_cookies.py b/tests/test_chrome_cookies.py
index a64eb962..557659d0 100644
--- a/tests/test_chrome_cookies.py
+++ b/tests/test_chrome_cookies.py
@@ -206,8 +206,8 @@ class TestDecryption:
class TestChromeNotInstalled:
def test_db_not_found(self):
with mock.patch(
- "lib.chrome_cookies.CHROME_COOKIES_DB",
- Path("/nonexistent/path/Cookies"),
+ "lib.chrome_cookies._find_chromium_cookies_db",
+ return_value=None,
):
result = extract_chrome_cookies_macos(".x.com", ["auth_token"])
assert result is None
@@ -284,7 +284,7 @@ class TestUnencryptedCookies:
(".x.com", "ct0", "plain_ct0_value", b""),
])
- with mock.patch("lib.chrome_cookies.CHROME_COOKIES_DB", Path(db_path)):
+ with mock.patch("lib.chrome_cookies._find_chromium_cookies_db", return_value=Path(db_path)):
# No keychain needed for unencrypted values
with mock.patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=None):
result = extract_chrome_cookies_macos(".x.com", ["auth_token", "ct0"])
@@ -313,7 +313,7 @@ class TestFullExtraction:
(".other.com", "other", "", b""), # unrelated cookie
])
- with mock.patch("lib.chrome_cookies.CHROME_COOKIES_DB", Path(db_path)):
+ with mock.patch("lib.chrome_cookies._find_chromium_cookies_db", return_value=Path(db_path)):
with mock.patch(
"lib.chrome_cookies._get_chromium_encryption_key",
return_value=KNOWN_PASSPHRASE,
@@ -330,7 +330,7 @@ class TestFullExtraction:
(".other.com", "session", "val", b""),
])
- with mock.patch("lib.chrome_cookies.CHROME_COOKIES_DB", Path(db_path)):
+ with mock.patch("lib.chrome_cookies._find_chromium_cookies_db", return_value=Path(db_path)):
with mock.patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=None):
result = extract_chrome_cookies_macos(".x.com", ["auth_token"])
@@ -347,7 +347,7 @@ class TestFullExtraction:
(".x.com", "auth_token", "", encrypted_auth),
], db_version=24)
- with mock.patch("lib.chrome_cookies.CHROME_COOKIES_DB", Path(db_path)):
+ with mock.patch("lib.chrome_cookies._find_chromium_cookies_db", return_value=Path(db_path)):
with mock.patch(
"lib.chrome_cookies._get_chromium_encryption_key",
return_value=KNOWN_PASSPHRASE,
diff --git a/tests/test_chromium_browsers.py b/tests/test_chromium_browsers.py
new file mode 100644
index 00000000..8ebf1cd0
--- /dev/null
+++ b/tests/test_chromium_browsers.py
@@ -0,0 +1,317 @@
+"""Tests for the extended Chromium-family browser cookie support.
+
+Covers the three layers wired up for Brave/Edge/Vivaldi/Opera/Arc/Chromium:
+ - env.extract_browser_credentials (which browsers FROM_BROWSER selects)
+ - cookie_extract (routing browser name -> extractor)
+ - chrome_cookies (registry, profile finder, extraction)
+"""
+
+import sqlite3
+from unittest.mock import patch
+
+import pytest
+
+from lib.env import extract_browser_credentials
+from lib.cookie_extract import extract_cookies
+from lib.chrome_cookies import (
+ CHROMIUM_BROWSER_PROFILES,
+ _find_chromium_cookies_db,
+ extract_chromium_browser_cookies_macos,
+)
+
+# The Chromium-based browsers added on top of the original Chrome support.
+NEW_CHROMIUM_BROWSERS = ["brave", "edge", "vivaldi", "opera", "arc", "chromium"]
+ALL_AUTO_BROWSERS = ["firefox", "safari", "chrome", *NEW_CHROMIUM_BROWSERS]
+
+
+def _base_config(**overrides):
+ cfg = {
+ "AUTH_TOKEN": None,
+ "CT0": None,
+ "TRUTHSOCIAL_TOKEN": None,
+ "FROM_BROWSER": None,
+ "SETUP_COMPLETE": None,
+ }
+ cfg.update(overrides)
+ return cfg
+
+
+def _make_cookies_db(path, rows, db_version: int = 20) -> None:
+ """Create a minimal Chromium Cookies SQLite DB with plain (unencrypted) values."""
+ conn = sqlite3.connect(str(path))
+ c = conn.cursor()
+ c.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
+ c.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", (str(db_version),))
+ c.execute(
+ "CREATE TABLE cookies ("
+ " host_key TEXT NOT NULL,"
+ " name TEXT NOT NULL,"
+ " value TEXT NOT NULL DEFAULT '',"
+ " encrypted_value BLOB NOT NULL DEFAULT x''"
+ ")"
+ )
+ for host_key, name, value in rows:
+ c.execute(
+ "INSERT INTO cookies (host_key, name, value, encrypted_value) VALUES (?, ?, ?, ?)",
+ (host_key, name, value, b""),
+ )
+ conn.commit()
+ conn.close()
+
+
+def _make_encrypted_cookies_db(path, rows, db_version: int = 24) -> None:
+ """Create a Cookies DB with v10-encrypted_value rows (empty value column)."""
+ conn = sqlite3.connect(str(path))
+ c = conn.cursor()
+ c.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
+ c.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", (str(db_version),))
+ c.execute(
+ "CREATE TABLE cookies ("
+ " host_key TEXT NOT NULL,"
+ " name TEXT NOT NULL,"
+ " value TEXT NOT NULL DEFAULT '',"
+ " encrypted_value BLOB NOT NULL DEFAULT x''"
+ ")"
+ )
+ for host_key, name, encrypted_value in rows:
+ c.execute(
+ "INSERT INTO cookies (host_key, name, value, encrypted_value) VALUES (?, ?, ?, ?)",
+ (host_key, name, "", encrypted_value),
+ )
+ conn.commit()
+ conn.close()
+
+
+# ---------------------------------------------------------------------------
+# env.py: FROM_BROWSER selects the right browsers
+# ---------------------------------------------------------------------------
+
+
+class TestEnvBrowserSelection:
+ @pytest.mark.parametrize("browser", NEW_CHROMIUM_BROWSERS)
+ @patch("lib.cookie_extract.extract_cookies")
+ def test_explicit_chromium_browser_is_used(self, mock_extract, browser):
+ """FROM_BROWSER=<chromium browser> routes extraction to that browser."""
+ mock_extract.return_value = {"auth_token": "tok", "ct0": "ct0val"}
+ config = _base_config(FROM_BROWSER=browser)
+
+ result = extract_browser_credentials(config)
+
+ assert result["AUTH_TOKEN"] == "tok"
+ assert result["CT0"] == "ct0val"
+ # Every extraction call targeted exactly the requested browser.
+ assert mock_extract.call_args_list
+ for call in mock_extract.call_args_list:
+ assert call[0][0] == browser
+
+ @patch("lib.cookie_extract.extract_cookies")
+ def test_auto_tries_every_chromium_browser(self, mock_extract):
+ """FROM_BROWSER=auto tries Firefox/Safari plus the whole Chromium family."""
+ mock_extract.return_value = None # force it to try them all
+ config = _base_config(FROM_BROWSER="auto")
+
+ extract_browser_credentials(config)
+
+ tried = {call[0][0] for call in mock_extract.call_args_list}
+ for browser in ALL_AUTO_BROWSERS:
+ assert browser in tried, f"auto should try {browser}"
+
+ @patch("lib.cookie_extract.extract_cookies")
+ def test_default_still_silent_only(self, mock_extract):
+ """Default (no FROM_BROWSER) stays Firefox+Safari - no Keychain prompt."""
+ mock_extract.return_value = None
+ config = _base_config()
+
+ extract_browser_credentials(config)
+
+ tried = {call[0][0] for call in mock_extract.call_args_list}
+ assert tried == {"firefox", "safari"}
+
+
+# ---------------------------------------------------------------------------
+# cookie_extract.py: browser name routes to the chrome_cookies registry
+# ---------------------------------------------------------------------------
+
+
+class TestCookieExtractRouting:
+ @pytest.mark.parametrize("browser", ["edge", "vivaldi", "opera", "arc", "chromium"])
+ def test_routes_to_registry(self, browser):
+ with (
+ patch("lib.cookie_extract.platform.system", return_value="Darwin"),
+ patch(
+ "lib.chrome_cookies.extract_chromium_browser_cookies_macos",
+ return_value={"auth_token": f"{browser}_tok"},
+ ) as mock_macos,
+ ):
+ result = extract_cookies(browser, ".x.com", ["auth_token"])
+
+ assert result == {"auth_token": f"{browser}_tok"}
+ # The browser key is threaded through to the macOS extractor.
+ assert mock_macos.call_args[0][0] == browser
+
+ @pytest.mark.parametrize("browser", ["edge", "vivaldi", "opera", "arc", "chromium"])
+ def test_non_macos_returns_none(self, browser):
+ with patch("lib.cookie_extract.platform.system", return_value="Linux"):
+ assert extract_cookies(browser, ".x.com", ["auth_token"]) is None
+
+ def test_auto_macos_order_includes_chromium_family(self):
+ """auto on macOS calls every Chromium-family extractor when all miss."""
+ with (
+ patch("lib.cookie_extract.platform.system", return_value="Darwin"),
+ patch("lib.cookie_extract._extract_firefox_with_source", return_value=None),
+ patch("lib.cookie_extract.extract_chrome_cookies", return_value=None) as m_chrome,
+ patch("lib.cookie_extract.extract_brave_cookies", return_value=None) as m_brave,
+ patch("lib.cookie_extract.extract_edge_cookies", return_value=None) as m_edge,
+ patch("lib.cookie_extract.extract_vivaldi_cookies", return_value=None) as m_viv,
+ patch("lib.cookie_extract.extract_opera_cookies", return_value=None) as m_opera,
+ patch("lib.cookie_extract.extract_arc_cookies", return_value=None) as m_arc,
+ patch("lib.cookie_extract.extract_chromium_cookies", return_value=None) as m_chr,
+ patch("lib.cookie_extract.extract_safari_cookies", return_value=None),
+ ):
+ result = extract_cookies("auto", ".x.com", ["auth_token"])
+
+ assert result is None
+ for mock_fn in (m_chrome, m_brave, m_edge, m_viv, m_opera, m_arc, m_chr):
+ mock_fn.assert_called_once_with(".x.com", ["auth_token"])
+
+
+# ---------------------------------------------------------------------------
+# chrome_cookies.py: registry, profile finder, generic extraction
+# ---------------------------------------------------------------------------
+
+
+class TestChromiumRegistry:
+ def test_registry_has_expected_browsers(self):
+ assert set(CHROMIUM_BROWSER_PROFILES) == {"edge", "vivaldi", "opera", "arc", "chromium"}
+ for base_dir, service in CHROMIUM_BROWSER_PROFILES.values():
+ assert service.endswith("Safe Storage")
+ assert base_dir is not None
+
+ def test_unknown_browser_returns_none(self):
+ assert extract_chromium_browser_cookies_macos("netscape", ".x.com", ["auth_token"]) is None
+
+ def test_generic_extraction_plain_values(self, tmp_path):
+ """A registry browser extracts unencrypted cookies via the shared core."""
+ base = tmp_path / "Edge"
+ (base / "Default").mkdir(parents=True)
+ _make_cookies_db(
+ base / "Default" / "Cookies",
+ [
+ (".x.com", "auth_token", "edge_auth"),
+ (".x.com", "ct0", "edge_ct0"),
+ (".other.com", "session", "nope"),
+ ],
+ )
+
+ with (
+ patch.dict(
+ "lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
+ {"edge": (base, "Microsoft Edge Safe Storage")},
+ ),
+ # Plain values need no Keychain; ensure we never prompt.
+ patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=None),
+ ):
+ result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token", "ct0"])
+
+ assert result == {"auth_token": "edge_auth", "ct0": "edge_ct0"}
+
+ def test_db_not_found_returns_none(self, tmp_path):
+ empty = tmp_path / "Vivaldi"
+ empty.mkdir()
+ with patch.dict(
+ "lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
+ {"vivaldi": (empty, "Vivaldi Safe Storage")},
+ ):
+ assert extract_chromium_browser_cookies_macos("vivaldi", ".x.com", ["auth_token"]) is None
+
+
+class TestFindChromiumCookiesDb:
+ def test_prefers_default_profile(self, tmp_path):
+ (tmp_path / "Default").mkdir()
+ default_db = tmp_path / "Default" / "Cookies"
+ default_db.touch()
+ (tmp_path / "Cookies").touch() # direct file should be ignored
+ assert _find_chromium_cookies_db(tmp_path) == default_db
+
+ def test_falls_back_to_direct_cookies(self, tmp_path):
+ """Opera-style layout: Cookies directly under the base dir."""
+ direct = tmp_path / "Cookies"
+ direct.touch()
+ assert _find_chromium_cookies_db(tmp_path) == direct
+
+ def test_falls_back_to_numbered_profile(self, tmp_path):
+ prof = tmp_path / "Profile 2"
+ prof.mkdir()
+ db = prof / "Cookies"
+ db.touch()
+ assert _find_chromium_cookies_db(tmp_path) == db
+
+ def test_returns_none_when_missing(self, tmp_path):
+ assert _find_chromium_cookies_db(tmp_path) is None
+
+ def test_prefers_network_cookies_over_flat(self, tmp_path):
+ """Modern Chromium (>=96) stores under Default/Network/Cookies."""
+ (tmp_path / "Default" / "Network").mkdir(parents=True)
+ net = tmp_path / "Default" / "Network" / "Cookies"
+ net.touch()
+ (tmp_path / "Default" / "Cookies").touch() # legacy flat also present
+ assert _find_chromium_cookies_db(tmp_path) == net
+
+ def test_network_cookies_in_numbered_profile(self, tmp_path):
+ (tmp_path / "Profile 1" / "Network").mkdir(parents=True)
+ net = tmp_path / "Profile 1" / "Network" / "Cookies"
+ net.touch()
+ assert _find_chromium_cookies_db(tmp_path) == net
+
+
+class TestLazyKeychain:
+ """The Keychain key is fetched only when an encrypted cookie must be decrypted.
+
+ This keeps FROM_BROWSER=auto from prompting for every installed Chromium
+ browser - only the one actually holding the requested cookie prompts.
+ """
+
+ def _edge_at(self, tmp_path, rows, encrypted=False):
+ base = tmp_path / "Edge"
+ (base / "Default").mkdir(parents=True)
+ db = base / "Default" / "Cookies"
+ if encrypted:
+ _make_encrypted_cookies_db(db, rows)
+ else:
+ _make_cookies_db(db, rows)
+ return base
+
+ def test_keychain_not_fetched_for_plain_values(self, tmp_path):
+ base = self._edge_at(tmp_path, [(".x.com", "auth_token", "plain_tok")])
+ with (
+ patch.dict("lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
+ {"edge": (base, "Microsoft Edge Safe Storage")}),
+ patch("lib.chrome_cookies._get_chromium_encryption_key") as key_mock,
+ ):
+ result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token"])
+ assert result == {"auth_token": "plain_tok"}
+ key_mock.assert_not_called() # no decryption needed -> no Keychain prompt
+
+ def test_keychain_not_fetched_when_no_match(self, tmp_path):
+ base = self._edge_at(tmp_path, [(".other.com", "auth_token", "x")])
+ with (
+ patch.dict("lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
+ {"edge": (base, "Microsoft Edge Safe Storage")}),
+ patch("lib.chrome_cookies._get_chromium_encryption_key") as key_mock,
+ ):
+ result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token"])
+ assert result is None
+ key_mock.assert_not_called() # cookie absent -> no Keychain prompt
+
+ def test_keychain_fetched_and_decrypts_v10(self, tmp_path):
+ base = self._edge_at(tmp_path, [(".x.com", "auth_token", b"v10ciphertextbytes")], encrypted=True)
+ with (
+ patch.dict("lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
+ {"edge": (base, "Microsoft Edge Safe Storage")}),
+ patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=b"passphrase") as key_mock,
+ patch("lib.chrome_cookies._decrypt_v10_value", return_value="decrypted_tok") as dec_mock,
+ ):
+ result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token"])
+ assert result == {"auth_token": "decrypted_tok"}
+ key_mock.assert_called_once_with("Microsoft Edge Safe Storage")
+ assert dec_mock.called
diff --git a/tests/test_cookie_extract.py b/tests/test_cookie_extract.py
index cc694bf1..30590851 100644
--- a/tests/test_cookie_extract.py
+++ b/tests/test_cookie_extract.py
@@ -331,19 +331,22 @@ class TestExtractCookiesAuto:
"""Tests for extract_cookies with browser='auto'."""
def test_auto_macos_tries_chrome_then_firefox(self, mock_firefox_env):
- """On macOS, auto tries Chrome first, falls back to Firefox if Chrome fails."""
+ """On macOS, auto tries the Chromium family first, falls back to Firefox."""
profiles_dir = mock_firefox_env()
+ # Mock every Chromium-family extractor to None so the test is hermetic
+ # regardless of which browsers are actually installed/logged-in on the
+ # machine running it (auto tries these before Firefox).
with (
patch("lib.cookie_extract.platform.system", return_value="Darwin"),
- patch(
- "lib.cookie_extract.extract_chrome_cookies",
- return_value=None,
- ),
- patch(
- "lib.cookie_extract.extract_safari_cookies",
- return_value=None,
- ),
+ patch("lib.cookie_extract.extract_chrome_cookies", return_value=None),
+ patch("lib.cookie_extract.extract_brave_cookies", return_value=None),
+ patch("lib.cookie_extract.extract_edge_cookies", return_value=None),
+ patch("lib.cookie_extract.extract_vivaldi_cookies", return_value=None),
+ patch("lib.cookie_extract.extract_opera_cookies", return_value=None),
+ patch("lib.cookie_extract.extract_arc_cookies", return_value=None),
+ patch("lib.cookie_extract.extract_chromium_cookies", return_value=None),
+ patch("lib.cookie_extract.extract_safari_cookies", return_value=None),
patch(
"lib.cookie_extract._get_firefox_profiles_dir",
return_value=profiles_dir,
@@ -351,7 +354,7 @@ class TestExtractCookiesAuto:
):
result = extract_cookies("auto", ".x.com", ["auth_token", "ct0"])
- # Chrome and Safari return None, Firefox succeeds
+ # All Chromium browsers and Safari return None, Firefox succeeds
assert result is not None
assert result["auth_token"] == "tok_abc123"
assert result["ct0"] == "ct0_xyz789"