AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(cookies): require complete pairs before accepting (#1163)
Ilia Alshanetsky5c408623bc73
diff --git a/changelog.d/+cookie-partial-pairs.fixed.md b/changelog.d/+cookie-partial-pairs.fixed.mdnew file mode 100644index 00000000..a5806025--- /dev/null+++ b/changelog.d/+cookie-partial-pairs.fixed.md@@ -0,0 +1 @@+Browser cookie detection now requires the complete login pair before accepting a source, so a logged-out session can no longer shadow the browser where you are actually logged in.diff --git a/skills/last30days/scripts/lib/cookie_extract.py b/skills/last30days/scripts/lib/cookie_extract.pyindex b2348a33..b441f958 100644--- a/skills/last30days/scripts/lib/cookie_extract.py+++ b/skills/last30days/scripts/lib/cookie_extract.py@@ -22,6 +22,23 @@ from typing import Dict, List, Optionallogger = logging.getLogger(__name__)+def has_complete_pair(result: Optional[Dict[str, str]], cookie_names) -> bool:+ """Return True when ``result`` holds every requested cookie with a value.++ Shared by the Firefox profile scan, ``env.extract_browser_credentials``,+ and the setup wizard so a partial pair (e.g. a lone ``ct0`` from a+ logged-out session) never shadows a complete one. Empty values do not+ count: ``{"auth_token": "", "ct0": ""}`` is incomplete. ``cookie_names``+ is the spec's cookie list (a spec dict with a ``"cookies"`` key also+ works).+ """+ if not result:+ return False+ if isinstance(cookie_names, dict):+ cookie_names = cookie_names.get("cookies", [])+ return all(result.get(name) for name in cookie_names)++def _lock_temp_cookie_copy(path: str) -> None:"""Restrict copied cookie DB temp files to the current user on POSIX."""if os.name == "nt":@@ -228,13 +245,18 @@ def _try_firefox_dir(profiles_dir: Path, domain: str, cookie_names: List[str]) -Tries the default profile first, then falls back to scanning allprofiles for matching cookies. This handles multi-profile setupswhere the user is logged into x.com on a non-default profile.+ A complete match (all ``cookie_names``) always wins: a partial+ default-profile result is kept only as a fallback."""default_profile = _find_default_profile(profiles_dir)profiles_tried = 0+ fallback: Optional[Dict[str, str]] = Noneif default_profile is not None:result = _query_cookies_db(default_profile / "cookies.sqlite", domain, cookie_names)if result is not None:- return result+ if has_complete_pair(result, cookie_names):+ return result+ fallback = resultprofiles_tried = 1# Fallback: scan every profile directory for matching cookiestry:@@ -247,10 +269,15 @@ def _try_firefox_dir(profiles_dir: Path, domain: str, cookie_names: List[str]) -if db.is_file():result = _query_cookies_db(db, domain, cookie_names)if result is not None:- return result+ if has_complete_pair(result, cookie_names):+ return result+ if fallback is None:+ fallback = resultprofiles_tried += 1except OSError:pass+ if fallback is not None:+ return fallbacklogger.debug("No matching cookies found in %d Firefox profile(s)", profiles_tried)return Nonediff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex 11293572..924dabde 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -1098,16 +1098,28 @@ def extract_browser_credentials(config: dict[str, Any]) -> dict[str, str]:for _service, spec in COOKIE_DOMAINS.items():if all(config.get(env_key) for env_key in spec["mapping"].values()):continue+ # Cookies from different browsers can belong to different sessions,+ # so values are never combined across browsers: a complete set from+ # one browser wins, else the first browser's partial set is kept.+ chosen: dict[str, str] | None = None+ fallback: dict[str, str] | None = Nonefor browser in browsers:try:cookies = cookie_extract.extract_cookies(browser, spec["domain"], spec["cookies"])except Exception:continue- if cookies:- for cookie_name, env_key in spec["mapping"].items():- if cookie_name in cookies and not config.get(env_key):- extracted[env_key] = cookies[cookie_name]- break # Found cookies for this service, stop trying browsers+ if not cookies:+ continue+ if cookie_extract.has_complete_pair(cookies, spec["cookies"]):+ chosen = cookies+ break+ if fallback is None:+ fallback = cookies+ if chosen is None:+ chosen = fallback or {}+ for cookie_name, env_key in spec["mapping"].items():+ if chosen.get(cookie_name) and not config.get(env_key):+ extracted[env_key] = chosen[cookie_name]return extracteddiff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex 7ea0b4a1..69758d65 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -130,9 +130,9 @@ def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = Falsexcept Exception as exc:logger.debug("Cookie extraction failed for %s via %s: %s", source_name, browser, exc)continue- if result is not None and result[0]:+ if result is not None and cookie_extract.has_complete_pair(result[0], cookie_names):cookies_found[source_name] = result[1]- break # Found cookies for this service, stop trying browsers+ break # Complete pair found for this service, stop trying browsers# Check yt-dlp availability and install via Homebrew if missing. Windows# has no Homebrew, and its working install path is `pip install yt-dlp`@@ -935,6 +935,21 @@ def _existing_scrapecreators_key() -> Optional[str]:return None+def _clamp_device_interval(interval: Any) -> int:+ """Clamp a server-provided device-flow poll interval to [1, 30] seconds.++ The ``interval`` comes from the server (device/code response or the+ persisted poll handle), so 0 would hot-loop ``time.sleep``, a negative+ would crash it, a huge value would sail past the poll timeout, and a+ non-numeric value would raise. Defaults to 5 on missing/garbled input.+ """+ try:+ value = int(interval or 5)+ except (TypeError, ValueError):+ return 5+ return min(max(value, 1), 30)++def run_device_auth() -> Optional[Tuple[str, str, str, int]]:"""Start the device authorization flow.@@ -957,7 +972,7 @@ def run_device_auth() -> Optional[Tuple[str, str, str, int]]:device_code = data.get("device_code")user_code = data.get("user_code")verification_uri = data.get("verification_uri")- interval = data.get("interval", 5)+ interval = _clamp_device_interval(data.get("interval", 5))if not device_code or not user_code:# Log only the response's key names, never its values — a returning@@ -991,6 +1006,7 @@ def poll_device_auth("""import sys+ interval = _clamp_device_interval(interval)started_at = time.time()deadline = started_at + timeoutlast_reminder = started_at@@ -1323,7 +1339,7 @@ def run_github_poll(timeout: int = 300, *, _handle: Optional[Dict[str, Any]] = N}device_code = data["device_code"]- interval = int(data.get("interval", 5))+ interval = _clamp_device_interval(data.get("interval", 5))user_code = data.get("user_code", "")# Read the real clipboard state so the polling reminder never falsely claims# the code is on the clipboard (non-macOS, or a failed pbcopy). Missing keydiff --git a/tests/test_cookie_extract.py b/tests/test_cookie_extract.pyindex e6b8ce2a..43b26107 100644--- a/tests/test_cookie_extract.py+++ b/tests/test_cookie_extract.py@@ -14,6 +14,7 @@ from lib import cookie_extractfrom lib.cookie_extract import (extract_cookies,extract_firefox_cookies,+ has_complete_pair,_query_cookies_db,_find_default_profile,_get_firefox_profiles_dir,@@ -223,6 +224,74 @@ class TestExtractFirefoxCookies:assert result is None+ def test_default_partial_yields_to_complete_non_default(self, mock_firefox_env):+ """Default profile holds a lone ct0 (logged-out); the logged-in+ non-default profile's complete pair wins."""+ profiles_dir = mock_firefox_env(+ profiles={+ "aaa111.default": [+ (".x.com", "ct0", "partial_ct0"),+ ],+ "bbb222.release": [+ (".x.com", "auth_token", "tok_complete"),+ (".x.com", "ct0", "ct0_complete"),+ ],+ },+ profiles_ini=textwrap.dedent("""\+ [General]+ StartWithLastProfile=1++ [Profile0]+ Name=default+ IsRelative=1+ Path=aaa111.default+ Default=1++ [Profile1]+ Name=release+ IsRelative=1+ Path=bbb222.release+ """),+ )++ with patch(+ "lib.cookie_extract._get_firefox_profiles_dir",+ return_value=profiles_dir,+ ):+ result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])++ assert result is not None+ assert result["auth_token"] == "tok_complete"+ assert result["ct0"] == "ct0_complete"++ def test_partial_fallback_when_no_complete_profile(self, mock_firefox_env):+ """With no complete profile anywhere, the first partial is kept."""+ profiles_dir = mock_firefox_env(+ profiles={+ "aaa111.default": [+ (".x.com", "ct0", "partial_ct0"),+ ],+ },+ profiles_ini=textwrap.dedent("""\+ [General]+ StartWithLastProfile=1++ [Profile0]+ Name=default+ IsRelative=1+ Path=aaa111.default+ Default=1+ """),+ )++ with patch(+ "lib.cookie_extract._get_firefox_profiles_dir",+ return_value=profiles_dir,+ ):+ result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])++ assert result == {"ct0": "partial_ct0"}+def test_cookies_sqlite_empty(self, mock_firefox_env):"""Returns None when cookies.sqlite has no rows."""profiles_dir = mock_firefox_env(@@ -476,3 +545,34 @@ class TestExtractCookiesAuto:):result = extract_cookies("safari", ".x.com", ["auth_token"])assert result == {"auth_token": "safari_tok"}+++class TestHasCompletePair:+ """Tests for the shared has_complete_pair() helper."""++ def test_none_is_incomplete(self):+ assert has_complete_pair(None, ["auth_token", "ct0"]) is False++ def test_empty_is_incomplete(self):+ assert has_complete_pair({}, ["auth_token", "ct0"]) is False++ def test_partial_pair_is_incomplete(self):+ assert has_complete_pair({"ct0": "x"}, ["auth_token", "ct0"]) is False++ def test_empty_valued_pair_is_incomplete(self):+ assert has_complete_pair({"auth_token": "", "ct0": ""}, ["auth_token", "ct0"]) is False+ assert has_complete_pair({"auth_token": "a", "ct0": ""}, ["auth_token", "ct0"]) is False++ def test_complete_pair(self):+ assert has_complete_pair(+ {"auth_token": "a", "ct0": "c"}, ["auth_token", "ct0"]+ ) is True++ def test_single_cookie_service(self):+ assert has_complete_pair({"_session_id": "s"}, ["_session_id"]) is True++ def test_extra_keys_still_complete(self):+ assert has_complete_pair(+ {"auth_token": "a", "ct0": "c", "other": "o"},+ ["auth_token", "ct0"],+ ) is Truediff --git a/tests/test_env_cookies.py b/tests/test_env_cookies.pyindex 365c4fb0..a255e777 100644--- a/tests/test_env_cookies.py+++ b/tests/test_env_cookies.py@@ -99,6 +99,58 @@ class TestExtractBrowserCredentials:assert "AUTH_TOKEN" not in resultassert result["CT0"] == "cookie_ct0"+ @patch("lib.cookie_extract.extract_cookies")+ def test_partial_pair_does_not_shadow_complete_browser(self, mock_extract):+ """A partial X pair (lone ct0 from a logged-out session) must not+ stop the scan: the complete pair from a later browser wins."""+ def side_effect(browser, domain, cookie_names):+ if domain == ".x.com":+ if browser == "firefox":+ return {"ct0": "logged_out_ct0"}+ if browser == "safari":+ return {"auth_token": "tok", "ct0": "ct0"}+ if domain == ".truthsocial.com":+ return {"_session_id": "sess"}+ return None+ mock_extract.side_effect = side_effect+ config = _base_config(FROM_BROWSER="firefox,safari")+ result = extract_browser_credentials(config)+ assert result["AUTH_TOKEN"] == "tok"+ assert result["CT0"] == "ct0"++ @patch("lib.cookie_extract.extract_cookies")+ def test_complementary_partials_never_merge_across_browsers(self, mock_extract):+ """auth_token from one browser and ct0 from another can belong to+ different X sessions: only the first browser's partial is kept."""+ def side_effect(browser, domain, cookie_names):+ if domain == ".x.com":+ if browser == "firefox":+ return {"auth_token": "tok"}+ if browser == "safari":+ return {"ct0": "other_session_ct0"}+ return None+ mock_extract.side_effect = side_effect+ config = _base_config(FROM_BROWSER="firefox,safari")+ result = extract_browser_credentials(config)+ assert result["AUTH_TOKEN"] == "tok"+ assert "CT0" not in result++ @patch("lib.cookie_extract.extract_cookies")+ def test_partial_then_complete_uses_only_complete_browser(self, mock_extract):+ """A complete pair from a later browser replaces an earlier partial+ wholesale; no value from the partial browser survives."""+ def side_effect(browser, domain, cookie_names):+ if domain == ".x.com":+ if browser == "firefox":+ return {"auth_token": "stale_tok"}+ if browser == "safari":+ return {"auth_token": "tok", "ct0": "ct0"}+ return None+ mock_extract.side_effect = side_effect+ config = _base_config(FROM_BROWSER="firefox,safari")+ result = extract_browser_credentials(config)+ assert result == {"AUTH_TOKEN": "tok", "CT0": "ct0"}+class TestGetConfigCookieIntegration:"""Integration tests for policy-gated cookie extraction in get_config()."""diff --git a/tests/test_setup_wizard.py b/tests/test_setup_wizard.pyindex 4fb285d1..99d107f2 100644--- a/tests/test_setup_wizard.py+++ b/tests/test_setup_wizard.py@@ -1,5 +1,6 @@"""Tests for the first-run setup wizard module."""+import jsonimport osimport subprocessimport tempfile@@ -214,6 +215,38 @@ class TestRunAutoSetup:assert results["browser_cookie_scan_attempted"] is Trueassert "cookie_note" not in results+ @patch("lib.cookie_extract.extract_cookies_with_source")+ @patch("shutil.which")+ def test_partial_pair_not_recorded_as_found(self, mock_which, mock_extract):+ """A partial X pair (lone ct0) is not a found source."""+ mock_extract.return_value = ({"ct0": "lone_ct0"}, "chrome")+ mock_which.return_value = None++ results = setup_wizard.run_auto_setup({}, allow_browser_cookies=True)++ assert results["cookies_found"] == {}+ assert results["browser_cookie_scan_attempted"] is True++ @patch("lib.cookie_extract.extract_cookies_with_source")+ @patch("shutil.which")+ def test_partial_then_complete_records_complete_source(self, mock_which, mock_extract):+ """The scan keeps looking past a partial pair and records the+ browser that yielded the complete one."""+ def side_effect(browser, domain, cookie_names):+ if domain == ".x.com":+ if browser == "chrome":+ return ({"ct0": "lone_ct0"}, "chrome")+ if browser == "firefox":+ return ({"auth_token": "abc", "ct0": "xyz"}, "firefox")+ return None+ mock_extract.side_effect = side_effect+ mock_which.return_value = None++ config = {"FROM_BROWSER": "chrome,firefox"}+ results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True)++ assert results["cookies_found"]["x"] == "firefox"+class TestYtdlpAutoInstall:"""Tests for yt-dlp auto-install via Homebrew in run_auto_setup()."""@@ -993,3 +1026,90 @@ class TestBrightDataSetupSurface:def test_absent_offers_the_install_command_without_running_it(self):text = self._text({"action": "not_installed", "engine_active": False})assert "npm i -g @brightdata/cli" in text+++def _device_code_response(interval):+ """Build a mocked urlopen context manager yielding a device/code payload."""+ resp_data = {+ "device_code": "dc-123",+ "user_code": "ABCD-1234",+ "verification_uri": "https://github.com/login/device",+ "interval": interval,+ }+ mock_resp = MagicMock()+ mock_resp.read.return_value = json.dumps(resp_data).encode()+ mock_resp.__enter__ = lambda s: s+ mock_resp.__exit__ = MagicMock(return_value=False)+ return mock_resp+++class TestDeviceIntervalClamp:+ """Server-controlled poll intervals are clamped to [1, 30] before use."""++ @pytest.mark.parametrize("server,expected", [+ (0, 5),+ (-5, 1),+ (3600, 30),+ ("abc", 5),+ (None, 5),+ ("7", 7),+ ])+ @patch("lib.setup_wizard.urlopen")+ def test_run_device_auth_clamps_server_interval(+ self, mock_urlopen, server, expected+ ):+ """run_device_auth never returns 0/negative/huge/non-numeric intervals."""+ mock_urlopen.return_value = _device_code_response(server)++ result = setup_wizard.run_device_auth()++ assert result is not None+ assert result[3] == expected++ @pytest.mark.parametrize("stored,expected", [+ (0, 5),+ (-10, 1),+ (9999, 30),+ ("junk", 5),+ ])+ @patch("lib.setup_wizard._device_handle_path")+ @patch("lib.setup_wizard.fetch_api_key")+ @patch("lib.setup_wizard.poll_device_auth")+ def test_run_github_poll_clamps_stored_interval(+ self, mock_poll, mock_fetch, mock_handle, tmp_path, stored, expected+ ):+ """A poisoned persisted handle (or server value) cannot hot-loop,+ crash, or sail past the timeout via time.sleep(interval)."""+ handle = tmp_path / "h.json"+ handle.write_text(json.dumps(+ {"device_code": "dc", "interval": stored, "user_code": "ABCD-1234"}+ ))+ mock_handle.return_value = handle+ mock_poll.return_value = "tok"+ mock_fetch.return_value = {"ok": True, "api_key": "sc_k"}++ result = setup_wizard.run_github_poll(timeout=1)++ assert result["status"] == "success"+ assert mock_poll.call_args[0][1] == expected++ @pytest.mark.parametrize("raw,expected", [+ (0, 5),+ (-5, 1),+ (3600, 30),+ ])+ @patch("lib.setup_wizard.urlopen")+ @patch("lib.setup_wizard.time.sleep")+ def test_poll_device_auth_clamps_own_interval(+ self, mock_sleep, mock_urlopen, raw, expected+ ):+ """poll_device_auth validates its own interval even when a caller+ passes 0/negative/huge straight through."""+ mock_resp = MagicMock()+ mock_resp.read.return_value = json.dumps({"access_token": "tok"}).encode()+ mock_resp.__enter__ = lambda s: s+ mock_resp.__exit__ = MagicMock(return_value=False)+ mock_urlopen.return_value = mock_resp++ assert setup_wizard.poll_device_auth("dc", raw, timeout=30) == "tok"+ mock_sleep.assert_called_once_with(expected)