Skip to content

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

fix: require durable consent for browser cookie discovery (#1208)

Ilia Alshanetskyd3697d145053
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 076a1d1a..540ce639 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -88,7 +88,7 @@ On the very first `/last30days` run (no `~/.config/last30days/.env`, or `SETUP_C
The Modal and Non-Modal flows share the same consent points:
-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.
+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. The engine saves the decision as `BROWSER_CONSENT=true` or `false`; refusal blocks native browser and CDP reads on later runs, even if an older `FROM_BROWSER` selection remains. A later consented setup can replace the refusal. An explicit `FROM_BROWSER=off` remains a separate denial until you change it.
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, empty-path Reddit search backup, and the YouTube transcript fallback activate on the next run. Decline anytime; you can run it later by asking to set up ScrapeCreators. The Step 5 opt-in has two tiers, both comment-enabled: **Recommended** (TikTok + Instagram posts AND top comments, plus YouTube comments — `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments`) and **Everything**, which also adds Threads + Pinterest. Comments are on by default; Threads and Pinterest are the only opt-in extras.
@@ -196,13 +196,15 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \
1. an explicit env `AUTH_TOKEN`+`CT0` (never overwritten);
2. the [`agentcookie`](https://github.com/) sidecar CLI — `agentcookie cookies --domain .x.com --json` — a soft dependency (absent = skipped; `AGENTCOOKIE=off` disables it) that delivers cookies on Linux, where the on-disk Chrome store can't be decrypted here;
-3. a live signed-in Chrome/Chromium session over the DevTools Protocol (`Network.getAllCookies`);
+3. a live signed-in Chrome/Chromium session over the DevTools Protocol (`Network.getAllCookies`), after explicit browser-cookie consent;
4. the mainline browser extract, when `FROM_BROWSER` already lists a browser (on a Mac mini with a browser opted in, this native read runs *before* the CDP read).
A host counts as an "extra host" when ANY of these hold: `AGENTCOOKIE=on` (explicit opt-in, any OS); the platform is Linux; a Darwin **Mac mini** (`sysctl -n hw.model` prefix `Macmini`); or a Darwin **agentcookie sink** role. The host is never inferred from the home directory, PATH, or Hermes/OpenClaw env — only those signals. A plain MacBook does no agentcookie spawn and opens no CDP socket unless `AGENTCOOKIE=on`.
CDP endpoint resolution (extra hosts only, no port scan): `BROWSER_CDP_URL` if set, else port `18800` when it answers as Chrome, else `9222` + the X display number. Port `18800` is the last30days extras **NUX convention** — the agent launches a throwaway login Chrome with `SAND_CHROME_REMOTE_DEBUG_PORT=18800` (see SKILL.md's "X on Linux / Mac mini"), so it is not confused with a daily Chrome profile on `9222`+display (box-chrome's own built-in default). `18800` is tried first but falls through when it yields no complete pair, so a logged-out Chrome there never shadows a logged-in profile; pin `BROWSER_CDP_URL` if a stale session answers there. A Node `--inspect` endpoint is rejected; a Chrome page target is required.
+CDP reads require `BROWSER_CONSENT=true`, or an explicit Chromium browser / `auto` selection in `FROM_BROWSER` when no consent marker exists. A running debugging browser or `BROWSER_CDP_URL` alone grants no access. `BROWSER_CONSENT=false` and `FROM_BROWSER=off` each block CDP before endpoint discovery. The `agentcookie` sidecar remains separately controlled by `AGENTCOOKIE`.
+
**Example `.env` skeleton** (placeholders only - replace with your own values):
```bash
@@ -526,7 +528,8 @@ Every live run writes its JSON result to `~/.config/last30days/doctor-cache.json
| `LAST30DAYS_X_HOST_LANE` | `1` declares that the hosting model's X connector is in this session, so `--diagnose` and planning list `x` as available and the run expects `--x-posts`. Read from the process environment only: a `.env` line is ignored (doctor says so), so a removed connector never leaves a stale declaration. A run with the signal but no `--x-posts` records X as `error` ("connector result not passed"). |
| `LAST30DAYS_X_BACKEND` | Pins the X backend (`bird` / `xai` / `xurl` / `xquik` / `grok` / `xapi`); doctor renders the pin and predicts "will use" accordingly. The unpinned auto chain is bird → xai → xurl → xquik (grok and xapi are opt-in only). Pin `grok` to enable it; a leftover `~/.grok/auth.json` is never auto-selected. Pin `xapi` to use `X_BEARER_TOKEN` on an ordinary host. On a Grok Bot host the unpinned chain is the official chain (xapi → xai → xurl) and this pin is the only way to select a backend outside it; the pin keeps its exclusive, no-failover meaning there, and doctor names the pinned backend. |
| `AGENTCOOKIE` | `on` opts any host (incl. a MacBook) into the extra bird cookie lookups (agentcookie sidecar + live Chrome CDP); `off` disables the agentcookie sidecar reader. Unset uses host detection (Linux / Mac mini / Darwin sink get the extras). See "Extra bird cookie lookups" above. |
-| `BROWSER_CDP_URL` | Explicit Chrome DevTools endpoint (e.g. `http://127.0.0.1:18800`) for the extra-host CDP cookie lookup. Preferred over the `18800` / `9222`+`$DISPLAY` defaults. Extra hosts only. |
+| `BROWSER_CONSENT` | Browser-cookie decision saved by setup: `true` permits consented browser discovery; `false` blocks native browser and CDP reads across later runs. Native extraction still requires `FROM_BROWSER`; CDP permits a prior explicit Chromium / `auto` selection when this marker is absent. `FROM_BROWSER=off` always blocks both readers. |
+| `BROWSER_CDP_URL` | Explicit Chrome DevTools endpoint (e.g. `http://127.0.0.1:18800`) for the extra-host CDP cookie lookup. Preferred over the `18800` / `9222`+`$DISPLAY` defaults. Extra hosts only; setting an endpoint does not grant browser-cookie consent. |
| `LAST30DAYS_REDDIT_BACKEND` | `scrapecreators` makes ScrapeCreators the primary Reddit backend; doctor renders Reddit's conditional routing with the pin applied. |
| `LAST30DAYS_REDDIT_SC_MIN_ITEMS` | Integer thinness floor for ScrapeCreators Reddit **search** backfill. Default `5`: backfill when the free path returns fewer than 5 items, spending ScrapeCreators credits. Set another positive count to move the floor, or `0` to backfill only when the free path returns nothing. Unset or blank means `5`; a malformed value behaves like `0` (spends nothing extra). A run makes at most one ScrapeCreators Reddit backfill per distinct query, date window, and subreddit set, and each backfill is several API calls (searches plus comment fetches, roughly 10 at default depth). A failed backfill after free items only adds a detail note. Merged results dedupe by post id. Requires `SCRAPECREATORS_API_KEY`. Ignored when `LAST30DAYS_REDDIT_BACKEND=scrapecreators` (SC is already primary). |
diff --git a/changelog.d/+cr-003-browser-cookie-consent.security.md b/changelog.d/+cr-003-browser-cookie-consent.security.md
new file mode 100644
index 00000000..765a5ecf
--- /dev/null
+++ b/changelog.d/+cr-003-browser-cookie-consent.security.md
@@ -0,0 +1 @@
+Require explicit consent before reading browser cookies through Chrome debugging sessions. Setup now saves acceptance or refusal, and a saved refusal blocks native browser and CDP reads on subsequent runs without storing cookie values.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index a4d6ae36..00884004 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -581,15 +581,15 @@ Options:
**Step 3 - Run setup based on the choice.**
-**If the user picks Skip for now:** write `SETUP_COMPLETE=true` to `~/.config/last30days/.env` (append-only; run `mkdir -p ~/.config/last30days && touch ~/.config/last30days/.env` first if the file does not exist) so the wizard does NOT re-fire on every subsequent run. Do not run any `setup` command - the always-on sources (Reddit, HN, Polymarket, GitHub, Web) need no setup. If the invocation already includes a topic, research it immediately, then resume Step 4 (and Step 5 if a key is saved) in the same run after the findings; Step 6 stays skipped because the topic was supplied. Otherwise continue to Step 6.
+**If the user picks Skip for now:** write `SETUP_COMPLETE=true` and `BROWSER_CONSENT=false` to `~/.config/last30days/.env` (preserve other keys, replace an existing consent marker, and create the file with mode `0600` if absent) so the wizard does NOT re-fire on every subsequent run and later runs keep browser reads disabled. Do not run any `setup` command - the always-on sources (Reddit, HN, Polymarket, GitHub, Web) need no setup. If the invocation already includes a topic, research it immediately, then resume Step 4 (and Step 5 if a key is saved) in the same run after the findings; Step 6 stays skipped because the topic was supplied. Otherwise continue to Step 6.
**If the user picks Auto setup:**
Get cookie consent first. Check if `BROWSER_CONSENT=true` already exists in `~/.config/last30days/.env`; if so, skip the consent prompt and run `setup --allow-browser-cookies` directly. Otherwise **call AskUserQuestion:**
Question: "Auto setup installs the free CLIs either way - yt-dlp (YouTube), Digg, arXiv, and Techmeme. The only thing that needs your OK is reading your browser's x.com cookies to authenticate X/Twitter search: I check Chrome first (a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari. Cookies are read live, never saved to disk. Include X?"
Options (give each option the description shown):
-- "Yes - X cookies + all CLIs" - description: "Read x.com cookies for X/Twitter search AND install yt-dlp (YouTube), Digg, arXiv, and Techmeme." Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (relative to the skill root). Append `BROWSER_CONSENT=true` to `.env` after setup completes.
-- "Skip X - just the CLIs" - description: "No cookie reads. Still installs yt-dlp (YouTube), Digg, arXiv, and Techmeme." Run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. If the invocation already includes a topic, immediately research it with `--no-browser-cookies`, then resume Step 4 (and Step 5 if a key is saved) in the same run after the findings; Step 6 stays skipped because the topic was supplied.
+- "Yes - X cookies + all CLIs" - description: "Read x.com cookies for X/Twitter search AND install yt-dlp (YouTube), Digg, arXiv, and Techmeme." Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (relative to the skill root). The engine saves `BROWSER_CONSENT=true`; do not append a duplicate marker.
+- "Skip X - just the CLIs" - description: "No cookie reads. Still installs yt-dlp (YouTube), Digg, arXiv, and Techmeme." Run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. The engine saves `BROWSER_CONSENT=false`, so the refusal also applies on future runs. If the invocation already includes a topic, immediately research it with `--no-browser-cookies`, then resume Step 4 (and Step 5 if a key is saved) in the same run after the findings; Step 6 stays skipped because the topic was supplied.
- "xAI API key for X instead" - description: "Use an api.x.ai key for X search (no cookie read), plus install yt-dlp (YouTube), Digg, arXiv, and Techmeme." Ask them to paste it, write `XAI_API_KEY` to `.env`, then run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`.
**Grok CLI is an opt-in backup, not a setup-time recommendation.** Do NOT check for grok first or offer it as a primary option during setup. A leftover `~/.grok/auth.json` must never steal the X lane. If the user mentions having a Grok account, tell them: "You can use the Grok CLI by pinning `LAST30DAYS_X_BACKEND=grok` in your `.env` after running `grok login`. This is opt-in because a leftover grok login should not take over X automatically." Do not call it free — it needs a Grok plan.
@@ -659,9 +659,9 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI
**1. Welcome.** Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py --welcome` and show its stdout to the user VERBATIM (do not summarize or reformat). The welcome is engine-owned so it renders the same everywhere.
**2. Cookie consent (ask BEFORE reading anything).** First check if `BROWSER_CONSENT=true` already exists in `~/.config/last30days/.env` (e.g. granted in a prior Claude Code session); if so, skip this prompt and run `setup --allow-browser-cookies` directly. Otherwise ask. Example: `I can read your browser cookies to unlock X/Twitter and other logged-in sources - I check Chrome first (a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari. Want me to? (yes / no)` **Wait for the answer.**
- - On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (and append `BROWSER_CONSENT=true` to `.env` after it completes). Extracts cookies (Chrome/Chromium family first via the Keychain with no Full Disk Access, then Firefox and Safari; only a Firefox/Safari winner is pinned for later runs, so Chrome never re-prompts) and best-effort installs yt-dlp (YouTube), the free keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; activates only when on the agent subprocess PATH, typically `$HOME/.local/bin`; reports honestly if off-PATH; recommend-only if `npx` is unavailable), plus the free keyless arXiv and Techmeme CLIs.
+ - On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --allow-browser-cookies` (the engine saves `BROWSER_CONSENT=true`; do not append a duplicate marker). Extracts cookies (Chrome/Chromium family first via the Keychain with no Full Disk Access, then Firefox and Safari; only a Firefox/Safari winner is pinned for later runs, so Chrome never re-prompts) and best-effort installs yt-dlp (YouTube), the free keyless Digg CLI (`digg-pp-cli` via `@mvanhorn/printing-press-library install digg --cli-only`; activates only when on the agent subprocess PATH, typically `$HOME/.local/bin`; reports honestly if off-PATH; recommend-only if `npx` is unavailable), plus the free keyless arXiv and Techmeme CLIs.
- **Extras hosts (Linux / Mac mini / Darwin agentcookie sink) — a MacBook SKIPS this, and so does a `LAST30DAYS_HOST=grok-bot` host.** On these hosts the Chrome cookie store can't be decrypted, so the extract above finds nothing and X stays empty unless you capture a LIVE login over CDP. Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/box_chrome_login.py` (prints the host-correct command; `--exec` launches it; a MacBook prints "no launch needed" and spawns nothing). When `box-chrome` is on PATH it launches a throwaway profile on the last30days extras port **18800** (`SAND_CHROME_REMOTE_DEBUG_PORT=18800`, not box-chrome's default): `CHROME_USER_DATA_DIR=/tmp/last30days-x-chrome SAND_CHROME_REMOTE_DEBUG_PORT=18800 box-chrome --new-window https://x.com/login`. Wait for the x.com login page, then HAND THE DESKTOP to the human to type — do NOT drive the form. After they sign in, append `BROWSER_CDP_URL=http://127.0.0.1:18800` to `.env` (never `AUTH_TOKEN`/`CT0`; keep `AGENTCOOKIE=off` during the harvest) and re-run `setup --allow-browser-cookies`. Full steps and the block/rate-limit stop rule: **X on Linux / Mac mini** below. This extras-host login only runs on the consented **yes** path; a waiting topic never skips it when the user said yes to X.
- - On **no** → run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp (YouTube), Digg, arXiv, and Techmeme, still writes `SETUP_COMPLETE`. If the invocation already includes a topic, immediately research it with `--no-browser-cookies`, then resume the deferred onboarding in the same run after the findings: the ScrapeCreators offer (step 4) and source tier (step 4b) if a key is saved. Do not re-ask cookie consent as part of the resume.
+ - On **no** → run `FROM_BROWSER=off "${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup`. Skips all cookie reads; still installs yt-dlp (YouTube), Digg, arXiv, and Techmeme, still writes `SETUP_COMPLETE`. The engine saves `BROWSER_CONSENT=false`, so later runs also skip native browser and CDP reads. If the invocation already includes a topic, immediately research it with `--no-browser-cookies`, then resume the deferred onboarding in the same run after the findings: the ScrapeCreators offer (step 4) and source tier (step 4b) if a key is saved. Do not re-ask cookie consent as part of the resume.
**3. Full Disk Access remediation (macOS only).** After `setup`, inspect stderr. If it contains `Permission denied reading Cookies.binarycookies` on macOS, surface: `macOS blocked the cookie read. To enable X/Twitter: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry only when no research topic is waiting. If a topic is already waiting or the user skips, continue immediately with available sources.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 85aa6b9e..e5957a6e 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -3340,8 +3340,16 @@ def _main(
# first-run scan but never pinned.
if from_browser in {"chrome", "brave", "edge", "vivaldi", "opera", "arc", "chromium"}:
from_browser = None
- setup_wizard.write_setup_config(env.CONFIG_FILE, from_browser=from_browser)
- results["env_written"] = True
+ results["env_written"] = setup_wizard.write_setup_config(
+ env.CONFIG_FILE,
+ from_browser=from_browser,
+ browser_consent=(
+ None if args.diagnose else _setup_allows_browser_cookies(args, extra_argv)
+ ),
+ )
+ if not results["env_written"]:
+ sys.stderr.write("Setup configuration could not be fully saved; some settings may already be saved.\n")
+ return 1
sys.stderr.write(setup_wizard.get_setup_status_text(results) + "\n")
return 0
diff --git a/skills/last30days/scripts/lib/chrome_cdp.py b/skills/last30days/scripts/lib/chrome_cdp.py
index 0bdaf78b..b0d5a4f1 100644
--- a/skills/last30days/scripts/lib/chrome_cdp.py
+++ b/skills/last30days/scripts/lib/chrome_cdp.py
@@ -25,7 +25,9 @@ Deliberate constraints (see docs/plans/2026-08-31 X plan):
* **Require a Chrome page target.** ``/json/version`` must report a Chrome /
Chromium browser (a Node inspector is rejected) and ``/json`` must expose a
``page`` target.
-* **``FROM_BROWSER=off`` skips CDP.**
+* **Explicit consent required.** ``BROWSER_CONSENT=true`` or an explicit
+ Chromium/``auto`` selection permits CDP. ``FROM_BROWSER=off`` or a recorded
+ refusal blocks it, including when an endpoint is configured.
* Stdlib only: a tiny RFC 6455 websocket client, no third-party dependency.
* Cookie **values are never logged** — only counts and endpoints.
* First complete pair wins: both ``auth_token`` and ``ct0`` must be present.
@@ -390,23 +392,33 @@ def _pair_from_cookies(cookies: List[Dict[str, Any]]) -> Dict[str, str]:
return {}
+def cookie_access_allowed(config: Optional[Dict[str, Any]] = None) -> bool:
+ config = config or {}
+ from_browser = str(config.get("FROM_BROWSER") or "").strip().lower()
+ if from_browser == "off":
+ return False
+ consent = config.get("BROWSER_CONSENT")
+ if consent is not None:
+ return str(consent).strip().lower() in {"1", "true", "yes", "on"}
+ requested = {browser.strip() for browser in from_browser.split(",")}
+ return bool(requested & {"auto", "chrome", "brave", "edge", "vivaldi", "opera", "arc", "chromium"})
+
+
def read_x_cookies(config: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, str]]:
"""Return the complete X cookie pair from a live Chrome session, or None.
Resolves the debug endpoint (BROWSER_CDP_URL, else 18800 if Chrome, else
9222+$DISPLAY), requires a Chrome page target, and calls
``Network.getAllCookies``. Returns ``{"auth_token", "ct0"}`` only when BOTH
- cookies are found (no half-pair). ``FROM_BROWSER=off`` returns None without
- opening a socket. Any failure returns None so the caller falls through.
+ cookies are found (no half-pair). Without explicit consent, returns None
+ before resolving endpoints or opening a socket. Any failure returns None
+ so the caller falls through.
Never raises.
Host gating (extras-only) lives in the caller (``env.x_extras_enabled``);
on a plain MacBook this function is never invoked, so no socket is opened.
"""
- from_browser = ""
- if config is not None:
- from_browser = (config.get("FROM_BROWSER") or "").strip().lower()
- if from_browser == "off":
+ if not cookie_access_allowed(config):
return None
for base in candidate_endpoints(config):
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 924dabde..084f74e8 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -664,6 +664,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
# automated contexts (cron/CI/eval). Read by trustpilot._harvest_allowed.
('LAST30DAYS_TRUSTPILOT_NO_BROWSER', None),
('FROM_BROWSER', None),
+ ('BROWSER_CONSENT', None),
# agentcookie sidecar: soft-dep X cookie source (lib/agentcookie.py),
# active only on extra hosts (Linux / Mac mini / Darwin sink) or when
# set to "on". "off" disables the sidecar reader.
@@ -990,8 +991,8 @@ def _discover_and_apply_x_credentials(config: dict[str, Any]) -> None:
if mini_extract_first and not have_pair():
_apply_browser_extract(config)
- # (3) live Chrome CDP — extras only, complete pair only.
- if extras and not have_pair():
+ # (3) live Chrome CDP — extras only, after browser-cookie consent.
+ if extras and not have_pair() and chrome_cdp.cookie_access_allowed(config):
pair = chrome_cdp.read_x_cookies(config)
if pair:
_apply_x_pair(config, pair["auth_token"], pair["ct0"], "chrome cdp")
@@ -1044,6 +1045,9 @@ def cookie_extraction_browsers(config: dict[str, Any]) -> list[str]:
"""
if not x_policy(config).cookie_discovery:
return []
+ consent = config.get("BROWSER_CONSENT")
+ if consent is not None and str(consent).strip().lower() not in {"1", "true", "yes", "on"}:
+ return []
silent_browsers = ["firefox", "safari"]
chromium_browsers = ["chrome", "brave", "edge", "vivaldi", "opera", "arc", "chromium"]
known_browsers = silent_browsers + chromium_browsers
diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.py
index 69758d65..9188b45d 100644
--- a/skills/last30days/scripts/lib/setup_wizard.py
+++ b/skills/last30days/scripts/lib/setup_wizard.py
@@ -110,6 +110,7 @@ def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = Fals
from . import cookie_extract
cookie_config = dict(config)
+ cookie_config["BROWSER_CONSENT"] = "true"
if not (cookie_config.get("FROM_BROWSER") or "").strip():
# Chromium-first: Chrome/Brave/etc. read cookies via the Keychain
# with no Full Disk Access, so try them before Safari, whose
@@ -585,11 +586,17 @@ def _format_env_value(value: str) -> str:
return value
-def write_setup_config(env_path: Path, from_browser: str | None = None) -> bool:
- """Write SETUP_COMPLETE and FROM_BROWSER to the .env file.
+def write_setup_config(
+ env_path: Path,
+ from_browser: str | None = None,
+ *,
+ browser_consent: bool | None = None,
+) -> bool:
+ """Write setup completion, browser selection, and consent to the .env file.
Creates the file and parent directories if needed.
- Appends to existing file without overwriting existing keys.
+ Appends without overwriting existing keys, except for an explicit consent
+ decision.
Args:
env_path: Path to the .env file (e.g. ~/.config/last30days/.env)
@@ -599,6 +606,8 @@ def write_setup_config(env_path: Path, from_browser: str | None = None) -> bool:
default (Firefox/Safari, no Keychain prompt) then applies. We avoid
persisting "auto" because it makes every later run probe Chrome and
re-trigger the Keychain prompt.
+ browser_consent: Record the user's current cookie-access decision.
+ None preserves any previous decision.
Returns:
True if config was written successfully, False on error.
@@ -606,6 +615,12 @@ def write_setup_config(env_path: Path, from_browser: str | None = None) -> bool:
try:
env_path = Path(env_path)
env_path.parent.mkdir(parents=True, exist_ok=True)
+ if browser_consent is not None:
+ if not write_api_key(
+ env_path, "true" if browser_consent else "false",
+ key_name="BROWSER_CONSENT", replace=True,
+ ):
+ return False
# Read existing content to avoid overwriting keys
existing_keys: set = set()
diff --git a/tests/test_browser_cookie_consent.py b/tests/test_browser_cookie_consent.py
new file mode 100644
index 00000000..6fc1dc9d
--- /dev/null
+++ b/tests/test_browser_cookie_consent.py
@@ -0,0 +1,153 @@
+"""Durable browser consent at config, setup, and CDP boundaries."""
+
+import os
+import sys
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+import last30days as cli
+from lib import chrome_cdp, env, setup_wizard
+
+
+def browser_session(tmp_path, monkeypatch):
+ env_path = tmp_path / ".env"
+ env_path.touch(mode=0o600)
+ monkeypatch.setattr(env, "CONFIG_FILE", env_path)
+ for name in ("FROM_BROWSER", "BROWSER_CONSENT", "BROWSER_CDP_URL", "LAST30DAYS_HOST"):
+ monkeypatch.delenv(name, raising=False)
+ cookies = [
+ {"name": "auth_token", "value": f"test-auth-{tmp_path.name}", "domain": ".x.com"},
+ {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
+ ]
+ with (
+ mock.patch("platform.system", return_value="Linux"),
+ mock.patch.object(env, "_load_keychain", return_value={}),
+ mock.patch.object(env, "_load_pass", return_value={}),
+ mock.patch("lib.agentcookie.read_x_cookies", return_value=None),
+ mock.patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) as native,
+ mock.patch.object(chrome_cdp, "_get_all_cookies", return_value=cookies) as cdp,
+ ):
+ yield env_path, cdp, native, cookies[0]["value"]
+
+
[email protected]("settings", ["", "BROWSER_CONSENT=false\nFROM_BROWSER=chrome\n"])
+def test_repeated_research_does_not_read_unconsented_browser(browser_session, settings):
+ env_path, cdp, native, _ = browser_session
+ env_path.write_text(settings + "BROWSER_CDP_URL=ws://127.0.0.1:18800/devtools/page/test\n")
+
+ for _ in range(2):
+ config = env.get_config(env.ConfigLoadPolicy(browser_cookies="read"))
+ assert not config.get("AUTH_TOKEN")
+ assert not config.get("CT0")
+ cdp.assert_not_called()
+ native.assert_not_called()
+
+
[email protected]("settings", ["BROWSER_CONSENT=true\n", "FROM_BROWSER=chrome\n"])
+def test_repeated_research_reads_explicitly_consented_browser(browser_session, settings):
+ env_path, cdp, _, auth_token = browser_session
+ env_path.write_text(settings + "BROWSER_CDP_URL=ws://127.0.0.1:18800/devtools/page/test\n")
+
+ for _ in range(2):
+ config = env.get_config(env.ConfigLoadPolicy(browser_cookies="read"))
+ assert config["AUTH_TOKEN"] == auth_token
+ assert config["CT0"] == "test-ct0"
+ assert cdp.call_count == 2
+ assert auth_token not in env_path.read_text()
+
+
+def test_from_browser_off_overrides_recorded_consent(browser_session):
+ env_path, cdp, native, _ = browser_session
+ env_path.write_text("BROWSER_CONSENT=true\nFROM_BROWSER=off\n")
+ config = env.get_config(env.ConfigLoadPolicy(browser_cookies="read"))
+ assert not config.get("AUTH_TOKEN")
+ cdp.assert_not_called()
+ native.assert_not_called()
+
+
+def test_setup_decline_replaces_prior_consent_and_survives_next_run(browser_session):
+ env_path, cdp, native, _ = browser_session
+ env_path.write_text("BROWSER_CONSENT=true\nFROM_BROWSER=chrome\n")
+ with (
+ mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}),
+ mock.patch.object(sys, "argv", ["last30days.py", "setup"]),
+ ):
+ assert cli.main() == 0
+
+ persisted = env.load_env_file(env_path)
+ assert persisted["BROWSER_CONSENT"] == "false"
+ assert persisted["FROM_BROWSER"] == "chrome"
+ for _ in range(2):
+ config = env.get_config(env.ConfigLoadPolicy(browser_cookies="read"))
+ assert not config.get("AUTH_TOKEN")
+ cdp.assert_not_called()
+ native.assert_not_called()
+
+
+def test_setup_grant_records_consent_for_cdp_without_persisting_cookies(browser_session):
+ env_path, cdp, _, auth_token = browser_session
+ env_path.write_text("BROWSER_CONSENT=false\nBROWSER_CDP_URL=ws://127.0.0.1:18800/devtools/page/test\n")
+ with (
+ mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}),
+ mock.patch.object(sys, "argv", ["last30days.py", "setup", "--allow-browser-cookies"]),
+ ):
+ assert cli.main() == 0
+
+ assert env.load_env_file(env_path)["BROWSER_CONSENT"] == "true"
+ for _ in range(2):
+ config = env.get_config(env.ConfigLoadPolicy(browser_cookies="read"))
+ assert config["AUTH_TOKEN"] == auth_token
+ assert cdp.call_count == 2
+ assert auth_token not in env_path.read_text()
+
+
+def test_setup_reports_failure_when_consent_cannot_be_saved(browser_session, capsys):
+ with (
+ mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}),
+ mock.patch("lib.setup_wizard.write_api_key", return_value=False),
+ mock.patch.object(sys, "argv", ["last30days.py", "setup"]),
+ ):
+ assert cli.main() == 1
+ assert "configuration could not be fully saved" in capsys.readouterr().err
+
+
[email protected]("allow_cookies", [False, True])
+def test_setup_reports_partial_save_without_reverting_consent(
+ browser_session, capsys, allow_cookies,
+):
+ env_path, cdp, native, _ = browser_session
+ previous_consent = "false" if allow_cookies else "true"
+ env_path.write_text(f"BROWSER_CONSENT={previous_consent}\nFROM_BROWSER=chrome\n")
+ real_open = os.open
+
+ def fail_completion_append(path, flags, *args, **kwargs):
+ if Path(path) == env_path and flags & os.O_APPEND:
+ raise OSError("test-only completion write failure")
+ return real_open(path, flags, *args, **kwargs)
+
+ argv = ["last30days.py", "setup"]
+ if allow_cookies:
+ argv.append("--allow-browser-cookies")
+ with (
+ mock.patch.object(setup_wizard, "run_auto_setup", return_value={"cookies_found": {}}),
+ mock.patch.object(setup_wizard.os, "open", side_effect=fail_completion_append),
+ mock.patch.object(sys, "argv", argv),
+ ):
+ assert cli.main() == 1
+
+ persisted = env.load_env_file(env_path)
+ assert persisted["BROWSER_CONSENT"] == ("true" if allow_cookies else "false")
+ assert "SETUP_COMPLETE" not in persisted
+ assert persisted["FROM_BROWSER"] == "chrome"
+ if not allow_cookies:
+ for _ in range(2):
+ config = env.get_config(env.ConfigLoadPolicy(browser_cookies="read"))
+ assert not config.get("AUTH_TOKEN")
+ cdp.assert_not_called()
+ native.assert_not_called()
+ stderr = capsys.readouterr().err
+ assert "some settings may already be saved" in stderr
+ assert "configuration was not saved" not in stderr
diff --git a/tests/test_chrome_cdp.py b/tests/test_chrome_cdp.py
index 0b151133..c0123b1d 100644
--- a/tests/test_chrome_cdp.py
+++ b/tests/test_chrome_cdp.py
@@ -14,6 +14,8 @@ import struct
import threading
from unittest import mock
+import pytest
+
from lib import chrome_cdp
_WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
@@ -143,6 +145,21 @@ def test_from_browser_off_skips_endpoints():
assert chrome_cdp.read_x_cookies({"FROM_BROWSER": "off"}) is None
[email protected]("config", [
+ None,
+ {},
+ {"BROWSER_CDP_URL": "ws://127.0.0.1:18800/devtools/page/test"},
+ {"FROM_BROWSER": "firefox"},
+ {"FROM_BROWSER": "chrome", "BROWSER_CONSENT": "false"},
+ {"FROM_BROWSER": "chrome", "BROWSER_CONSENT": "unknown"},
+ {"FROM_BROWSER": "off", "BROWSER_CONSENT": "true"},
+])
+def test_missing_or_declined_consent_skips_endpoint_discovery(config):
+ with mock.patch.object(chrome_cdp, "candidate_endpoints") as endpoints:
+ assert chrome_cdp.read_x_cookies(config) is None
+ endpoints.assert_not_called()
+
+
# --- Fake CDP server (stdlib socket) ---------------------------------------
@@ -318,7 +335,7 @@ def test_read_x_cookies_via_fake_cdp():
{"name": "guest_id", "value": "irrelevant", "domain": ".x.com"},
]
with _FakeCDPServer(cookies) as server:
- config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}"}
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}", "BROWSER_CONSENT": "true"}
result = chrome_cdp.read_x_cookies(config)
assert result == {"auth_token": "test-auth-token", "ct0": "test-ct0"}
@@ -326,7 +343,7 @@ def test_read_x_cookies_via_fake_cdp():
def test_read_x_cookies_incomplete_pair_returns_none():
cookies = [{"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"}]
with _FakeCDPServer(cookies) as server:
- config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}"}
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}", "BROWSER_CONSENT": "true"}
result = chrome_cdp.read_x_cookies(config)
assert result is None
@@ -338,7 +355,7 @@ def test_read_x_cookies_rejects_node_inspector():
{"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
]
with _FakeCDPServer(cookies, browser="node.js/v20.0.0") as server:
- config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}"}
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{server.port}", "BROWSER_CONSENT": "true"}
result = chrome_cdp.read_x_cookies(config)
assert result is None
@@ -355,7 +372,7 @@ def test_read_x_cookies_rejects_wss_without_plaintext_connect():
mock.patch("socket.create_connection", side_effect=AssertionError("no plaintext connect to TLS endpoint")),
mock.patch("urllib.request.urlopen", side_effect=AssertionError("no http probe of TLS endpoint")),
):
- assert chrome_cdp.read_x_cookies({"BROWSER_CDP_URL": "wss://127.0.0.1:9222/devtools/page/ABC"}) is None
+ assert chrome_cdp.read_x_cookies({"BROWSER_CDP_URL": "wss://127.0.0.1:9222/devtools/page/ABC", "BROWSER_CONSENT": "true"}) is None
def test_read_x_cookies_rejects_https_base_without_connect():
@@ -364,7 +381,7 @@ def test_read_x_cookies_rejects_https_base_without_connect():
mock.patch("socket.create_connection", side_effect=AssertionError("no connect")),
mock.patch("urllib.request.urlopen", side_effect=AssertionError("no TLS http probe")),
):
- assert chrome_cdp.read_x_cookies({"BROWSER_CDP_URL": "https://127.0.0.1:18800"}) is None
+ assert chrome_cdp.read_x_cookies({"BROWSER_CDP_URL": "https://127.0.0.1:18800", "BROWSER_CONSENT": "true"}) is None
def test_wsconn_connect_refuses_wss():
@@ -376,5 +393,5 @@ def test_read_x_cookies_no_reachable_endpoint_returns_none():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
dead_port = s.getsockname()[1]
- config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{dead_port}"}
+ config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{dead_port}", "BROWSER_CONSENT": "true"}
assert chrome_cdp.read_x_cookies(config) is None
diff --git a/tests/test_x_extras_gating.py b/tests/test_x_extras_gating.py
index ac8d02b0..7ba0f3e2 100644
--- a/tests/test_x_extras_gating.py
+++ b/tests/test_x_extras_gating.py
@@ -181,7 +181,7 @@ def test_explicit_env_pair_not_overwritten_on_extra_host():
def test_cdp_used_when_agentcookie_empty_on_extra_host():
- config = {}
+ config = {"BROWSER_CONSENT": "true"}
with (
mock.patch("platform.system", return_value="Linux"),
mock.patch("lib.agentcookie.read_x_cookies", return_value=None),