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: gate browser-cookie reads by command policy (#670)
Trevin Chowc8ab309f4532
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex bb5887b9..b6ec8a41 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -44,6 +44,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--save-dir <path>` - one-off output location. **Flag wins over env var.** If neither flag nor env var is set, the engine does not write a file (DB persistence is independent — see `LAST30DAYS_STORE` below).- `--output <file>` - write the rendered output to an exact file path, using the format selected by `--emit`.- `--save-suffix <name>` - distinguish runs of the same topic (e.g. per client: `--save-suffix=acme`).+- `--no-browser-cookies` - hard-disable browser-cookie extraction for this run, even when `FROM_BROWSER` is configured. MCP and folder-mode hosts use this for safe defaults.The footer line `📎 Raw results saved to ${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}/<slug>-raw.md` is the canonical pointer; if it shows backslashes on Windows update past v3.1.1.@@ -58,7 +59,7 @@ On the very first `/last30days` run (no `~/.config/last30days/.env`, or `SETUP_CBoth share the same consent points:-1. **Browser cookies** - the model asks before reading anything. On yes it extracts Firefox/Safari cookies (never Chrome, to avoid a macOS Keychain prompt) to unlock X/Twitter and other logged-in sources, and installs yt-dlp + the keyless Digg CLI. On no it runs setup with `FROM_BROWSER=off` (skips all cookie reads, still installs the tools).+1. **Browser cookies** - the model asks before reading anything. On yes it runs `setup --allow-browser-cookies`, which extracts Firefox/Safari cookies (never Chrome unless `FROM_BROWSER=auto` or a named Chromium browser is explicitly configured) to unlock X/Twitter and other logged-in sources, and installs yt-dlp + the keyless Digg CLI. On no it runs setup without `--allow-browser-cookies` (or with `FROM_BROWSER=off`), which skips all cookie reads and still installs the tools.2. **Full Disk Access (macOS)** - if a cookie read is permission-denied, the model surfaces the System Settings > Privacy & Security > Full Disk Access fix and offers one retry.3. **ScrapeCreators GitHub signup** - offered on every first run (10,000 free calls). On consent it runs `setup --github`, which opens a browser for GitHub device-auth (or registers instantly via the `gh` CLI when installed) and, on success, **persists `SCRAPECREATORS_API_KEY` automatically** (0o600, masked in output) so TikTok, Instagram, X, YouTube comments, and the SC Reddit/YouTube backups activate on the next run. Decline anytime; you can run it later by asking to set up ScrapeCreators. (Threads and Pinterest are not surfaced in onboarding but remain available via `INCLUDE_SOURCES`.)@@ -129,10 +130,11 @@ CT0=<your-ct0-token># OR Xquik key-based X search# XQUIK_API_KEY=<your-xquik-key># 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.+# Unset = no browser-cookie reads. FROM_BROWSER=auto tries Firefox/Safari and+# 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@@ -142,7 +144,7 @@ BSKY_APP_PASSWORD=<your-app-password>After editing: `chmod 600 ~/.config/last30days/.env` (or `chmod 600 .claude/last30days.env` if using the project-scoped variant).-**Troubleshooting:** if a source you expected to see isn't appearing in results, run `python3 scripts/last30days.py --diagnose`. It prints a per-source availability report (which keys were detected, which CLIs are installed, which backends are reachable) without running a full search.+**Troubleshooting:** if a source you expected to see isn't appearing in results, run `python3 scripts/last30days.py --diagnose`. It prints a safe preflight report for source availability, config source, browser-cookie plan, external command availability, and write destinations without reading browser cookies or running live provider probes.### Perplexity source modesdiff --git a/mcp/internal/tools/research.go b/mcp/internal/tools/research.goindex 150ca80e..42ecdb51 100644--- a/mcp/internal/tools/research.go+++ b/mcp/internal/tools/research.go@@ -74,10 +74,7 @@ func makeResearchHandler(cfg Config) server.ToolHandlerFunc {)), nil}- runArgs := []string{topic, "--emit=" + emit}- if save {- runArgs = append(runArgs, "--save")- }+ runArgs := researchRunArgs(topic, emit, save)res, runErr := engine.Run(ctx, engine.RunOptions{CacheDir: cacheDir,@@ -90,6 +87,14 @@ func makeResearchHandler(cfg Config) server.ToolHandlerFunc {}}+func researchRunArgs(topic, emit string, save bool) []string {+ runArgs := []string{topic, "--emit=" + emit, "--no-browser-cookies"}+ if save {+ runArgs = append(runArgs, "--save")+ }+ return runArgs+}+func requireString(args map[string]any, name string) (string, error) {raw, ok := args[name]if !ok {diff --git a/mcp/internal/tools/research_test.go b/mcp/internal/tools/research_test.goindex 0edb6840..ed06e496 100644--- a/mcp/internal/tools/research_test.go+++ b/mcp/internal/tools/research_test.go@@ -97,6 +97,14 @@ func TestBoolArgument(t *testing.T) {}}+func TestResearchRunArgsIncludesNoBrowserCookies(t *testing.T) {+ args := researchRunArgs("OpenAI", "compact", false)+ want := []string{"OpenAI", "--emit=compact", "--no-browser-cookies"}+ if strings.Join(args, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("args = %#v, want %#v", args, want)+ }+}+func TestResearchHandlerValidationErrorsAreToolErrors(t *testing.T) {// Validation failures are returned as MCP tool errors (not Go errors)// so Claude sees a structured failure with a readable message ratherdiff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 20350c7b..bc14ce4b 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -293,6 +293,8 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--debug", action="store_true", help="Enable HTTP debug logging")parser.add_argument("--mock", action="store_true", help="Use mock retrieval fixtures")parser.add_argument("--diagnose", action="store_true", help="Print provider and source availability")+ parser.add_argument("--no-browser-cookies", action="store_true",+ help="Disable browser-cookie extraction even when FROM_BROWSER is configured")parser.add_argument("--save-dir", help="Optional directory for saving the rendered output")parser.add_argument("--output", help="Optional exact file path for saving the rendered output")parser.add_argument("--synthesis-file", help="Markdown synthesis to embed in --emit=html output")@@ -618,7 +620,7 @@ def _write_last_run(topic: str, report: "schema.Report") -> None:pass-def _propagate_config_to_environ() -> None:+def _propagate_config_to_environ(config: dict[str, object]) -> None:"""Push relevant env keys to os.environ so provider modules can read them.The env.get_config() function reads from a .env file, but providers.py@@ -626,17 +628,30 @@ def _propagate_config_to_environ() -> None:XAI_BASE_URL overrides are silently ignored. This is a no-op forkeys that are already set in process env."""- try:- config = env.get_config()- except Exception:- returnfor key in ("OPENAI_BASE_URL", "XAI_BASE_URL"):val = config.get(key)if val and not os.environ.get(key):os.environ[key] = val-_propagate_config_to_environ()+def _setup_allows_browser_cookies(args: argparse.Namespace, extra_argv: list[str]) -> bool:+ return (+ not args.no_browser_cookies+ and not args.diagnose+ and "--allow-browser-cookies" in extra_argv+ )+++def _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: list[str]) -> env.ConfigLoadPolicy:+ if args.no_browser_cookies:+ browser_mode = "off"+ elif args.diagnose:+ browser_mode = "plan_only"+ elif topic.lower() == "setup":+ browser_mode = "read" if _setup_allows_browser_cookies(args, extra_argv) else "off"+ else:+ browser_mode = "read"+ return env.ConfigLoadPolicy(browser_cookies=browser_mode)def main() -> int:@@ -647,7 +662,9 @@ def main() -> int:if args.debug:os.environ["LAST30DAYS_DEBUG"] = "1"- config = env.get_config()+ topic = " ".join(args.topic).strip()+ config = env.get_config(policy=_config_policy_for_args(args, topic, extra_argv))+ _propagate_config_to_environ(config)# Env-var fallback for --save-dir, mirroring the LAST30DAYS_STORE pattern below.# Uses `is None` / `is not None` checks (not truthy `or`) at every layer so that@@ -666,7 +683,6 @@ def main() -> int:os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = config["LAST30DAYS_YOUTUBE_SSH_HOST"]# Handle setup subcommand- topic = " ".join(args.topic).strip()if topic.lower() == "setup":from lib import setup_wizardif "--openclaw" in extra_argv:@@ -690,14 +706,17 @@ def main() -> int:print(json.dumps(results))return 0sys.stderr.write("Running auto-setup...\n")- results = setup_wizard.run_auto_setup(config)+ results = setup_wizard.run_auto_setup(+ config,+ allow_browser_cookies=_setup_allows_browser_cookies(args, extra_argv),+ )# Persist FROM_BROWSER only when every service's cookies came from the# SAME single browser — then we can fast-path future runs to it. If# different services matched different browsers, or none matched, leave- # FROM_BROWSER unset: the safe default (Firefox/Safari) then covers all- # of them with no Keychain prompt. We deliberately do NOT pin "auto"- # here (it would re-probe Chrome and re-trigger the prompt) nor a single- # browser (it would silently skip the service that used the other one).+ # FROM_BROWSER unset so the safe default remains no browser-cookie+ # reads. We deliberately do NOT pin "auto" here (it would re-probe+ # Chrome and re-trigger the prompt) nor a single browser (it would+ # silently skip the service that used the other one).found_browsers = set(results.get("cookies_found", {}).values())from_browser = found_browsers.pop() if len(found_browsers) == 1 else Nonesetup_wizard.write_setup_config(env.CONFIG_FILE, from_browser=from_browser)@@ -706,7 +725,7 @@ def main() -> int:return 0requested_sources = resolve_requested_sources(args.search, config)- diag = pipeline.diagnose(config, requested_sources)+ diag = pipeline.diagnose(config, requested_sources, safe=args.diagnose)if args.diagnose:print(json.dumps(diag, indent=2, sort_keys=True))diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex ab59f351..c0525106 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -77,6 +77,20 @@ class OpenAIAuth:codex_auth_file: str+BrowserCookieMode = Literal["off", "read", "plan_only"]+++@dataclass(frozen=True)+class ConfigLoadPolicy:+ """Local-read gates for configuration loading.++ Bare library calls use the safe default: no browser-cookie extraction. CLI+ entry points can opt into narrower behavior after parsing command intent.+ """++ browser_cookies: BrowserCookieMode = "off"++def _check_file_permissions(path: Path) -> None:"""Warn to stderr if a secrets file has overly permissive permissions."""if os.name == "nt":@@ -328,7 +342,7 @@ def _find_project_env() -> Path | None:return None-def get_config() -> dict[str, Any]:+def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:"""Load configuration from multiple sources.Priority (highest wins):@@ -337,6 +351,7 @@ def get_config() -> dict[str, Any]:3. ~/.config/last30days/.env (global config)4. macOS Keychain items prefixed ``last30days-`` (Darwin only)"""+ policy = policy or ConfigLoadPolicy()# Load from global config filefile_env = load_env_file(CONFIG_FILE) if CONFIG_FILE else {}@@ -477,12 +492,15 @@ def get_config() -> dict[str, Any]:else:config['_CONFIG_SOURCE'] = 'env_only'- # Extract browser credentials if configured- browser_creds = extract_browser_credentials(config)- for key, value in browser_creds.items():- if not config.get(key):- config[key] = value- config[f"_{key}_SOURCE"] = "browser"+ config['_BROWSER_COOKIE_MODE'] = policy.browser_cookies+ config['_BROWSER_COOKIE_BROWSERS'] = cookie_extraction_browsers(config)++ if policy.browser_cookies == "read":+ browser_creds = extract_browser_credentials(config)+ for key, value in browser_creds.items():+ if not config.get(key):+ config[key] = value+ config[f"_{key}_SOURCE"] = "browser"return config@@ -508,16 +526,17 @@ COOKIE_DOMAINS: dict[str, dict[str, Any]] = {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. 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.+ Default (FROM_BROWSER unset): no browser-cookie reads. The Chromium family+ (Chrome, Brave, Edge, Vivaldi, Opera, Arc, Chromium) is available only when+ explicitly selected 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=firefox,safari`` - a comma-separated explicit browser list.- ``FROM_BROWSER=auto`` - also try every Chromium browser (user accepts theKeychain dialog when needed).- ``FROM_BROWSER=off`` - returns [] (extraction disabled).@@ -528,14 +547,20 @@ def cookie_extraction_browsers(config: dict[str, Any]) -> list[str]:"""silent_browsers = ["firefox", "safari"]chromium_browsers = ["chrome", "brave", "edge", "vivaldi", "opera", "arc", "chromium"]+ known_browsers = silent_browsers + chromium_browsersfrom_browser = (config.get("FROM_BROWSER") or "").strip().lower()+ if not from_browser:+ return []if from_browser == "off":return []- if from_browser in silent_browsers or from_browser in chromium_browsers:+ if "," in from_browser:+ browsers = [b.strip() for b in from_browser.split(",") if b.strip()]+ return [b for b in browsers if b in known_browsers]+ if from_browser in known_browsers:return [from_browser]if from_browser == "auto":return silent_browsers + chromium_browsers- return list(silent_browsers)+ return []diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 46a1851e..7a9c8105 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -162,10 +162,15 @@ def available_sources(config: dict[str, Any], requested_sources: list[str] | Nonreturn available-def diagnose(config: dict[str, Any], requested_sources: list[str] | None = None) -> dict[str, Any]:+def diagnose(+ config: dict[str, Any],+ requested_sources: list[str] | None = None,+ *,+ safe: bool = False,+) -> dict[str, Any]:requested_sources = normalize_requested_sources(requested_sources)google_key = _google_key(config)- x_status = env.get_x_source_status(config, probe=True)+ x_status = env.get_x_source_status(config, probe=not safe)native_web_backend = Noneif config.get("BRAVE_API_KEY"):native_web_backend = "brave"@@ -185,6 +190,22 @@ def diagnose(config: dict[str, Any], requested_sources: list[str] | None = None)reasoning_provider_available = any(providers_status[name] for name in ("google", "openai", "xai", "openrouter"))+ external_commands = {+ "yt-dlp": bool(which("yt-dlp")),+ "digg-pp-cli": bool(which("digg-pp-cli")),+ "gh": bool(which("gh")),+ }+ credential_destinations = {+ "global_env": str(env.CONFIG_FILE) if env.CONFIG_FILE else None,+ }+ browser_cookies = {+ "mode": config.get("_BROWSER_COOKIE_MODE", "off"),+ "browsers": list(config.get("_BROWSER_COOKIE_BROWSERS") or []),+ "reads_values": False if safe else config.get("_BROWSER_COOKIE_MODE") == "read",+ }+ local_writes: list[dict[str, str]] = []+ if config.get("LAST30DAYS_MEMORY_DIR"):+ local_writes.append({"kind": "report", "path": str(config.get("LAST30DAYS_MEMORY_DIR"))})return {"providers": providers_status,"local_mode": not reasoning_provider_available,@@ -201,6 +222,12 @@ def diagnose(config: dict[str, Any], requested_sources: list[str] | None = None)"has_scrapecreators": bool(config.get("SCRAPECREATORS_API_KEY")),"has_github": bool(config.get("GITHUB_TOKEN") or which("gh")),"available_sources": available_sources(config, requested_sources),+ "safe": safe,+ "config_source": config.get("_CONFIG_SOURCE"),+ "browser_cookies": browser_cookies,+ "external_commands": external_commands,+ "credential_destinations": credential_destinations,+ "local_writes": local_writes,}diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex c545c829..3fe19b99 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -28,12 +28,12 @@ def is_first_run(config: Dict[str, Any]) -> bool:return not config.get("SETUP_COMPLETE")-def run_auto_setup(config: Dict[str, Any]) -> Dict[str, Any]:+def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = False) -> Dict[str, Any]:"""Perform the auto-setup actions.- - Runs cookie extraction for all registered domains, trying the browsers- from ``env.cookie_extraction_browsers()`` (honors ``FROM_BROWSER``;- defaults to Firefox/Safari, so no Chrome Keychain prompt)+ - Optionally runs cookie extraction for all registered domains, trying the+ browsers from ``env.cookie_extraction_browsers()``. Browser reads are off+ unless ``allow_browser_cookies`` is true.- Checks if yt-dlp is installed- Best-effort install of digg-pp-cli (Printing Press library)@@ -49,31 +49,31 @@ def run_auto_setup(config: Dict[str, Any]) -> Dict[str, Any]:digg_stderr: present when digg_action is install_faileddigg_path: present when digg_action is installed_off_path (binary on disk, not on PATH)"""- from . import cookie_extractfrom .env import COOKIE_DOMAINS, cookie_extraction_browserscookies_found: Dict[str, str] = {}- # Honor FROM_BROWSER and default to the silent browsers (Firefox/Safari).- # Using "auto" here used to probe Chrome unconditionally, triggering a- # "Chrome Safe Storage" Keychain prompt on first run that the steady-state- # path deliberately avoids. Chrome is now opt-in via FROM_BROWSER=chrome|auto.- # An empty list (FROM_BROWSER=off) makes the inner loop a no-op.- browsers = cookie_extraction_browsers(config)-- for source_name, spec in COOKIE_DOMAINS.items():- domain = spec["domain"]- cookie_names = spec["cookies"]-- for browser in browsers:- try:- result = cookie_extract.extract_cookies_with_source(browser, domain, cookie_names)- except 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]:- cookies_found[source_name] = result[1]- break # Found cookies for this service, stop trying browsers+ if allow_browser_cookies:+ from . import cookie_extract++ cookie_config = dict(config)+ if not (cookie_config.get("FROM_BROWSER") or "").strip():+ cookie_config["FROM_BROWSER"] = "firefox,safari"+ browsers = cookie_extraction_browsers(cookie_config)++ for source_name, spec in COOKIE_DOMAINS.items():+ domain = spec["domain"]+ cookie_names = spec["cookies"]++ for browser in browsers:+ try:+ result = cookie_extract.extract_cookies_with_source(browser, domain, cookie_names)+ except 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]:+ cookies_found[source_name] = result[1]+ break # Found cookies for this service, stop trying browsers# Check yt-dlp availability and install via Homebrew if missingytdlp_action: strdiff --git a/tests/test_chromium_browsers.py b/tests/test_chromium_browsers.pyindex 8ebf1cd0..18d212ae 100644--- a/tests/test_chromium_browsers.py+++ b/tests/test_chromium_browsers.py@@ -117,15 +117,14 @@ class TestEnvBrowserSelection: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."""+ def test_default_skips_browser_cookie_reads(self, mock_extract):+ """Default (no FROM_BROWSER) reads no local browser cookies."""mock_extract.return_value = Noneconfig = _base_config()extract_browser_credentials(config)- tried = {call[0][0] for call in mock_extract.call_args_list}- assert tried == {"firefox", "safari"}+ mock_extract.assert_not_called()# ---------------------------------------------------------------------------diff --git a/tests/test_env_cookies.py b/tests/test_env_cookies.pyindex 72dc2df3..d667a09c 100644--- a/tests/test_env_cookies.py+++ b/tests/test_env_cookies.py@@ -5,7 +5,7 @@ from unittest.mock import patchimport pytest-from lib.env import extract_browser_credentials, COOKIE_DOMAINS+from lib.env import ConfigLoadPolicy, extract_browser_credentials, COOKIE_DOMAINSdef _base_config(**overrides):@@ -55,17 +55,13 @@ class TestExtractBrowserCredentials:mock_extract.assert_not_called()@patch("lib.cookie_extract.extract_cookies")- def test_no_from_browser_defaults_to_silent(self, mock_extract):- """Default (no FROM_BROWSER): tries Firefox and Safari only, skips Chrome."""+ def test_no_from_browser_skips_all(self, mock_extract):+ """Default (no FROM_BROWSER): reads no browser cookies."""mock_extract.return_value = Noneconfig = _base_config()result = extract_browser_credentials(config)assert result == {}- # Should try firefox and safari but NOT chrome- browser_args = [call[0][0] for call in mock_extract.call_args_list]- assert "firefox" in browser_args- assert "safari" in browser_args- assert "chrome" not in browser_args+ mock_extract.assert_not_called()@patch("lib.cookie_extract.extract_cookies")def test_from_browser_firefox_only(self, mock_extract):@@ -105,14 +101,14 @@ class TestExtractBrowserCredentials:class TestGetConfigCookieIntegration:- """Integration test: get_config() calls extract_browser_credentials."""+ """Integration tests for policy-gated cookie extraction in get_config()."""@patch("lib.cookie_extract.extract_cookies")@patch("lib.env._find_project_env", return_value=None)@patch("lib.env.load_env_file", return_value={})@patch("lib.env._load_keychain", return_value={})@patch("lib.env.get_openai_auth")- def test_get_config_injects_cookies(+ def test_get_config_default_does_not_extract_cookies(self, mock_openai, mock_keychain, mock_load, mock_proj, mock_extract):from lib.env import get_config, OpenAIAuth@@ -128,5 +124,30 @@ class TestGetConfigCookieIntegration:}with patch.dict(os.environ, env_patch, clear=False):config = get_config()+ assert config["AUTH_TOKEN"] is None+ assert config["CT0"] is None+ mock_extract.assert_not_called()++ @patch("lib.cookie_extract.extract_cookies")+ @patch("lib.env._find_project_env", return_value=None)+ @patch("lib.env.load_env_file", return_value={})+ @patch("lib.env._load_keychain", return_value={})+ @patch("lib.env.get_openai_auth")+ def test_get_config_with_cookie_policy_injects_cookies(+ self, mock_openai, mock_keychain, mock_load, mock_proj, mock_extract+ ):+ from lib.env import get_config, OpenAIAuth+ mock_openai.return_value = OpenAIAuth(+ token=None, source="none", status="missing",+ account_id=None, codex_auth_file="/fake",+ )+ mock_extract.return_value = {"auth_token": "browser_tok", "ct0": "browser_ct0"}+ env_patch = {+ "SETUP_COMPLETE": "true",+ "FROM_BROWSER": "auto",+ "LAST30DAYS_CONFIG_DIR": "",+ }+ with patch.dict(os.environ, env_patch, clear=False):+ config = get_config(policy=ConfigLoadPolicy(browser_cookies="read"))assert config["AUTH_TOKEN"] == "browser_tok"assert config["CT0"] == "browser_ct0"diff --git a/tests/test_security_boundaries.py b/tests/test_security_boundaries.pynew file mode 100644index 00000000..d8c58fc6--- /dev/null+++ b/tests/test_security_boundaries.py@@ -0,0 +1,124 @@+"""Regression tests for agent-host local-read boundaries."""++from __future__ import annotations++import importlib+import io+import json+import os+import sys+from contextlib import redirect_stderr, redirect_stdout+from unittest import mock++import last30days as cli+++def test_importing_cli_does_not_load_config_or_propagate_endpoints(monkeypatch):+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ monkeypatch.delenv("XAI_BASE_URL", raising=False)+ with mock.patch("lib.env.get_config", side_effect=AssertionError("import loaded config")):+ importlib.reload(cli)+ assert os.environ.get("OPENAI_BASE_URL") is None+ assert os.environ.get("XAI_BASE_URL") is None+++def test_diagnose_uses_plan_only_cookie_policy_and_safe_pipeline(monkeypatch):+ seen: dict[str, object] = {}++ def fake_get_config(*, policy):+ seen["policy"] = policy+ return {"_BROWSER_COOKIE_MODE": policy.browser_cookies, "_BROWSER_COOKIE_BROWSERS": ["firefox"]}++ with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \+ mock.patch.object(cli.pipeline, "diagnose", return_value={"ok": True}) as diagnose, \+ mock.patch.object(sys, "argv", ["last30days.py", "--diagnose"]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert seen["policy"].browser_cookies == "plan_only"+ diagnose.assert_called_once_with(+ {"_BROWSER_COOKIE_MODE": "plan_only", "_BROWSER_COOKIE_BROWSERS": ["firefox"]},+ None,+ safe=True,+ )+ assert json.loads(stdout.getvalue()) == {"ok": True}+++def test_setup_without_cookie_flag_disables_browser_cookie_setup(monkeypatch):+ with mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as setup, \+ mock.patch("lib.setup_wizard.write_setup_config", return_value=True), \+ mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \+ mock.patch.object(sys, "argv", ["last30days.py", "setup"]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert setup.call_args.kwargs["allow_browser_cookies"] is False+++def test_setup_cookie_flag_allows_browser_cookie_setup(monkeypatch):+ with mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as setup, \+ mock.patch("lib.setup_wizard.write_setup_config", return_value=True), \+ mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \+ mock.patch.object(sys, "argv", ["last30days.py", "setup", "--allow-browser-cookies"]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert setup.call_args.kwargs["allow_browser_cookies"] is True+++def test_no_browser_cookies_overrides_setup_cookie_flag(monkeypatch):+ seen: dict[str, object] = {}++ def fake_get_config(*, policy):+ seen["policy"] = policy+ return {}++ with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \+ mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as setup, \+ mock.patch("lib.setup_wizard.write_setup_config", return_value=True), \+ mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \+ mock.patch.object(+ sys,+ "argv",+ ["last30days.py", "--no-browser-cookies", "setup", "--allow-browser-cookies"],+ ):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert seen["policy"].browser_cookies == "off"+ assert setup.call_args.kwargs["allow_browser_cookies"] is False+++def test_diagnose_overrides_setup_cookie_flag(monkeypatch):+ seen: dict[str, object] = {}++ def fake_get_config(*, policy):+ seen["policy"] = policy+ return {}++ with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \+ mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as setup, \+ mock.patch("lib.setup_wizard.write_setup_config", return_value=True), \+ mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \+ mock.patch.object(+ sys,+ "argv",+ ["last30days.py", "--diagnose", "setup", "--allow-browser-cookies"],+ ):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ assert cli.main() == 0++ assert seen["policy"].browser_cookies == "plan_only"+ assert setup.call_args.kwargs["allow_browser_cookies"] is Falsediff --git a/tests/test_setup_wizard.py b/tests/test_setup_wizard.pyindex 7b8fa605..fc3f9624 100644--- a/tests/test_setup_wizard.py+++ b/tests/test_setup_wizard.py@@ -50,7 +50,7 @@ class TestRunAutoSetup:mock_which.return_value = "/usr/local/bin/yt-dlp"config = {}- results = setup_wizard.run_auto_setup(config)+ results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True)assert "x" in results["cookies_found"]assert results["cookies_found"]["x"] == "chrome"@@ -69,6 +69,7 @@ class TestRunAutoSetup:results = setup_wizard.run_auto_setup(config)assert results["cookies_found"] == {}+ mock_extract.assert_not_called()assert results["ytdlp_installed"] is Falseassert results["ytdlp_action"] == "no_homebrew"@@ -80,7 +81,7 @@ class TestRunAutoSetup:mock_which.return_value = Noneconfig = {}- results = setup_wizard.run_auto_setup(config)+ results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True)assert results["cookies_found"] == {}@@ -99,7 +100,7 @@ class TestRunAutoSetup:mock_which.return_value = Noneconfig = {}- results = setup_wizard.run_auto_setup(config)+ results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True)assert results["cookies_found"]["x"] == "firefox"assert results["cookies_found"]["truthsocial"] == "firefox"@@ -522,12 +523,11 @@ class TestMaskApiKey:class TestCookieExtractionBrowsers:"""Tests for env.cookie_extraction_browsers() — the shared browser policy."""- def test_default_excludes_chrome(self):- """FROM_BROWSER unset -> Firefox/Safari only, never Chrome (no prompt)."""+ def test_default_disables_extraction(self):+ """FROM_BROWSER unset -> no browser-cookie reads."""from lib import envbrowsers = env.cookie_extraction_browsers({})- assert "chrome" not in browsers- assert browsers == ["firefox", "safari"]+ assert browsers == []def test_off_disables_extraction(self):from lib import env@@ -550,13 +550,12 @@ class TestWizardDoesNotProbeChromeByDefault:def test_default_run_never_requests_chrome(self, _mock_which, mock_extract):setup_wizard.run_auto_setup({})requested_browsers = {call.args[0] for call in mock_extract.call_args_list}- assert "chrome" not in requested_browsers- assert requested_browsers <= {"firefox", "safari"}+ assert requested_browsers == set()@patch("lib.cookie_extract.extract_cookies_with_source", return_value=None)@patch("shutil.which", return_value=None)def test_from_browser_auto_does_request_chrome(self, _mock_which, mock_extract):- setup_wizard.run_auto_setup({"FROM_BROWSER": "auto"})+ setup_wizard.run_auto_setup({"FROM_BROWSER": "auto"}, allow_browser_cookies=True)requested_browsers = {call.args[0] for call in mock_extract.call_args_list}assert "chrome" in requested_browsers