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: support keychain credential aliases
oc-morty8979bc74e434
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 11aa4ad8..574806db 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -192,6 +192,31 @@ export LAST30DAYS_PASS_PREFIX="secrets/last30days/" # default: last30days/Both sources cover the same key set as the `.env` skeleton above.+#### Reusing existing macOS Keychain items++If you already have keys stored under another Keychain naming convention, you+can reference them without copying the secret by setting non-secret alias+metadata in `LAST30DAYS_KEYCHAIN_ALIASES`. The loader still checks+`last30days-<KEY>` first; aliases are fallback lookups only.++```bash+# ~/.config/last30days/.env+LAST30DAYS_KEYCHAIN_ALIASES={"XAI_API_KEY":{"account":"keychain-user","service":"existing-xai-api-key"},"BRAVE_API_KEY":"existing-brave-api-key"}+```++Each JSON key must be one of the supported env-var names (`XAI_API_KEY`,+`SCRAPECREATORS_API_KEY`, `BRAVE_API_KEY`, etc). A string value means "use this+service name with the current user account"; an object can specify both+`account` and `service`. Lists are allowed for fallback order:++```bash+LAST30DAYS_KEYCHAIN_ALIASES={"XAI_API_KEY":[{"account":"keychain-user","service":"existing-xai-api-key"},{"service":"last-resort-xai"}]}+```++The alias value contains no secret material; it is safe to keep in `.env` as+configuration. The secret itself remains in its original Keychain item and is+read directly by the engine process.+### 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/README.md b/README.mdindex 4c2653a0..38040edd 100644--- a/README.md+++ b/README.md@@ -308,6 +308,8 @@ skills/last30days/scripts/setup-keychain.sh --delete XAI_API_KEYItems are stored under service name `last30days-<KEY>` for the current user. On non-Darwin platforms the loader is a no-op, so there is no behaviour change for Linux/Windows users.+Already have keys under different Keychain service names? Set the non-secret `LAST30DAYS_KEYCHAIN_ALIASES` mapping described in [CONFIGURATION.md](CONFIGURATION.md#reusing-existing-macos-keychain-items) instead of copying secrets.+See [CONFIGURATION.md](CONFIGURATION.md) for the full per-source key matrix, reasoning provider priority, and web-search backend priority.## Configurationdiff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex ab59f351..ac705aa8 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -34,6 +34,13 @@ CODEX_AUTH_FILE = Path(os.environ.get("CODEX_AUTH_FILE", str(Path.home() / ".cod# Example: `security add-generic-password -a "$USER" -s last30days-XAI_API_KEY -w "xai-..."`.KEYCHAIN_SERVICE_PREFIX = "last30days-"+# Optional non-secret aliases for users who already store API keys under a+# different Keychain naming convention. Configure as JSON in+# LAST30DAYS_KEYCHAIN_ALIASES, for example:+# {"XAI_API_KEY":{"account":"keychain-user","service":"existing-xai-api-key"}}+# A string value is shorthand for {"service": "..."} with the current user.+KEYCHAIN_ALIASES_ENV = "LAST30DAYS_KEYCHAIN_ALIASES"+# Single source of truth for which credentials the Keychain loader looks up.# The setup-keychain.sh helper mirrors this list and is held in sync via# tests/test_env_keychain.py::test_keychain_keys_match_setup_script.@@ -121,13 +128,58 @@ def load_env_file(path: Path) -> dict[str, str]:return env-def _load_keychain(keys: list[str]) -> dict[str, str]:+def _parse_keychain_aliases(raw: str | None) -> dict[str, list[dict[str, str]]]:+ """Parse non-secret Keychain alias metadata from JSON.++ Supported forms:+ {"XAI_API_KEY": "existing-xai-api-key"}+ {"XAI_API_KEY": {"service": "existing-xai-api-key", "account": "keychain-user"}}+ {"XAI_API_KEY": [{"service": "primary"}, {"service": "fallback"}]}++ Invalid entries are ignored silently so a typo never blocks canonical+ `last30days-<KEY>` lookups.+ """+ if not raw:+ return {}+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError:+ return {}+ if not isinstance(parsed, dict):+ return {}++ allowed = set(KEYCHAIN_KEYS)+ aliases: dict[str, list[dict[str, str]]] = {}+ for key, spec in parsed.items():+ if key not in allowed:+ continue+ specs = spec if isinstance(spec, list) else [spec]+ clean_specs: list[dict[str, str]] = []+ for item in specs:+ if isinstance(item, str):+ service = item.strip()+ account = ""+ elif isinstance(item, dict):+ service = str(item.get("service", "")).strip()+ account = str(item.get("account", "")).strip()+ else:+ continue+ if service:+ clean_specs.append({"service": service, "account": account})+ if clean_specs:+ aliases[key] = clean_specs+ return aliases+++def _load_keychain(keys: list[str], aliases: dict[str, list[dict[str, str]]] | None = None) -> dict[str, str]:"""Load credentials from macOS Keychain (no-op on other platforms).Each key is looked up as a generic password with service name``f"{KEYCHAIN_SERVICE_PREFIX}{key}"`` for the current user. Missing items- and lookup failures are silent — Keychain is the lowest-priority source- and is meant to be additive over `.env` files and process environment.+ then fall back to optional alias metadata from+ ``LAST30DAYS_KEYCHAIN_ALIASES``. Lookup failures are silent — Keychain is+ the lowest-priority source and is meant to be additive over `.env` files+ and process environment."""import platformif platform.system() != "Darwin":@@ -157,19 +209,32 @@ def _load_keychain(keys: list[str]) -> dict[str, str]:else:user = "unknown"env: dict[str, str] = {}- for key in keys:++ def lookup(account: str, service: str) -> str:try:result = subprocess.run([security, "find-generic-password",- "-a", user,- "-s", f"{KEYCHAIN_SERVICE_PREFIX}{key}",+ "-a", account,+ "-s", service,"-w"],capture_output=True, text=True, timeout=5,)except (subprocess.TimeoutExpired, OSError):- continue+ return ""if result.returncode == 0 and result.stdout.strip():- env[key] = result.stdout.strip()+ return result.stdout.strip()+ return ""++ for key in keys:+ value = lookup(user, f"{KEYCHAIN_SERVICE_PREFIX}{key}")+ if not value and aliases:+ for alias in aliases.get(key, []):+ alias_account = alias.get("account") or user+ value = lookup(alias_account, alias["service"])+ if value:+ break+ if value:+ env[key] = valuereturn env@@ -349,7 +414,9 @@ def get_config() -> dict[str, Any]:# Keychain is the lowest-priority source (Darwin only; no-op elsewhere).# Loaded before openai_auth so OPENAI_API_KEY can come from Keychain too.- keychain_env = _load_keychain(list(KEYCHAIN_KEYS))+ keychain_aliases_raw = os.environ.get(KEYCHAIN_ALIASES_ENV) or merged_env.get(KEYCHAIN_ALIASES_ENV)+ keychain_aliases = _parse_keychain_aliases(keychain_aliases_raw)+ keychain_env = _load_keychain(list(KEYCHAIN_KEYS), keychain_aliases)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@@ -435,6 +502,7 @@ def get_config() -> dict[str, Any]:('LAST30DAYS_DEFAULT_SEARCH', ''),('LAST30DAYS_YOUTUBE_SSH_HOST', None),('LAST30DAYS_TRANSCRIPT_TIMEOUT', None),+ (KEYCHAIN_ALIASES_ENV, None),# Whisper transcription provider for caption-free audio/video. Groq's# free tier is preferred; OPENAI_API_KEY is the paid backstop (already# resolved above via openai_auth).diff --git a/tests/test_env_keychain.py b/tests/test_env_keychain.pyindex 601a8612..08990489 100644--- a/tests/test_env_keychain.py+++ b/tests/test_env_keychain.py@@ -41,6 +41,32 @@ def _run_result(returncode: int, stdout: str = "") -> subprocess.CompletedProcesreturn subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="")+def test_parse_keychain_aliases_accepts_string_and_object_forms():+ raw = (+ '{"XAI_API_KEY":"existing-xai-api-key",'+ '"BRAVE_API_KEY":{"account":"keychain-user","service":"existing-brave-api-key"}}'+ )+ assert env._parse_keychain_aliases(raw) == {+ "XAI_API_KEY": [{"service": "existing-xai-api-key", "account": ""}],+ "BRAVE_API_KEY": [{"service": "existing-brave-api-key", "account": "keychain-user"}],+ }+++def test_parse_keychain_aliases_accepts_ordered_fallback_list():+ raw = '{"XAI_API_KEY":[{"service":"primary-xai"},{"account":"keychain-user","service":"fallback-xai"}]}'+ assert env._parse_keychain_aliases(raw) == {+ "XAI_API_KEY": [+ {"service": "primary-xai", "account": ""},+ {"service": "fallback-xai", "account": "keychain-user"},+ ],+ }+++def test_parse_keychain_aliases_ignores_invalid_json_and_unknown_keys():+ assert env._parse_keychain_aliases("not json") == {}+ assert env._parse_keychain_aliases('{"NOT_A_KEY":"secret-service"}') == {}++def test_load_keychain_loads_present_keys_skips_missing():def fake_run(cmd, **kwargs):service = cmd[cmd.index("-s") + 1]@@ -58,6 +84,49 @@ def test_load_keychain_loads_present_keys_skips_missing():assert result == {"XAI_API_KEY": "xai-abc", "BRAVE_API_KEY": "brv-xyz"}+def test_load_keychain_uses_alias_when_canonical_missing():+ calls = []++ def fake_run(cmd, **kwargs):+ account = cmd[cmd.index("-a") + 1]+ service = cmd[cmd.index("-s") + 1]+ calls.append((account, service))+ if account == "keychain-user" and service == "existing-xai-api-key":+ return _run_result(0, "xai-alias\n")+ return _run_result(44)++ aliases = {"XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}]}+ with mock.patch("platform.system", return_value="Darwin"), \+ mock.patch("shutil.which", return_value="/usr/bin/security"), \+ mock.patch.dict("os.environ", {"USER": "mortimer"}, clear=False), \+ mock.patch("subprocess.run", side_effect=fake_run):+ result = env._load_keychain(["XAI_API_KEY"], aliases)++ assert result == {"XAI_API_KEY": "xai-alias"}+ assert calls == [+ ("mortimer", "last30days-XAI_API_KEY"),+ ("keychain-user", "existing-xai-api-key"),+ ]+++def test_load_keychain_canonical_wins_over_alias():+ def fake_run(cmd, **kwargs):+ service = cmd[cmd.index("-s") + 1]+ if service == "last30days-XAI_API_KEY":+ return _run_result(0, "xai-canonical\n")+ if service == "existing-xai-api-key":+ return _run_result(0, "xai-alias\n")+ return _run_result(44)++ aliases = {"XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}]}+ with mock.patch("platform.system", return_value="Darwin"), \+ mock.patch("shutil.which", return_value="/usr/bin/security"), \+ mock.patch("subprocess.run", side_effect=fake_run):+ result = env._load_keychain(["XAI_API_KEY"], aliases)++ assert result == {"XAI_API_KEY": "xai-canonical"}++def test_load_keychain_strips_whitespace_and_newlines():with mock.patch("platform.system", return_value="Darwin"), \mock.patch("shutil.which", return_value="/usr/bin/security"), \@@ -143,6 +212,45 @@ def test_get_config_global_file_outranks_keychain(clean_env, tmp_path, monkeypatassert cfg["_CONFIG_SOURCE"].startswith("global:")+def test_get_config_passes_aliases_from_global_file(clean_env, tmp_path, monkeypatch):+ cfg_file = tmp_path / "global.env"+ cfg_file.write_text(+ 'LAST30DAYS_KEYCHAIN_ALIASES={"XAI_API_KEY":{"account":"keychain-user","service":"existing-xai-api-key"}}\n'+ )+ monkeypatch.setattr(env, "CONFIG_FILE", cfg_file)++ def fake_load_keychain(keys, aliases=None):+ assert aliases == {+ "XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}],+ }+ return {"XAI_API_KEY": "xai-from-alias"}++ with mock.patch.object(env, "_load_keychain", side_effect=fake_load_keychain):+ cfg = env.get_config()++ assert cfg["XAI_API_KEY"] == "xai-from-alias"+ assert cfg["LAST30DAYS_KEYCHAIN_ALIASES"].startswith('{"XAI_API_KEY"')+++def test_get_config_passes_aliases_from_process_env(clean_env, monkeypatch):+ monkeypatch.setenv(+ "LAST30DAYS_KEYCHAIN_ALIASES",+ '{"XAI_API_KEY":{"account":"keychain-user","service":"existing-xai-api-key"}}',+ )++ def fake_load_keychain(keys, aliases=None):+ assert aliases == {+ "XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}],+ }+ return {"XAI_API_KEY": "xai-from-env-alias"}++ with mock.patch.object(env, "_load_keychain", side_effect=fake_load_keychain):+ cfg = env.get_config()++ assert cfg["XAI_API_KEY"] == "xai-from-env-alias"+ assert cfg["LAST30DAYS_KEYCHAIN_ALIASES"].startswith('{"XAI_API_KEY"')++def test_get_config_openai_key_can_come_from_keychain(clean_env):"""OPENAI_API_KEY must be visible to get_openai_auth via the keychainmerge — wiring regression test."""