Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

fix(security): harden local credential handling

Pnante4c31b29b182
diff --git a/agent_reach/channels/xueqiu.py b/agent_reach/channels/xueqiu.py
index f1ce444b..c5bc528d 100644
--- a/agent_reach/channels/xueqiu.py
+++ b/agent_reach/channels/xueqiu.py
@@ -85,7 +85,10 @@ def _load_cookies_from_browser() -> bool:
if not any(c.get("name") == "xq_a_token" for c in cookies):
return False
for c in cookies:
- _cookie_jar.set(c["name"], c["value"], domain=c.get("domain", ".xueqiu.com"))
+ name = c.get("name")
+ value = c.get("value")
+ if name and value is not None:
+ _inject_cookie_string(f"{name}={value}")
return True
except ImportError:
import browser_cookie3
diff --git a/agent_reach/cli.py b/agent_reach/cli.py
index 1d356768..3cd45f61 100644
--- a/agent_reach/cli.py
+++ b/agent_reach/cli.py
@@ -352,7 +352,7 @@ def _cmd_install(args):
print("Dry run complete. No changes were made.")
-def _install_skill():
+def _install_skill(force: bool = True):
"""Install Agent Reach as an agent skill (OpenClaw / Claude Code / .agents)."""
import os
import shutil
@@ -380,9 +380,12 @@ def _install_skill():
except FileNotFoundError:
return skill_pkg.joinpath("SKILL.md").read_text(encoding="utf-8")
- def _copy_skill_dir(target: str) -> bool:
+ def _copy_skill_dir(target: str) -> str | None:
"""Copy entire skill directory (locale-specific SKILL.md + references/)."""
try:
+ if not force and os.path.exists(os.path.join(target, "SKILL.md")):
+ return "preserved"
+
# Clear existing installation. A symlinked skill dir (dotfiles
# setups) breaks shutil.rmtree — unlink the link itself instead.
if os.path.islink(target):
@@ -416,10 +419,10 @@ def _install_skill():
with open(os.path.join(refs_target, name), "w", encoding="utf-8") as f:
f.write(content)
- return True
+ return "installed"
except Exception as e:
print(f" Warning: Could not install skill: {e}")
- return False
+ return None
# Determine skill install path (priority: .agents > openclaw > claude)
skill_dirs = [
@@ -437,16 +440,23 @@ def _install_skill():
for skill_dir in skill_dirs:
if os.path.isdir(skill_dir):
target = os.path.join(skill_dir, "agent-reach")
- if _copy_skill_dir(target):
+ status = _copy_skill_dir(target)
+ if status:
platform_name = "Agent" if ".agents" in skill_dir else "OpenClaw" if "openclaw" in skill_dir else "Claude Code"
- print(f"Skill installed for {platform_name}: {target}")
+ if status == "preserved":
+ print(f"Skill already installed for {platform_name}, preserving existing files: {target}")
+ else:
+ print(f"Skill installed for {platform_name}: {target}")
installed = True
if not installed:
# No known skill directory found — create for .agents by default
target = os.path.expanduser("~/.agents/skills/agent-reach")
os.makedirs(os.path.dirname(target), exist_ok=True)
- if _copy_skill_dir(target):
+ status = _copy_skill_dir(target)
+ if status == "preserved":
+ print(f"Skill already installed, preserving existing files: {target}")
+ elif status == "installed":
print(f"Skill installed: {target}")
else:
print(" -- Could not install agent skill (optional)")
@@ -1249,14 +1259,21 @@ def _configure_xhs_cookies(value):
# Create with 0o600 atomically so the file is never world-readable
# between open() and a follow-up chmod() (same pattern Config.save()
# uses in config.py).
+ import os
import stat
- cookie_path = os.path.expanduser("~/.agent-reach/xhs-cookies.json")
+
+ from agent_reach.utils.paths import make_private_dir
+
+ cookie_dir = make_private_dir(os.path.expanduser("~/.agent-reach"))
+ cookie_path = cookie_dir / "xhs-cookies.json"
try:
fd = os.open(
- cookie_path,
+ str(cookie_path),
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
stat.S_IRUSR | stat.S_IWUSR, # 0o600
)
+ if os.name != "nt":
+ os.chmod(cookie_path, stat.S_IRUSR | stat.S_IWUSR)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(cookies_json)
except OSError:
@@ -1473,7 +1490,7 @@ def _cmd_doctor(args=None):
rprint(format_report(results))
# Auto-install skill if not already present (fixes #154)
- _install_skill()
+ _install_skill(force=False)
def _cmd_setup():
diff --git a/agent_reach/config.py b/agent_reach/config.py
index 4386bb47..59d91851 100644
--- a/agent_reach/config.py
+++ b/agent_reach/config.py
@@ -11,6 +11,8 @@ from typing import Any, Optional
import yaml
+from agent_reach.utils.paths import make_private_dir
+
class Config:
"""Manages Agent Reach configuration."""
@@ -36,7 +38,7 @@ class Config:
def _ensure_dir(self):
"""Create config directory if it doesn't exist."""
- self.config_dir.mkdir(parents=True, exist_ok=True)
+ make_private_dir(self.config_dir)
def load(self):
"""Load config from YAML file."""
@@ -58,6 +60,8 @@ class Config:
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
stat.S_IRUSR | stat.S_IWUSR, # 0o600
)
+ if os.name != "nt":
+ os.chmod(self.config_path, stat.S_IRUSR | stat.S_IWUSR)
with os.fdopen(fd, "w", encoding="utf-8") as f:
yaml.dump(self.data, f, default_flow_style=False, allow_unicode=True)
except OSError:
@@ -65,6 +69,8 @@ class Config:
# are not fully supported.
with open(self.config_path, "w", encoding="utf-8") as f:
yaml.dump(self.data, f, default_flow_style=False, allow_unicode=True)
+ if os.name != "nt":
+ os.chmod(self.config_path, 0o600)
def get(self, key: str, default: Any = None) -> Any:
"""Get a config value. Also checks environment variables (uppercase)."""
@@ -101,9 +107,23 @@ class Config:
def to_dict(self) -> dict:
"""Return config as dict (masks sensitive values)."""
+ sensitive_markers = (
+ "key",
+ "token",
+ "password",
+ "proxy",
+ "cookie",
+ "secret",
+ "session",
+ "sessdata",
+ "csrf",
+ "auth",
+ "cred",
+ "ct0",
+ )
masked = {}
for k, v in self.data.items():
- if any(s in k.lower() for s in ("key", "token", "password", "proxy")):
+ if any(s in k.lower() for s in sensitive_markers):
masked[k] = f"{str(v)[:8]}..." if v else None
else:
masked[k] = v
diff --git a/agent_reach/cookie_extract.py b/agent_reach/cookie_extract.py
index 545f9621..a3e92876 100644
--- a/agent_reach/cookie_extract.py
+++ b/agent_reach/cookie_extract.py
@@ -8,9 +8,7 @@ Usage:
agent-reach configure --from-browser chrome
"""
-import sys
-from typing import Dict, List, Optional, Tuple
-
+from typing import Dict, List, Tuple
# Platform cookie specs: (platform_name, domain_pattern, needed_cookies)
PLATFORM_SPECS = [
@@ -165,9 +163,14 @@ def _open_owner_only(path: str):
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
stat.S_IRUSR | stat.S_IWUSR, # 0o600
)
+ if os.name != "nt":
+ os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
return os.fdopen(fd, "w", encoding="utf-8")
except OSError:
- return open(path, "w", encoding="utf-8")
+ handle = open(path, "w", encoding="utf-8")
+ if os.name != "nt":
+ os.chmod(path, 0o600)
+ return handle
def _sync_xfetch_session(auth_token: str, ct0: str) -> None:
@@ -176,8 +179,10 @@ def _sync_xfetch_session(auth_token: str, ct0: str) -> None:
import os
try:
+ from agent_reach.utils.paths import make_private_dir
+
xfetch_dir = os.path.join(os.path.expanduser("~"), ".config", "xfetch")
- os.makedirs(xfetch_dir, exist_ok=True)
+ make_private_dir(xfetch_dir)
session_path = os.path.join(xfetch_dir, "session.json")
session_data: dict = {}
if os.path.exists(session_path):
@@ -207,8 +212,10 @@ def _sync_bird_env(auth_token: str, ct0: str) -> None:
import shlex
try:
+ from agent_reach.utils.paths import make_private_dir
+
bird_dir = os.path.join(os.path.expanduser("~"), ".config", "bird")
- os.makedirs(bird_dir, exist_ok=True)
+ make_private_dir(bird_dir)
env_path = os.path.join(bird_dir, "credentials.env")
with _open_owner_only(env_path) as f:
f.write(f"AUTH_TOKEN={shlex.quote(auth_token)}\n")
diff --git a/agent_reach/skill/references/video.md b/agent_reach/skill/references/video.md
index 5fdbc3db..529d1ca8 100644
--- a/agent_reach/skill/references/video.md
+++ b/agent_reach/skill/references/video.md
@@ -47,6 +47,7 @@ agent-reach transcribe "https://www.youtube.com/watch?v=VIDEO_ID"
agent-reach transcribe ./local_audio.mp3 -o /tmp/transcript.txt
```
+> `agent-reach transcribe` 只接收公开 http(s) URL 或本地音频文件。用 `ytsearch5:` 搜索时,先从 yt-dlp 结果里选出具体视频 URL,再转写。
> 需要先配置 key:`agent-reach configure groq-key gsk_xxx`(免费,console.groq.com)
> 或 `agent-reach configure openai-key sk-xxx`。默认 auto 模式:groq 失败自动降级 openai。
diff --git a/agent_reach/transcribe.py b/agent_reach/transcribe.py
index 2ffd6124..0344a05e 100644
--- a/agent_reach/transcribe.py
+++ b/agent_reach/transcribe.py
@@ -13,11 +13,13 @@ Designed to be importable from channels (e.g. YouTubeChannel.transcribe).
from __future__ import annotations
+import ipaddress
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import List, Optional
+from urllib.parse import urlparse
import requests
@@ -53,6 +55,12 @@ class NoProviderConfigured(TranscribeError):
"""Raised when no provider has an API key configured."""
+_BLOCKED_HOSTS = {
+ "localhost",
+ "metadata.google.internal",
+}
+
+
def _require(binary: str) -> None:
if not shutil.which(binary):
raise MissingDependency(f"{binary} not found in PATH")
@@ -74,8 +82,49 @@ def _run(cmd: List[str], timeout: int = 600) -> None:
)
+def _is_private_ip(value: str) -> bool:
+ try:
+ ip = ipaddress.ip_address(value)
+ except ValueError:
+ return False
+ return any(
+ (
+ ip.is_private,
+ ip.is_loopback,
+ ip.is_link_local,
+ ip.is_reserved,
+ ip.is_multicast,
+ ip.is_unspecified,
+ )
+ )
+
+
+def _assert_safe_public_url(url: str) -> None:
+ """Reject literal local/internal URLs without DNS-resolving public hosts."""
+ if "://" not in url:
+ before_slash = url.split("/", 1)[0]
+ if ":" in before_slash:
+ host_part, port_part = before_slash.rsplit(":", 1)
+ if not host_part or not port_part.isdigit():
+ raise TranscribeError("SSRF blocked: only public http(s) URLs are allowed")
+ parsed = urlparse(f"https://{url}")
+ else:
+ parsed = urlparse(url)
+ if parsed.scheme not in {"http", "https"}:
+ raise TranscribeError("SSRF blocked: only public http(s) URLs are allowed")
+
+ host = (parsed.hostname or "").strip().lower().rstrip(".")
+ if not host:
+ raise TranscribeError("SSRF blocked: URL host is missing")
+ if host in _BLOCKED_HOSTS or host.endswith(".localhost"):
+ raise TranscribeError("SSRF blocked: internal host is not allowed")
+ if _is_private_ip(host):
+ raise TranscribeError("SSRF blocked: private/internal IP is not allowed")
+
+
def download_audio(url: str, out_dir: Path) -> Path:
"""Download audio with yt-dlp into out_dir; return the resulting file path."""
+ _assert_safe_public_url(url)
_require("yt-dlp")
template = out_dir / "source.%(ext)s"
_run(
@@ -88,6 +137,7 @@ def download_audio(url: str, out_dir: Path) -> Path:
"0",
"-o",
str(template),
+ "--",
url,
],
timeout=1800, # long podcasts over slow networks — generous but bounded
@@ -224,7 +274,14 @@ def transcribe(
names = ", ".join(PROVIDERS[p]["key_field"] for p in order)
raise NoProviderConfigured(f"no provider key configured (need one of: {names})")
- work_dir = Path(out_dir) if out_dir else Path(tempfile.mkdtemp(prefix="transcribe-"))
+ if out_dir:
+ return _transcribe_in_dir(source, order, cfg, Path(out_dir))
+
+ with tempfile.TemporaryDirectory(prefix="transcribe-") as tmp:
+ return _transcribe_in_dir(source, order, cfg, Path(tmp))
+
+
+def _transcribe_in_dir(source: str, order: List[str], cfg: Config, work_dir: Path) -> str:
work_dir.mkdir(parents=True, exist_ok=True)
src_path = Path(source)
diff --git a/agent_reach/utils/paths.py b/agent_reach/utils/paths.py
index 850ab7dd..727c70ab 100644
--- a/agent_reach/utils/paths.py
+++ b/agent_reach/utils/paths.py
@@ -1,4 +1,4 @@
-"""Cross-platform path and remediation helpers for yt-dlp."""
+"""Cross-platform path and remediation helpers."""
from __future__ import annotations
@@ -7,6 +7,15 @@ import sys
from pathlib import Path
+def make_private_dir(path: str | Path) -> Path:
+ """Create a directory restricted to the current user where supported."""
+ target = Path(path)
+ target.mkdir(mode=0o700, parents=True, exist_ok=True)
+ if sys.platform != "win32":
+ os.chmod(target, 0o700)
+ return target
+
+
def get_ytdlp_config_dir() -> Path:
"""Return the recommended yt-dlp user config directory for this OS."""
diff --git a/docs/update.md b/docs/update.md
index 79a9bfa6..546a7388 100644
--- a/docs/update.md
+++ b/docs/update.md
@@ -89,9 +89,11 @@ agent-reach version
agent-reach doctor
```
-Running `agent-reach doctor` (text mode) also auto-syncs the bundled skill
-(SKILL.md + references) into every detected agent skill directory — no
-separate skill-update step is needed.
+Running `agent-reach doctor` (text mode) also makes sure an Agent Reach skill
+exists in detected agent skill directories. If the user already has a skill
+there, doctor preserves it instead of overwriting local customizations. Use
+`agent-reach skill --install` when you explicitly want to refresh the bundled
+skill files.
Check the doctor output:
diff --git a/tests/test_channels.py b/tests/test_channels.py
index f6f8aa69..08abe7a8 100644
--- a/tests/test_channels.py
+++ b/tests/test_channels.py
@@ -685,6 +685,35 @@ class TestXueqiuChannel:
cookie_names = {c.name for c in xq_mod._cookie_jar}
assert "xq_a_token" in cookie_names
+ def test_load_cookies_from_browser_rookiepy_path(self, monkeypatch):
+ import sys
+ import types
+
+ import agent_reach.channels.xueqiu as xueqiu_mod
+
+ xueqiu_mod._cookie_jar.clear()
+ fake_rookiepy = types.SimpleNamespace(
+ chrome=lambda domains=None: [
+ {
+ "name": "xq_a_token",
+ "value": "TOKEN_FROM_BROWSER",
+ "domain": ".xueqiu.com",
+ },
+ {
+ "name": "xq_is_login",
+ "value": "1",
+ "domain": ".xueqiu.com",
+ },
+ ]
+ )
+ monkeypatch.setitem(sys.modules, "rookiepy", fake_rookiepy)
+
+ assert xueqiu_mod._load_cookies_from_browser() is True
+ assert any(
+ cookie.name == "xq_a_token" and cookie.value == "TOKEN_FROM_BROWSER"
+ for cookie in xueqiu_mod._cookie_jar
+ )
+
def test_get_json_sends_referer_and_browser_ua(self, monkeypatch):
"""_get_json() must send Referer and a browser-like User-Agent."""
import agent_reach.channels.xueqiu as xueqiu_mod
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 2f91be13..4c26588c 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -11,6 +11,7 @@ import requests
import agent_reach.cli as cli
from agent_reach.cli import main
+from agent_reach.config import Config
class TestCLI:
@@ -35,6 +36,31 @@ class TestCLI:
assert "Agent Reach" in captured.out
assert "✅" in captured.out
+ def test_doctor_preserves_existing_skill_install(self, monkeypatch, tmp_path, capsys):
+ skill_dir = tmp_path / ".agents" / "skills" / "agent-reach"
+ skill_dir.mkdir(parents=True)
+ skill_file = skill_dir / "SKILL.md"
+ custom_content = "# custom Agent Reach skill\n"
+ skill_file.write_text(custom_content, encoding="utf-8")
+
+ monkeypatch.setattr(
+ cli.os.path,
+ "expanduser",
+ lambda p: p.replace("~", str(tmp_path)),
+ )
+ config_dir = tmp_path / ".agent-reach"
+ monkeypatch.setattr(Config, "CONFIG_DIR", config_dir)
+ monkeypatch.setattr(Config, "CONFIG_FILE", config_dir / "config.yaml")
+ monkeypatch.setattr("agent_reach.doctor.check_all", lambda config: {})
+ monkeypatch.setattr("agent_reach.doctor.format_report", lambda results: "report")
+
+ cli._cmd_doctor(Namespace(json=False))
+
+ assert skill_file.read_text(encoding="utf-8") == custom_content
+ out = capsys.readouterr().out
+ assert "preserving existing files" in out
+ assert f"Skill installed for Agent: {skill_dir}" not in out
+
def test_transcribe_command_prints_text(self, capsys):
with patch("agent_reach.transcribe.transcribe", return_value="hello transcript"):
with patch("sys.argv", ["agent-reach", "transcribe", "audio.mp3"]):
diff --git a/tests/test_config.py b/tests/test_config.py
index a7bb2a42..9fe6f196 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -1,12 +1,7 @@
# -*- coding: utf-8 -*-
"""Tests for Agent Reach config module."""
-import os
-import tempfile
-from pathlib import Path
-
import pytest
-import yaml
from agent_reach.config import Config
@@ -21,7 +16,7 @@ def tmp_config(tmp_path):
class TestConfig:
def test_init_creates_dir(self, tmp_path):
config_file = tmp_path / "subdir" / "config.yaml"
- config = Config(config_path=config_file)
+ Config(config_path=config_file)
assert config_file.parent.exists()
def test_set_and_get(self, tmp_config):
@@ -74,6 +69,26 @@ class TestConfig:
assert masked["exa_api_key"] == "super-se..."
assert masked["normal_setting"] == "visible"
+ def test_to_dict_masks_cookie_and_session_credentials(self, tmp_config):
+ secrets = {
+ "twitter_ct0": "csrf-secret-value",
+ "xhs_cookie": "web_session=xhs-secret",
+ "xueqiu_cookie": "xq_a_token=xueqiu-secret",
+ "bilibili_sessdata": "bili-session-secret",
+ "bilibili_csrf": "bili-csrf-secret",
+ "twitter_auth_token": "twitter-auth-secret",
+ }
+ for key, value in secrets.items():
+ tmp_config.set(key, value)
+
+ tmp_config.set("normal_setting", "visible")
+ masked = tmp_config.to_dict()
+
+ dumped = str(masked)
+ for value in secrets.values():
+ assert value not in dumped
+ assert masked["normal_setting"] == "visible"
+
def test_save_creates_file_with_restricted_permissions(self, tmp_path):
import stat
import sys
@@ -86,3 +101,35 @@ class TestConfig:
# File should be owner-only read/write (0o600)
assert not (mode & stat.S_IRGRP), "group read should not be set"
assert not (mode & stat.S_IROTH), "other read should not be set"
+
+ def test_save_tightens_existing_config_file_permissions(self, tmp_path):
+ import os
+ import stat
+ import sys
+
+ config_file = tmp_path / "secure_config.yaml"
+ config_file.write_text("twitter_auth_token: old\n", encoding="utf-8")
+ if sys.platform != "win32":
+ os.chmod(config_file, 0o644)
+
+ config = Config(config_path=config_file)
+ config.set("twitter_auth_token", "new-secret")
+
+ if sys.platform != "win32":
+ mode = config_file.stat().st_mode
+ assert not (mode & stat.S_IRGRP), "group read should be removed"
+ assert not (mode & stat.S_IROTH), "other read should be removed"
+
+ def test_config_dir_has_restricted_permissions(self, tmp_path):
+ import stat
+ import sys
+
+ config_file = tmp_path / "private" / "config.yaml"
+ Config(config_path=config_file)
+
+ if sys.platform != "win32":
+ mode = config_file.parent.stat().st_mode
+ assert not (mode & stat.S_IRGRP), "group read should not be set"
+ assert not (mode & stat.S_IXGRP), "group execute should not be set"
+ assert not (mode & stat.S_IROTH), "other read should not be set"
+ assert not (mode & stat.S_IXOTH), "other execute should not be set"
diff --git a/tests/test_cookie_extract_perms.py b/tests/test_cookie_extract_perms.py
index d40e9ef4..579ca117 100644
--- a/tests/test_cookie_extract_perms.py
+++ b/tests/test_cookie_extract_perms.py
@@ -13,10 +13,10 @@ import os
import stat
import subprocess
import sys
-import tempfile
import pytest
+from agent_reach.cli import _configure_xhs_cookies
from agent_reach.cookie_extract import _sync_bird_env, _sync_xfetch_session
@@ -25,12 +25,28 @@ def _owner_only(path: str) -> bool:
return not (mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH))
+def _owner_only_dir(path: str) -> bool:
+ mode = os.stat(path).st_mode
+ return not (
+ mode
+ & (
+ stat.S_IRGRP
+ | stat.S_IWGRP
+ | stat.S_IXGRP
+ | stat.S_IROTH
+ | stat.S_IWOTH
+ | stat.S_IXOTH
+ )
+ )
+
+
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX perm semantics only")
def test_sync_xfetch_session_writes_0600(tmp_path, monkeypatch):
monkeypatch.setenv("HOME", str(tmp_path))
_sync_xfetch_session("auth_xxx", "ct0_yyy")
session_path = tmp_path / ".config" / "xfetch" / "session.json"
assert session_path.exists(), "expected ~/.config/xfetch/session.json"
+ assert _owner_only_dir(str(session_path.parent)), "xfetch dir must be 0o700"
assert _owner_only(str(session_path)), "session.json must be 0o600"
# Round-trip the content so we know we didn't accidentally corrupt JSON.
data = json.loads(session_path.read_text(encoding="utf-8"))
@@ -38,15 +54,42 @@ def test_sync_xfetch_session_writes_0600(tmp_path, monkeypatch):
assert data["ct0"] == "ct0_yyy"
[email protected](sys.platform == "win32", reason="POSIX perm semantics only")
+def test_sync_xfetch_session_tightens_existing_file(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ session_path = tmp_path / ".config" / "xfetch" / "session.json"
+ session_path.parent.mkdir(parents=True)
+ session_path.write_text('{"authToken": "old"}', encoding="utf-8")
+ os.chmod(session_path, 0o644)
+
+ _sync_xfetch_session("auth_xxx", "ct0_yyy")
+
+ assert _owner_only(str(session_path)), "existing session.json must be tightened"
+
+
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX perm semantics only")
def test_sync_bird_env_writes_0600(tmp_path, monkeypatch):
monkeypatch.setenv("HOME", str(tmp_path))
_sync_bird_env("auth_xxx", "ct0_yyy")
env_path = tmp_path / ".config" / "bird" / "credentials.env"
assert env_path.exists(), "expected ~/.config/bird/credentials.env"
+ assert _owner_only_dir(str(env_path.parent)), "bird dir must be 0o700"
assert _owner_only(str(env_path)), "credentials.env must be 0o600"
[email protected](sys.platform == "win32", reason="POSIX perm semantics only")
+def test_sync_bird_env_tightens_existing_file(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ env_path = tmp_path / ".config" / "bird" / "credentials.env"
+ env_path.parent.mkdir(parents=True)
+ env_path.write_text("AUTH_TOKEN=old\n", encoding="utf-8")
+ os.chmod(env_path, 0o644)
+
+ _sync_bird_env("auth_xxx", "ct0_yyy")
+
+ assert _owner_only(str(env_path)), "existing credentials.env must be tightened"
+
+
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX sh needed for sourcing")
def test_sync_bird_env_quotes_shell_metachars(tmp_path, monkeypatch):
"""Tokens containing ", $, `, ; etc. must not break out of the assignment.
@@ -87,3 +130,22 @@ def test_sync_bird_env_quotes_shell_metachars(tmp_path, monkeypatch):
# And no side-effect files materialised.
assert not pwn_auth.exists()
assert not pwn_ct0.exists()
+
+
[email protected](sys.platform == "win32", reason="POSIX perm semantics only")
+def test_configure_xhs_cookies_tightens_local_fallback_file(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr("shutil.which", lambda name: None if name == "docker" else name)
+
+ cookie_path = tmp_path / ".agent-reach" / "xhs-cookies.json"
+ cookie_path.parent.mkdir()
+ cookie_path.write_text("[]", encoding="utf-8")
+ os.chmod(cookie_path, 0o644)
+
+ _configure_xhs_cookies("web_session=xhs_secret")
+
+ assert _owner_only_dir(str(cookie_path.parent)), "~/.agent-reach must be 0o700"
+ assert _owner_only(str(cookie_path)), "existing xhs-cookies.json must be tightened"
+ data = json.loads(cookie_path.read_text(encoding="utf-8"))
+ assert data[0]["name"] == "web_session"
+ assert data[0]["value"] == "xhs_secret"
diff --git a/tests/test_transcribe.py b/tests/test_transcribe.py
index bf8afdf8..748a8011 100644
--- a/tests/test_transcribe.py
+++ b/tests/test_transcribe.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""Tests for agent_reach.transcribe — provider routing, fallback, and errors."""
+from pathlib import Path
from typing import List
import pytest
@@ -224,6 +225,144 @@ class TestOrchestrator:
with pytest.raises(tr.TranscribeError, match="unknown provider"):
tr.transcribe(str(chunk_file), provider="azure", config=fake_config)
+ def test_auto_temp_dir_is_cleaned_up(self, monkeypatch, fake_config, tmp_path):
+ fake_config.set("groq_api_key", "gsk_test")
+ created_work_dirs = []
+
+ class FakeTemporaryDirectory:
+ def __init__(self, prefix=None):
+ self.path = tmp_path / "auto-work"
+
+ def __enter__(self):
+ self.path.mkdir()
+ created_work_dirs.append(self.path)
+ return str(self.path)
+
+ def __exit__(self, *_):
+ for child in self.path.iterdir():
+ child.unlink()
+ self.path.rmdir()
+
+ def fake_download(source, out_dir):
+ assert Path(out_dir) == tmp_path / "auto-work"
+ audio = Path(out_dir) / "source.m4a"
+ audio.write_bytes(b"audio")
+ return audio
+
+ def fake_compress(src, out_dir):
+ compressed = Path(out_dir) / "compressed.m4a"
+ compressed.write_bytes(b"x" * 1024)
+ return compressed
+
+ monkeypatch.setattr(tr.tempfile, "TemporaryDirectory", FakeTemporaryDirectory)
+ monkeypatch.setattr(tr, "download_audio", fake_download)
+ monkeypatch.setattr(tr, "compress_audio", fake_compress)
+ monkeypatch.setattr(
+ tr.requests,
+ "post",
+ lambda *a, **k: FakeResponse(200, "transcript text"),
+ )
+
+ text = tr.transcribe("https://example.com/video", config=fake_config)
+
+ assert text == "transcript text"
+ assert created_work_dirs
+ assert not created_work_dirs[0].exists()
+
+ def test_explicit_out_dir_is_preserved(self, monkeypatch, fake_config, tmp_path):
+ fake_config.set("groq_api_key", "gsk_test")
+ work = tmp_path / "caller-owned"
+
+ def fake_download(source, out_dir):
+ audio = Path(out_dir) / "source.m4a"
+ audio.write_bytes(b"audio")
+ return audio
+
+ def fake_compress(src, out_dir):
+ compressed = Path(out_dir) / "compressed.m4a"
+ compressed.write_bytes(b"x" * 1024)
+ return compressed
+
+ monkeypatch.setattr(tr, "download_audio", fake_download)
+ monkeypatch.setattr(tr, "compress_audio", fake_compress)
+ monkeypatch.setattr(
+ tr.requests,
+ "post",
+ lambda *a, **k: FakeResponse(200, "transcript text"),
+ )
+
+ tr.transcribe("https://example.com/video", out_dir=work, config=fake_config)
+
+ assert work.exists()
+ assert (work / "compressed.m4a").exists()
+
+
+class TestDownloadAudioSafety:
+ def test_rejects_private_network_url_before_yt_dlp(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(tr, "_require", lambda binary: None)
+
+ def should_not_run(*args, **kwargs):
+ raise AssertionError("yt-dlp must not run for private/internal URLs")
+
+ monkeypatch.setattr(tr, "_run", should_not_run)
+
+ with pytest.raises(tr.TranscribeError, match="private|internal|SSRF"):
+ tr.download_audio("http://169.254.169.254/latest/meta-data/", tmp_path)
+
+ def test_passes_public_url_after_end_of_options_marker(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(tr, "_require", lambda binary: None)
+ captured = {}
+
+ def fake_run(cmd, timeout=600):
+ captured["cmd"] = cmd
+ (tmp_path / "source.m4a").write_bytes(b"audio")
+
+ monkeypatch.setattr(tr, "_run", fake_run)
+
+ audio = tr.download_audio("https://example.com/watch?v=123", tmp_path)
+
+ assert audio == tmp_path / "source.m4a"
+ assert "--" in captured["cmd"]
+ marker_index = captured["cmd"].index("--")
+ assert captured["cmd"][marker_index + 1] == "https://example.com/watch?v=123"
+
+ def test_preserves_bare_public_urls_supported_by_yt_dlp(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(tr, "_require", lambda binary: None)
+ captured = {}
+
+ def fake_run(cmd, timeout=600):
+ captured["cmd"] = cmd
+ (tmp_path / "source.m4a").write_bytes(b"audio")
+
+ monkeypatch.setattr(tr, "_run", fake_run)
+
+ tr.download_audio("youtu.be/abc123", tmp_path)
+
+ assert captured["cmd"][-1] == "youtu.be/abc123"
+
+ def test_does_not_dns_resolve_public_hostnames(self, monkeypatch, tmp_path):
+ import socket
+
+ monkeypatch.setattr(tr, "_require", lambda binary: None)
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("public hostnames should not be DNS-resolved here")
+ ),
+ )
+ captured = {}
+
+ def fake_run(cmd, timeout=600):
+ captured["cmd"] = cmd
+ (tmp_path / "source.m4a").write_bytes(b"audio")
+
+ monkeypatch.setattr(tr, "_run", fake_run)
+
+ tr.download_audio("https://youtu.be/abc123", tmp_path)
+
+ assert captured["cmd"][-1] == "https://youtu.be/abc123"
+
# --- YouTubeChannel integration --------------------------------------- #