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
feat(env): add a pass(1) credential source (Linux/Unix analog of Keychain) (#564)
george larson627d36c0aab3
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 081a17c4..77628a9f 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -95,6 +95,41 @@ After editing: `chmod 600 ~/.config/last30days/.env` (or `chmod 600 .claude/last**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.+### Encrypted credential sources (Keychain / pass)++If you'd rather not keep keys in a plaintext `.env`, the loader has two+encrypted sources that decrypt secrets transiently at call time (never written+to disk, never logged). Both are **lowest-priority and additive** — an explicit+`.env` or process-env value always overrides them, so you can mix and match. The+`pass` source is only consulted for keys still missing after the higher-priority+sources, so a box that merely has `pass` installed pays no decrypt cost when+everything is already in `.env`.++| Platform | Source | Store keys with | Lookup convention |+|---|---|---|---|+| macOS | Keychain | `scripts/setup-keychain.sh` | service name `last30days-<KEY>` |+| Linux / Unix (anywhere `pass` exists, incl. macOS) | [`pass`(1)](https://www.passwordstore.org/) | `scripts/setup-pass.sh` | pass path `last30days/<KEY>` |++```bash+# macOS Keychain+./scripts/setup-keychain.sh # interactive; --list / --delete KEY++# pass(1) — Linux/Unix analog+./scripts/setup-pass.sh # interactive; --list / --delete KEY+./scripts/setup-pass.sh SCRAPECREATORS_API_KEY # just one key+```++The `pass` source honors `PASSWORD_STORE_DIR`. If your store organizes secrets+under a different prefix, point the loader at it with `LAST30DAYS_PASS_PREFIX`+(works from your `.env` too, and must match where `setup-pass.sh` wrote them).+The prefix is used verbatim, so keep the trailing separator:++```bash+export LAST30DAYS_PASS_PREFIX="secrets/last30days/" # default: last30days/+```++Both sources cover the same key set as the `.env` skeleton above.+### Bluesky app-password format and search host`BSKY_APP_PASSWORD` should be a 19-char app password in `xxxx-xxxx-xxxx-xxxx` format (lowercase alphanumeric, three hyphens). Generate one at <https://bsky.app/settings/app-passwords>. The AT Protocol's `createSession` endpoint also accepts your main account login password, but that's bad hygiene — main passwords have no scope (an app password can be limited to non-DM access) and can't be revoked individually.diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex 1f2cf390..1521c3ce 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -46,6 +46,15 @@ KEYCHAIN_KEYS = ("XIAOHONGSHU_API_BASE",)+# pass(1) integration: Linux/Unix analog of the Keychain source. Each key in+# KEYCHAIN_KEYS is looked up at pass path f"{prefix}{KEY}", the direct analog of+# Keychain's "last30days-<KEY>" service-name convention, so any user stores keys+# under one namespace without editing code. The prefix is resolved at call time+# (in get_config) from LAST30DAYS_PASS_PREFIX in the process env or a config+# file, falling back to this default; included verbatim, so keep the trailing+# separator. Honors PASSWORD_STORE_DIR.+DEFAULT_PASS_PATH_PREFIX = "last30days/"+AuthSource = Literal["api_key", "codex", "none"]AuthStatus = Literal["ok", "missing", "expired", "missing_account_id"]@@ -152,6 +161,45 @@ def _load_keychain(keys: list[str]) -> dict[str, str]:return env+def _load_pass(keys: list[str], prefix: str) -> dict[str, str]:+ """Load credentials from a pass(1) store (no-op if `pass` is absent).++ The Linux/Unix analog of the macOS Keychain source. Each env-var name is+ looked up at pass path ``f"{prefix}{key}"`` — mirroring Keychain's+ ``last30days-<key>`` service-name convention — so any user stores keys under+ that namespace without editing code (prefix overridable via+ ``LAST30DAYS_PASS_PREFIX``). The secret is decrypted in a subprocess and+ read from stdout's first line (pass keeps the secret there; any metadata+ follows) — never written to disk, never logged. Honors ``PASSWORD_STORE_DIR``.+ Missing entries and failures are silent: pass is a lowest-priority, additive+ source like Keychain, so an explicit .env or process-env value still wins.+ """+ import shutil+ pass_bin = shutil.which("pass")+ if not pass_bin:+ return {}++ import subprocess+ env: dict[str, str] = {}+ for key in keys:+ try:+ result = subprocess.run(+ [pass_bin, "show", f"{prefix}{key}"],+ capture_output=True, text=True, timeout=5,+ encoding="utf-8", errors="replace",+ )+ except (subprocess.TimeoutExpired, OSError):+ # A timeout (GPG/pinentry hanging) or exec failure isn't a per-key+ # condition — it means the store is unusable right now. Stop instead+ # of paying the timeout once per key; otherwise a locked store would+ # stall every config load by 5s x len(keys). A genuinely missing key+ # returns fast with a non-zero exit and is handled below.+ break+ if result.returncode == 0 and result.stdout.strip():+ env[key] = result.stdout.strip().splitlines()[0]+ return env++def _decode_jwt_payload(token: str) -> dict[str, Any] | None:"""Decode JWT payload without verification."""try:@@ -291,6 +339,22 @@ def get_config() -> dict[str, Any]:# Loaded before openai_auth so OPENAI_API_KEY can come from Keychain too.keychain_env = _load_keychain(list(KEYCHAIN_KEYS))merged_env = {**keychain_env, **merged_env}+ # pass(1) store: Linux/Unix analog of Keychain at convention path+ # {prefix}<KEY>. Decrypts transiently so secrets stay encrypted at rest (no+ # plaintext .env). Lowest priority: Keychain, the config files, and process+ # env all win over it. Two efficiency guards so a user who merely has `pass`+ # on PATH doesn't pay for it: resolve the prefix from the loaded config/env+ # (not import time, so a .env-set LAST30DAYS_PASS_PREFIX is honored), and+ # probe ONLY keys still unset after the higher-priority sources — an empty+ # list short-circuits with no gpg/pinentry calls at all.+ pass_prefix = (+ os.environ.get("LAST30DAYS_PASS_PREFIX")+ or merged_env.get("LAST30DAYS_PASS_PREFIX")+ or DEFAULT_PASS_PATH_PREFIX+ )+ pass_missing = [k for k in KEYCHAIN_KEYS if k not in os.environ and not merged_env.get(k)]+ pass_env = _load_pass(pass_missing, pass_prefix)+ merged_env = {**pass_env, **merged_env}openai_auth = get_openai_auth(merged_env)@@ -369,6 +433,8 @@ def get_config() -> dict[str, Any]:config['_CONFIG_SOURCE'] = f'global:{CONFIG_FILE}'elif keychain_env:config['_CONFIG_SOURCE'] = 'keychain'+ elif pass_env:+ config['_CONFIG_SOURCE'] = 'pass'else:config['_CONFIG_SOURCE'] = 'env_only'diff --git a/skills/last30days/scripts/setup-pass.sh b/skills/last30days/scripts/setup-pass.shnew file mode 100755index 00000000..053eebae--- /dev/null+++ b/skills/last30days/scripts/setup-pass.sh@@ -0,0 +1,131 @@+#!/usr/bin/env bash+# Store last30days API keys in a pass(1) store.+#+# Keys are stored at pass path `last30days/<KEY>` (the Linux/Unix analog of the+# Keychain `last30days-<KEY>` convention). The lib/env.py loader picks them up+# automatically as a lowest-priority credential source wherever `pass` exists.+# Honors PASSWORD_STORE_DIR; override the path prefix with LAST30DAYS_PASS_PREFIX+# (must match what the loader uses).+#+# Usage:+# ./setup-pass.sh # interactive: prompts for each key+# ./setup-pass.sh KEY [KEY..] # prompt only for the listed keys+# ./setup-pass.sh --list # list which last30days/* entries exist+# ./setup-pass.sh --delete KEY # remove a stored key+#+# Existing values are shown as "(set)" and skipped unless --replace is passed.+# Skip any prompt with empty input.++set -euo pipefail++PREFIX="${LAST30DAYS_PASS_PREFIX:-last30days/}"+# Mirrors lib/env.py::KEYCHAIN_KEYS — kept in sync via+# tests/test_env_pass.py::test_pass_keys_match_setup_script.+ALL_KEYS=(+ OPENAI_API_KEY+ XAI_API_KEY+ GOOGLE_API_KEY+ GEMINI_API_KEY+ GOOGLE_GENAI_API_KEY+ SCRAPECREATORS_API_KEY+ APIFY_API_TOKEN+ AUTH_TOKEN+ CT0+ BSKY_HANDLE+ BSKY_APP_PASSWORD+ TRUTHSOCIAL_TOKEN+ BRAVE_API_KEY+ EXA_API_KEY+ SERPER_API_KEY+ OPENROUTER_API_KEY+ PARALLEL_API_KEY+ XQUIK_API_KEY+ XIAOHONGSHU_API_BASE+)++REPLACE=0+ACTION="prompt"+TARGETS=()++while [[ $# -gt 0 ]]; do+ case "$1" in+ --list) ACTION="list"; shift ;;+ --delete) ACTION="delete"; shift ;;+ --replace) REPLACE=1; shift ;;+ --help|-h) sed -n '2,/^$/p' "$0" | sed 's/^# //; s/^#//'; exit 0 ;;+ -*) echo "unknown flag: $1" >&2; exit 2 ;;+ *) TARGETS+=("$1"); shift ;;+ esac+done++# Checked after flag parsing so `--help` works on a box without pass installed.+if ! command -v pass >/dev/null 2>&1; then+ echo "setup-pass.sh requires the pass(1) password manager (not found on PATH)." >&2+ exit 1+fi++case "$ACTION" in+ list)+ echo "Stored ${PREFIX}* pass entries:"+ for key in "${ALL_KEYS[@]}"; do+ if pass show "${PREFIX}${key}" >/dev/null 2>&1; then+ echo " $key"+ fi+ done+ exit 0+ ;;+ delete)+ if [[ ${#TARGETS[@]} -eq 0 ]]; then+ echo "--delete needs at least one KEY name" >&2; exit 2+ fi+ for key in "${TARGETS[@]}"; do+ if pass rm -f "${PREFIX}${key}" >/dev/null 2>&1; then+ echo "deleted: $key"+ else+ echo "not found: $key"+ fi+ done+ exit 0+ ;;+esac++if [[ ${#TARGETS[@]} -eq 0 ]]; then+ TARGETS=("${ALL_KEYS[@]}")+fi++added=0; skipped=0; replaced=0+for key in "${TARGETS[@]}"; do+ if pass show "${PREFIX}${key}" >/dev/null 2>&1; then+ existing=1+ else+ existing=0+ fi+ if [[ "$existing" -eq 1 && "$REPLACE" -eq 0 ]]; then+ printf " %-28s (set, skipping — use --replace to overwrite)\n" "$key"+ skipped=$((skipped + 1))+ continue+ fi+ printf " %-28s " "$key"+ IFS= read -rs value+ echo+ if [[ -z "$value" ]]; then+ skipped=$((skipped + 1))+ continue+ fi+ # Don't let one failed insert (gpg misconfig, missing store key, disk) abort+ # the whole batch under `set -e`; report it and move on.+ if ! printf '%s\n' "$value" | pass insert -m -f "${PREFIX}${key}" >/dev/null; then+ echo " failed: $key (pass insert error)" >&2+ skipped=$((skipped + 1))+ continue+ fi+ if [[ "$existing" -eq 1 ]]; then+ replaced=$((replaced + 1))+ else+ added=$((added + 1))+ fi+done++echo+echo "Done. added=$added replaced=$replaced skipped=$skipped"+echo "Verify with: $0 --list"diff --git a/tests/test_env_keychain.py b/tests/test_env_keychain.pyindex 53c9e81d..5c7db81f 100644--- a/tests/test_env_keychain.py+++ b/tests/test_env_keychain.py@@ -108,6 +108,9 @@ def clean_env(monkeypatch, tmp_path):monkeypatch.delenv(var, raising=False)monkeypatch.setattr(env, "CONFIG_FILE", tmp_path / "does-not-exist.env")monkeypatch.chdir(tmp_path) # no project .env in this tree either+ # Neutralize the pass(1) source so these tests don't pick up a real pass+ # store on the host running them (tests that exercise pass override this).+ monkeypatch.setattr(env, "_load_pass", lambda *a, **k: {})def test_get_config_reports_keychain_source(clean_env):diff --git a/tests/test_env_pass.py b/tests/test_env_pass.pynew file mode 100644index 00000000..2091ac05--- /dev/null+++ b/tests/test_env_pass.py@@ -0,0 +1,244 @@+"""Tests for the pass(1) credential source in lib/env.py.++Covers:+ - missing `pass` binary returns {}+ - successful lookups return parsed key/value pairs at the prefix convention+ - first-line extraction + whitespace stripping+ - subprocess timeout / OSError are swallowed+ - the path prefix is honored (default + LAST30DAYS_PASS_PREFIX override)+ - get_config merges pass below keychain and below explicit env, and labels+ _CONFIG_SOURCE = 'pass' when pass is the effective source+ - lib/env.py KEYCHAIN_KEYS and setup-pass.sh ALL_KEYS stay in lockstep+"""++from __future__ import annotations++import re+import subprocess+from pathlib import Path+from unittest import mock++import pytest++from lib import env++SETUP_PASS_SH = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts" / "setup-pass.sh"++# ---------------------------------------------------------------------------+# _load_pass unit tests+# ---------------------------------------------------------------------------+++def _run_result(returncode: int, stdout: str = "") -> subprocess.CompletedProcess:+ return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="")+++def test_load_pass_returns_empty_when_pass_missing():+ with mock.patch("shutil.which", return_value=None):+ assert env._load_pass(["XAI_API_KEY"], "last30days/") == {}+++def test_load_pass_loads_present_keys_skips_missing():+ def fake_run(cmd, **kwargs):+ path = cmd[-1] # [pass_bin, "show", "<prefix><key>"]+ if path == "last30days/XAI_API_KEY":+ return _run_result(0, "xai-abc\n")+ if path == "last30days/BRAVE_API_KEY":+ return _run_result(0, "brv-xyz\n")+ return _run_result(1) # pass exits non-zero for a missing entry++ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", side_effect=fake_run):+ result = env._load_pass(["XAI_API_KEY", "BRAVE_API_KEY", "OPENAI_API_KEY"], "last30days/")++ assert result == {"XAI_API_KEY": "xai-abc", "BRAVE_API_KEY": "brv-xyz"}+++def test_load_pass_takes_first_line_only():+ # pass entries keep the secret on line 1; metadata may follow.+ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", return_value=_run_result(0, "sk-secret\nurl: https://x\nuser: bob\n")):+ assert env._load_pass(["OPENAI_API_KEY"], "last30days/") == {"OPENAI_API_KEY": "sk-secret"}+++def test_load_pass_strips_whitespace():+ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", return_value=_run_result(0, " hello-key \n")):+ assert env._load_pass(["FOO"], "last30days/") == {"FOO": "hello-key"}+++def test_load_pass_skips_empty_and_whitespace_only_stdout():+ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", return_value=_run_result(0, " \n")):+ assert env._load_pass(["XAI_API_KEY"], "last30days/") == {}+++def test_load_pass_swallows_timeout():+ def fake_run(cmd, **kwargs):+ raise subprocess.TimeoutExpired(cmd=cmd, timeout=5)++ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", side_effect=fake_run):+ assert env._load_pass(["XAI_API_KEY"], "last30days/") == {}+++def test_load_pass_swallows_oserror():+ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", side_effect=OSError("boom")):+ assert env._load_pass(["XAI_API_KEY"], "last30days/") == {}+++def test_load_pass_stops_probing_after_timeout():+ # A hanging store (GPG/pinentry) must not be probed once per key — otherwise+ # a locked store stalls every config load by 5s x len(keys).+ calls = {"n": 0}++ def fake_run(cmd, **kwargs):+ calls["n"] += 1+ raise subprocess.TimeoutExpired(cmd=cmd, timeout=5)++ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", side_effect=fake_run):+ result = env._load_pass(["XAI_API_KEY", "BRAVE_API_KEY", "OPENAI_API_KEY"], "last30days/")++ assert result == {}+ assert calls["n"] == 1 # stopped after the first timeout, didn't probe the rest+++def test_load_pass_honors_prefix():+ seen = {}++ def fake_run(cmd, **kwargs):+ seen["path"] = cmd[-1]+ return _run_result(0, "v\n")++ with mock.patch("shutil.which", return_value="/usr/bin/pass"), \+ mock.patch("subprocess.run", side_effect=fake_run):+ env._load_pass(["XAI_API_KEY"], "secrets/l30/")++ assert seen["path"] == "secrets/l30/XAI_API_KEY"+++# ---------------------------------------------------------------------------+# get_config integration tests (pass merged below keychain and explicit env)+# ---------------------------------------------------------------------------+++def clean_env(monkeypatch, tmp_path):+ for var in [+ "OPENAI_API_KEY", "XAI_API_KEY", "BRAVE_API_KEY", "AUTH_TOKEN", "CT0",+ "SCRAPECREATORS_API_KEY", "APIFY_API_TOKEN", "BSKY_HANDLE",+ "BSKY_APP_PASSWORD", "TRUTHSOCIAL_TOKEN", "EXA_API_KEY",+ "SERPER_API_KEY", "OPENROUTER_API_KEY", "PARALLEL_API_KEY",+ "XQUIK_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY",+ "GOOGLE_GENAI_API_KEY", "INCLUDE_SOURCES", "FROM_BROWSER",+ ]:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setattr(env, "CONFIG_FILE", tmp_path / "does-not-exist.env")+ monkeypatch.chdir(tmp_path)+++def test_get_config_reports_pass_source(clean_env):+ with mock.patch.object(env, "_load_keychain", return_value={}), \+ mock.patch.object(env, "_load_pass", return_value={"XAI_API_KEY": "xai-from-pass"}):+ cfg = env.get_config()+ assert cfg["_CONFIG_SOURCE"] == "pass"+ assert cfg["XAI_API_KEY"] == "xai-from-pass"+++def test_get_config_keychain_outranks_pass(clean_env):+ with mock.patch.object(env, "_load_keychain", return_value={"XAI_API_KEY": "xai-from-kc"}), \+ mock.patch.object(env, "_load_pass", return_value={"XAI_API_KEY": "xai-from-pass"}):+ cfg = env.get_config()+ assert cfg["XAI_API_KEY"] == "xai-from-kc"+ assert cfg["_CONFIG_SOURCE"] == "keychain"+++def test_get_config_env_var_overrides_pass(clean_env, monkeypatch):+ monkeypatch.setenv("XAI_API_KEY", "xai-from-env")+ with mock.patch.object(env, "_load_keychain", return_value={}), \+ mock.patch.object(env, "_load_pass", return_value={"XAI_API_KEY": "xai-from-pass"}):+ cfg = env.get_config()+ assert cfg["XAI_API_KEY"] == "xai-from-env"+++def test_get_config_global_file_outranks_pass(clean_env, tmp_path, monkeypatch):+ cfg_file = tmp_path / "global.env"+ cfg_file.write_text("XAI_API_KEY=xai-from-file\n")+ monkeypatch.setattr(env, "CONFIG_FILE", cfg_file)+ with mock.patch.object(env, "_load_keychain", return_value={}), \+ mock.patch.object(env, "_load_pass", return_value={"XAI_API_KEY": "xai-from-pass"}):+ cfg = env.get_config()+ assert cfg["XAI_API_KEY"] == "xai-from-file"+ assert cfg["_CONFIG_SOURCE"].startswith("global:")+++def test_get_config_probes_pass_only_for_missing_keys(clean_env, monkeypatch):+ # A key already supplied by a higher-priority source must not be probed in+ # pass — that's what keeps a `pass`-installed but `.env`-using box off gpg.+ monkeypatch.setenv("XAI_API_KEY", "xai-from-env")+ seen = {}++ def fake_load_pass(keys, prefix):+ seen["keys"] = list(keys)+ return {}++ with mock.patch.object(env, "_load_keychain", return_value={}), \+ mock.patch.object(env, "_load_pass", side_effect=fake_load_pass):+ env.get_config()++ assert "XAI_API_KEY" not in seen["keys"] # already supplied by env+ assert "BRAVE_API_KEY" in seen["keys"] # still missing, so probed+++def test_get_config_pass_prefix_resolved_from_config_file(clean_env, tmp_path, monkeypatch):+ # LAST30DAYS_PASS_PREFIX set in the .env config layer (not shell-exported)+ # must reach _load_pass — i.e. the prefix is resolved at call time.+ cfg_file = tmp_path / "global.env"+ cfg_file.write_text("LAST30DAYS_PASS_PREFIX=secrets/l30/\n")+ monkeypatch.setattr(env, "CONFIG_FILE", cfg_file)+ seen = {}++ def fake_load_pass(keys, prefix):+ seen["prefix"] = prefix+ return {}++ with mock.patch.object(env, "_load_keychain", return_value={}), \+ mock.patch.object(env, "_load_pass", side_effect=fake_load_pass):+ env.get_config()++ assert seen["prefix"] == "secrets/l30/"+++def test_get_config_openai_key_can_come_from_pass(clean_env):+ with mock.patch.object(env, "_load_keychain", return_value={}), \+ mock.patch.object(env, "_load_pass", return_value={"OPENAI_API_KEY": "sk-from-pass"}):+ cfg = env.get_config()+ assert cfg["OPENAI_API_KEY"] == "sk-from-pass"+ assert cfg["OPENAI_AUTH_SOURCE"] == "api_key"+++# ---------------------------------------------------------------------------+# Drift guard: lib/env.py KEYCHAIN_KEYS and setup-pass.sh ALL_KEYS must stay in+# lockstep, same as the Keychain helper. A mismatch means a key stored via the+# helper wouldn't be picked up by the loader, or vice versa.+# ---------------------------------------------------------------------------+++def _parse_all_keys_from_shell(script: Path) -> list[str]:+ text = script.read_text(encoding="utf-8")+ match = re.search(r"ALL_KEYS=\(\s*(.*?)\s*\)", text, re.DOTALL)+ if not match:+ raise AssertionError(f"ALL_KEYS=( ... ) array not found in {script}")+ body = re.sub(r"#[^\n]*", "", match.group(1))+ return [tok for tok in body.split() if tok]+++def test_pass_keys_match_setup_script():+ shell_keys = _parse_all_keys_from_shell(SETUP_PASS_SH)+ python_keys = list(env.KEYCHAIN_KEYS)+ assert shell_keys == python_keys, (+ "lib/env.py::KEYCHAIN_KEYS and scripts/setup-pass.sh::ALL_KEYS have "+ f"drifted.\n python: {python_keys}\n shell: {shell_keys}"+ )