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): make diagnostics provably read-only

Pnantb33672608761
diff --git a/agent_reach/backends/opencli.py b/agent_reach/backends/opencli.py
index f7a14c23..5118bed0 100644
--- a/agent_reach/backends/opencli.py
+++ b/agent_reach/backends/opencli.py
@@ -7,8 +7,10 @@ zero per-platform configuration, desktop-only (no headless).
Probing notes (verified live):
- `opencli doctor` AUTO-STARTS the daemon — a side effect, so health
- checks must use `opencli daemon status` (pure query) instead.
- - Exit codes are always 0; status must be parsed from text output.
+ checks must never use it.
+ - Current OpenCLI startup also mutates ``~/.opencli`` before handling
+ ``daemon status``. Only ``--version`` is a side-effect-free CLI fast path;
+ live daemon state is read from its documented loopback ``/status`` API.
- "Extension: disconnected" can mean a sleeping service worker, a disabled
extension, or an extension that was never loaded. Disk files distinguish
possible installation sources, but only a live daemon connection proves
@@ -16,7 +18,9 @@ Probing notes (verified live):
"""
import glob
+import json
import os
+import urllib.request
from dataclasses import dataclass
from agent_reach.probe import probe_command
@@ -43,6 +47,32 @@ _CHROME_PROFILE_ROOTS = (
)
_OPENCLI_UNPACKED_EXTENSION = "~/.opencli/extension"
+_OPENCLI_DAEMON_STATUS_URL = "http://127.0.0.1:19825/status"
+_MAX_DAEMON_STATUS_BYTES = 64 * 1024
+
+
+def _fetch_daemon_status(timeout: int = 2):
+ """Read OpenCLI's loopback status endpoint without starting the CLI."""
+ request = urllib.request.Request(
+ _OPENCLI_DAEMON_STATUS_URL,
+ headers={"X-OpenCLI": "1"},
+ method="GET",
+ )
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ try:
+ with opener.open(request, timeout=min(timeout, 2)) as response:
+ raw = response.read(_MAX_DAEMON_STATUS_BYTES + 1)
+ except Exception:
+ return None
+ if len(raw) > _MAX_DAEMON_STATUS_BYTES:
+ return None
+ try:
+ payload = json.loads(raw.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ return None
+ if not isinstance(payload, dict) or payload.get("ok") is not True:
+ return None
+ return payload
def _extension_installed_on_disk() -> bool:
@@ -118,23 +148,12 @@ def opencli_status(timeout: int = 10) -> OpenCLIStatus:
st = OpenCLIStatus(installed=True, version=version_probe.output.strip())
- daemon_probe = probe_command(
- "opencli",
- ["daemon", "status"],
- timeout=timeout,
- package=OPENCLI_PACKAGE,
- remove_env=_UNSUPPORTED_APP_ENV,
- )
- output = daemon_probe.output if daemon_probe.ok else ""
- # `opencli daemon status` prints lines like:
- # Daemon: running (PID 37389) / Daemon: not running
- # Extension: connected / Extension: disconnected
- for line in output.splitlines():
- line = line.strip().lower()
- if line.startswith("daemon:"):
- st.daemon_running = "not running" not in line and "running" in line
- elif line.startswith("extension:"):
- st.extension_connected = "disconnected" not in line and "connected" in line
+ daemon_status = _fetch_daemon_status(timeout)
+ if daemon_status is not None:
+ st.daemon_running = True
+ st.extension_connected = bool(
+ daemon_status.get("extensionConnected")
+ )
if not st.extension_connected:
st.extension_installed = _extension_installed_on_disk()
diff --git a/agent_reach/channels/_opencli_site.py b/agent_reach/channels/_opencli_site.py
index 52b2aff2..b87ea6f2 100644
--- a/agent_reach/channels/_opencli_site.py
+++ b/agent_reach/channels/_opencli_site.py
@@ -38,10 +38,10 @@ class OpenCLISiteChannel(Channel):
if st.broken:
return "error", st.hint
- self.active_backend = "OpenCLI"
if st.ready:
- return "ok", (
- f"OpenCLI 可用(复用浏览器登录态)。用法:{self.usage}。"
- f"若提示登录,请先在 Chrome 里登录 {self.login_hint}"
+ return "warn", (
+ f"OpenCLI 桥接已连接,但 {self.description} 的登录态和实际命令"
+ "未实时验证;Doctor 不执行平台命令,因此当前不标记为可用。"
+ f"需要时请先在 Chrome 里登录 {self.login_hint}"
)
return "warn", st.hint
diff --git a/agent_reach/channels/bilibili.py b/agent_reach/channels/bilibili.py
index 6d3c0f6c..0d21e184 100644
--- a/agent_reach/channels/bilibili.py
+++ b/agent_reach/channels/bilibili.py
@@ -65,7 +65,7 @@ class BilibiliChannel(Channel):
for wanted in ("ok", "warn"):
for backend, status, message in findings:
if status == wanted:
- self.active_backend = backend
+ self.active_backend = backend if status == "ok" else None
if broken_notes:
message += "\n[备选后端异常] " + ";".join(broken_notes)
return status, message
@@ -103,9 +103,9 @@ class BilibiliChannel(Channel):
if st.broken:
return "error", st.hint
if st.ready:
- return "ok", (
- "OpenCLI 可用(复用浏览器登录态)。用法:"
- "opencli bilibili search/video/subtitle/ranking -f yaml"
+ return "warn", (
+ "OpenCLI 桥接已连接,但 Bilibili 页面、登录态和实际命令"
+ "未实时验证;Doctor 不执行平台命令,因此当前不标记为可用。"
)
return "warn", st.hint
diff --git a/agent_reach/channels/exa_search.py b/agent_reach/channels/exa_search.py
index 456dba02..74427ddc 100644
--- a/agent_reach/channels/exa_search.py
+++ b/agent_reach/channels/exa_search.py
@@ -1,13 +1,10 @@
# -*- coding: utf-8 -*-
"""Exa Search — check if mcporter + Exa MCP is available."""
-from agent_reach.probe import probe_command
+import shutil
from .base import Channel
-from .mcporter import McporterConfigError, configured_server_names
-
-#: mcporter 是 npm 包,断链处方与默认的 pipx/uv 不同
-_MCPORTER_BROKEN_HINT = "mcporter 无法执行(node 环境损坏),重装:\n npm install -g mcporter"
+from .mcporter import McporterConfigError, inspect_mcporter_config
class ExaSearchChannel(Channel):
@@ -21,30 +18,27 @@ class ExaSearchChannel(Channel):
def check(self, config=None):
self.active_backend = None
- probe = probe_command(
- "mcporter",
- ["config", "list", "--json"],
- timeout=10,
- package="mcporter",
- )
- if probe.status == "missing":
+ if not shutil.which("mcporter"):
return "off", (
"需要 mcporter + Exa MCP。安装:\n"
" npm install -g mcporter\n"
- " mcporter config add exa https://mcp.exa.ai/mcp"
+ " mcporter config add exa https://mcp.exa.ai/mcp --scope home"
)
- if probe.status == "broken":
- return "error", _MCPORTER_BROKEN_HINT
- if not probe.ok: # timeout / error
- return "error", f"mcporter 执行异常:{probe.hint or probe.output or probe.status}"
try:
- server_names = configured_server_names(probe.output)
+ inspection = inspect_mcporter_config()
except McporterConfigError as exc:
return "error", f"mcporter 配置检查失败:{exc}"
- if "exa" in server_names:
- self.active_backend = self.backends[0]
- return "ok", "全网语义搜索可用(免费,无需 API Key)"
+ if "exa" in inspection.server_names:
+ return "warn", (
+ "Exa 已写入 mcporter 配置,但 Doctor 未启动远端服务做"
+ "连通验证,不能仅凭配置宣称可用。"
+ )
+ if inspection.imports_unchecked:
+ return "warn", (
+ "mcporter 本地配置未发现 Exa;配置还启用了 editor imports,"
+ "Doctor 为避免扩大凭据读取范围没有展开,当前未验证。"
+ )
return "off", (
"mcporter 已装但 Exa 未配置。运行:\n"
- " mcporter config add exa https://mcp.exa.ai/mcp"
+ " mcporter config add exa https://mcp.exa.ai/mcp --scope home"
)
diff --git a/agent_reach/channels/github.py b/agent_reach/channels/github.py
index 62f695f5..8441fa2c 100644
--- a/agent_reach/channels/github.py
+++ b/agent_reach/channels/github.py
@@ -1,10 +1,96 @@
# -*- coding: utf-8 -*-
"""GitHub — check if gh CLI is available."""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import yaml
+
from agent_reach.probe import probe_command
+from agent_reach.utils.paths import (
+ PrivatePathError,
+ read_small_text_no_follow,
+)
from .base import Channel
+_MAX_HOSTS_BYTES = 1024 * 1024
+_GH_READ_ONLY_ENV = {
+ # gh 2.92 creates ~/.local/state/gh/device-id even for `--version` unless
+ # telemetry is disabled. These are documented gh environment controls.
+ "GH_TELEMETRY": "false",
+ "DO_NOT_TRACK": "true",
+ "GH_NO_UPDATE_NOTIFIER": "1",
+ "GH_NO_EXTENSION_UPDATE_NOTIFIER": "1",
+}
+
+
+class GitHubConfigError(ValueError):
+ """Raised when gh credential metadata cannot be read safely."""
+
+
+def _gh_hosts_path() -> Path:
+ override = os.environ.get("GH_CONFIG_DIR")
+ if override:
+ return Path(os.path.abspath(os.path.expanduser(override))) / "hosts.yml"
+
+ xdg_config = os.environ.get("XDG_CONFIG_HOME")
+ if xdg_config:
+ return Path(xdg_config) / "gh" / "hosts.yml"
+
+ if os.name == "nt":
+ app_data = os.environ.get("APPDATA")
+ if app_data:
+ return Path(app_data) / "GitHub CLI" / "hosts.yml"
+
+ return Path.home() / ".config" / "gh" / "hosts.yml"
+
+
+def _saved_github_host_configured() -> bool:
+ """Inspect github.com's hosts.yml entry without executing gh."""
+ hosts_path = _gh_hosts_path()
+ try:
+ raw = read_small_text_no_follow(
+ hosts_path,
+ max_bytes=_MAX_HOSTS_BYTES,
+ )
+ except (OSError, PrivatePathError, UnicodeError) as exc:
+ raise GitHubConfigError("gh hosts.yml 无法安全读取") from exc
+ if raw is None:
+ return False
+ try:
+ payload = yaml.safe_load(raw)
+ except yaml.YAMLError as exc:
+ raise GitHubConfigError("gh hosts.yml 不是有效的 UTF-8 YAML") from exc
+ if payload is None:
+ return False
+ if not isinstance(payload, dict):
+ raise GitHubConfigError("gh hosts.yml 顶层必须是对象")
+
+ host = payload.get("github.com")
+ if host is None:
+ return False
+ if not isinstance(host, dict):
+ raise GitHubConfigError("gh hosts.yml 的 github.com 配置无效")
+
+ users = host.get("users")
+ if users is not None and not isinstance(users, dict):
+ raise GitHubConfigError("gh hosts.yml 的 users 配置无效")
+ return bool(host.get("oauth_token") or host.get("user") or users)
+
+
+def _explicit_github_credentials(config) -> bool:
+ if any(os.environ.get(name) for name in ("GH_TOKEN", "GITHUB_TOKEN")):
+ return True
+ if config is None:
+ return False
+ try:
+ return bool(config.get("github_token"))
+ except Exception as exc:
+ raise GitHubConfigError("Agent Reach 的 GitHub 配置无法读取") from exc
+
class GitHubChannel(Channel):
name = "github"
@@ -18,26 +104,42 @@ class GitHubChannel(Channel):
return host_matches(url, "github.com")
def check(self, config=None):
- # 真跑 gh auth status 探活。注意:未登录时 rc!=0 是正常业务态(warn),不是 error。
- probe = probe_command("gh", ["auth", "status"], timeout=10, package="gh")
+ self.active_backend = None
+ probe = probe_command(
+ "gh",
+ ["--version"],
+ timeout=10,
+ package="gh",
+ env=_GH_READ_ONLY_ENV,
+ )
if probe.status == "missing":
- self.active_backend = None
return "warn", "gh CLI 未安装。安装:https://cli.github.com"
if probe.status == "broken":
- # gh 是二进制安装(brew/官方包),不是 pip 包——处方不用 pipx/uv 文案
- self.active_backend = None
return "error", (
"gh 命令存在但无法执行——安装已损坏。重装即可修复:\n"
" brew reinstall gh\n"
"或从 https://cli.github.com 重新安装 gh CLI"
)
- if probe.status == "timeout":
- # gh 本体能启动(工具是活的),只是状态检查超时
- self.active_backend = "gh CLI"
- return "warn", "gh CLI 状态检查超时,运行 gh auth status 查看详情"
- if probe.ok:
- self.active_backend = "gh CLI"
- return "ok", "完整可用(读取、搜索、Fork、Issue、PR 等)"
- # rc != 0:gh 活着但未认证(gh auth status 的正常业务态)
- self.active_backend = "gh CLI"
- return "warn", "gh CLI 已安装但未认证。运行 gh auth login 可解锁完整功能"
+ if not probe.ok:
+ detail = probe.hint or probe.status
+ return "error", f"gh CLI 版本检查失败:{detail}"
+
+ try:
+ configured = _explicit_github_credentials(
+ config
+ ) or _saved_github_host_configured()
+ except GitHubConfigError as exc:
+ return "warn", (
+ f"gh CLI 可执行,但认证配置无法安全确认:{exc}。"
+ "Doctor 不执行会写 device-id 的 `gh auth status`,当前未验证。"
+ )
+
+ if configured:
+ return "warn", (
+ "gh CLI 可执行,且检测到显式认证配置;Doctor 不执行会写"
+ " device-id 的 `gh auth status`,因此未实时验证,未标记为可用。"
+ )
+ return "warn", (
+ "gh CLI 可执行,但未检测到显式认证配置。运行 `gh auth login` "
+ "完成登录;Doctor 不会自动执行 `gh auth status`。"
+ )
diff --git a/agent_reach/channels/linkedin.py b/agent_reach/channels/linkedin.py
index d480ae93..88184286 100644
--- a/agent_reach/channels/linkedin.py
+++ b/agent_reach/channels/linkedin.py
@@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-
"""LinkedIn — check if linkedin-scraper-mcp is available."""
-from agent_reach.probe import probe_command
+import shutil
from .base import Channel
-from .mcporter import McporterConfigError, configured_server_names
+from .mcporter import McporterConfigError, inspect_mcporter_config
-#: mcporter 是 npm 包,断链处方与默认的 pipx/uv 不同
-_MCPORTER_BROKEN_HINT = "mcporter 无法执行(node 环境损坏),重装:\n npm install -g mcporter"
_LINKEDIN_SERVER_NAMES = {"linkedin", "linkedin-scraper", "linkedin-scraper-mcp"}
@@ -24,32 +22,31 @@ class LinkedInChannel(Channel):
def check(self, config=None):
self.active_backend = None
- probe = probe_command(
- "mcporter",
- ["config", "list", "--json"],
- timeout=10,
- package="mcporter",
- )
- if probe.status == "missing":
+ if not shutil.which("mcporter"):
return "off", (
"基本内容可通过 Jina Reader 读取。完整功能需要:\n"
" pip install linkedin-scraper-mcp\n"
- " mcporter config add linkedin http://localhost:3000/mcp\n"
+ " mcporter config add linkedin http://localhost:3000/mcp "
+ "--scope home\n"
" 详见 https://github.com/stickerdaniel/linkedin-mcp-server"
)
- if probe.status == "broken":
- return "error", _MCPORTER_BROKEN_HINT
- if not probe.ok: # timeout / error
- return "error", f"mcporter 执行异常:{probe.hint or probe.output or probe.status}"
try:
- server_names = configured_server_names(probe.output)
+ inspection = inspect_mcporter_config()
except McporterConfigError as exc:
return "error", f"mcporter 配置检查失败:{exc}"
- if server_names & _LINKEDIN_SERVER_NAMES:
- self.active_backend = "linkedin-scraper-mcp"
- return "ok", "完整可用(Profile、公司、职位搜索)"
+ if inspection.server_names & _LINKEDIN_SERVER_NAMES:
+ return "warn", (
+ "LinkedIn MCP 已写入 mcporter 配置,但 Doctor 未启动本地"
+ "服务做连通验证,不能仅凭配置宣称完整可用。"
+ )
+ if inspection.imports_unchecked:
+ return "warn", (
+ "mcporter 本地配置未发现 LinkedIn MCP;配置还启用了 editor "
+ "imports,Doctor 为避免扩大凭据读取范围没有展开,当前未验证。"
+ )
return "off", (
"mcporter 已装但 LinkedIn MCP 未配置。运行:\n"
" pip install linkedin-scraper-mcp\n"
- " mcporter config add linkedin http://localhost:3000/mcp"
+ " mcporter config add linkedin http://localhost:3000/mcp "
+ "--scope home"
)
diff --git a/agent_reach/channels/mcporter.py b/agent_reach/channels/mcporter.py
index a9aaab29..0d7ee8a1 100644
--- a/agent_reach/channels/mcporter.py
+++ b/agent_reach/channels/mcporter.py
@@ -1,12 +1,133 @@
-"""Helpers for interpreting mcporter's machine-readable config output."""
+"""Read-only helpers for interpreting mcporter configuration."""
from __future__ import annotations
import json
+import os
+from dataclasses import dataclass
+from pathlib import Path
+
+from agent_reach.utils.paths import (
+ PrivatePathError,
+ read_small_text_no_follow,
+)
+
+_MAX_CONFIG_BYTES = 1024 * 1024
+_MISSING = object()
class McporterConfigError(ValueError):
- """Raised when mcporter's advertised JSON output is not trustworthy."""
+ """Raised when mcporter configuration is not trustworthy."""
+
+
+@dataclass(frozen=True)
+class McporterConfigInspection:
+ """Minimal, non-secret routing facts from one mcporter config layer."""
+
+ server_names: frozenset[str]
+ source: str | None
+ imports_unchecked: bool = False
+
+
+def inspect_mcporter_config(
+ root_dir: str | Path | None = None,
+) -> McporterConfigInspection:
+ """Read the effective local mcporter config without starting mcporter.
+
+ An explicit ``MCPORTER_CONFIG`` is a single layer. Otherwise mcporter
+ 0.7.3 loads the first home config
+ (``~/.mcporter/mcporter.json`` / ``mcporter.jsonc``) and then
+ ``<cwd>/config/mcporter.json``; project entries override duplicate home
+ names. Only exact ``mcpServers`` keys are returned. Editor imports are
+ deliberately not opened because Doctor must not expand its
+ credential-read boundary.
+ """
+ selected_layers = _select_config_layers(root_dir)
+ if not selected_layers:
+ return McporterConfigInspection(frozenset(), None)
+
+ names = set()
+ imports_unchecked = False
+ sources = []
+ for config_path, source in selected_layers:
+ payload = _read_config_object(config_path)
+ servers = payload.get("mcpServers")
+ if not isinstance(servers, dict):
+ raise McporterConfigError("mcporter 配置缺少 mcpServers 对象")
+
+ for name, definition in servers.items():
+ if not isinstance(name, str) or not name.strip():
+ raise McporterConfigError("mcporter 配置包含无效的 server name")
+ if not isinstance(definition, dict):
+ raise McporterConfigError("mcporter server 定义必须是对象")
+ names.add(name.casefold())
+
+ imports = payload.get("imports", _MISSING)
+ if imports is _MISSING:
+ # mcporter defaults to importing supported editor configs when the
+ # key is omitted. Doctor intentionally does not open those files.
+ imports_unchecked = True
+ elif not isinstance(imports, list) or not all(
+ isinstance(item, str) for item in imports
+ ):
+ raise McporterConfigError("mcporter imports 必须是字符串列表")
+ elif imports:
+ imports_unchecked = True
+ sources.append(source)
+
+ return McporterConfigInspection(
+ frozenset(names),
+ "+".join(sources),
+ imports_unchecked=imports_unchecked,
+ )
+
+
+def _select_config_layers(
+ root_dir: str | Path | None,
+) -> list[tuple[Path, str]]:
+ root = Path(os.path.abspath(os.fspath(root_dir or Path.cwd())))
+ explicit = os.environ.get("MCPORTER_CONFIG", "").strip()
+ if explicit:
+ expanded = Path(os.path.expanduser(explicit))
+ if not expanded.is_absolute():
+ expanded = root / expanded
+ return [(Path(os.path.abspath(os.fspath(expanded))), "explicit")]
+
+ layers = []
+ home_base = Path.home() / ".mcporter"
+ for name in ("mcporter.json", "mcporter.jsonc"):
+ candidate = home_base / name
+ if os.path.lexists(candidate):
+ layers.append((candidate, "home"))
+ break
+
+ project_path = root / "config" / "mcporter.json"
+ if os.path.lexists(project_path):
+ layers.append((project_path, "project"))
+ return layers
+
+
+def _read_config_object(config_path: Path) -> dict:
+ try:
+ raw = read_small_text_no_follow(
+ config_path,
+ max_bytes=_MAX_CONFIG_BYTES,
+ )
+ except PrivatePathError as exc:
+ raise McporterConfigError(
+ f"mcporter 配置文件无法安全读取:{exc}"
+ ) from exc
+ except (OSError, UnicodeError) as exc:
+ raise McporterConfigError("mcporter 配置文件无法安全读取") from exc
+ if raw is None:
+ raise McporterConfigError("mcporter 配置文件不存在")
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise McporterConfigError("mcporter 配置不是有效的 UTF-8 JSON") from exc
+ if not isinstance(payload, dict):
+ raise McporterConfigError("mcporter 配置顶层必须是对象")
+ return payload
def configured_server_names(output: str) -> set[str]:
diff --git a/agent_reach/channels/reddit.py b/agent_reach/channels/reddit.py
index 7754074f..c214959a 100644
--- a/agent_reach/channels/reddit.py
+++ b/agent_reach/channels/reddit.py
@@ -11,27 +11,22 @@ logged-in session: OpenCLI reuses the browser's, rdt-cli imports cookies.
import json
import shutil
-import subprocess
+import time
+from pathlib import Path
-from agent_reach.utils.process import utf8_subprocess_env
+from agent_reach.utils.paths import (
+ PrivatePathError,
+ read_small_text_no_follow,
+)
from .base import Channel
_CREDENTIAL_FILE = "~/.config/rdt-cli/credential.json"
+_CREDENTIAL_TTL_SECONDS = 7 * 86400
+_MAX_CREDENTIAL_BYTES = 1024 * 1024
# Pinned to the 0.4.2 state — PyPI still only has 0.4.1 (upstream issue #10).
_RDT_GIT_SOURCE = "git+https://github.com/public-clis/rdt-cli.git@5e4fb3720d5c174e976cd425ccc3b879d52cac66"
-#: shell 对"找到但不可执行/找不到"使用的退出码(对齐 agent_reach.probe)
-_BROKEN_EXIT_CODES = (126, 127)
-
-#: rdt 应从固定 git 源安装(PyPI 落后),断链处方与 probe 默认的 pipx/uv 不同
-_RDT_BROKEN_HINT = (
- "rdt 命令存在但无法执行——通常是系统 Python 升级后 venv 解释器丢失。\n"
- "PyPI 版本落后,推荐用固定 git 源强制重装:\n"
- f" pipx install --force '{_RDT_GIT_SOURCE}'"
-)
-
-
class RedditChannel(Channel):
name = "reddit"
description = "Reddit 帖子和评论"
@@ -60,7 +55,7 @@ class RedditChannel(Channel):
for wanted in ("ok", "warn"):
for backend, status, message in findings:
if status == wanted:
- self.active_backend = backend
+ self.active_backend = backend if status == "ok" else None
return status, message
if findings:
@@ -86,72 +81,64 @@ class RedditChannel(Channel):
if st.broken:
return "error", st.hint
if st.ready:
- return "ok", (
- "OpenCLI 可用(复用浏览器登录态)。用法:"
- "opencli reddit search/read/subreddit/hot -f yaml"
+ return "warn", (
+ "OpenCLI 桥接已连接,但 Reddit 登录态和实际命令未实时验证;"
+ "Doctor 不执行平台命令,因此当前不标记为可用。"
)
return "warn", st.hint
def _check_rdt(self):
- """rdt-cli candidate. None = not installed."""
- rdt = shutil.which("rdt")
- if not rdt:
+ """Inspect rdt's saved credential without invoking its auto-refresh."""
+ if not shutil.which("rdt"):
return None
- # 不走 probe_command:实测 `rdt status --json` 成功时(rc=0)也会向 stderr
- # 打网络重试日志,probe 把 stdout+stderr 合并后 JSON 解析必炸。
- # 故保留手写 subprocess(stdout 单独捕获),但异常分类对齐 probe 语义:
- # exec 失败/126/127 → broken(venv 断链处方),TimeoutExpired → 超时。
+ credential_path = Path.home() / ".config" / "rdt-cli" / "credential.json"
try:
- r = subprocess.run(
- [rdt, "status", "--json"],
- capture_output=True,
- encoding="utf-8",
- errors="replace",
- timeout=10,
- env=utf8_subprocess_env(),
+ payload = read_small_text_no_follow(
+ credential_path,
+ max_bytes=_MAX_CREDENTIAL_BYTES,
+ )
+ except PrivatePathError as exc:
+ return "warn", (
+ f"rdt-cli 已安装,但 credential.json 无法安全读取:{exc}。"
)
- except subprocess.TimeoutExpired:
- return "error", "rdt 响应超时(>10s),Reddit 状态未知。稍后重试或运行 `rdt status` 查看详情"
except OSError:
- # 含 FileNotFoundError:which 命中但 exec 失败 = venv 断链(probe 的 broken)
- return "error", _RDT_BROKEN_HINT
-
- if r.returncode in _BROKEN_EXIT_CODES:
- return "error", _RDT_BROKEN_HINT
-
- if r.returncode != 0:
- detail = (r.stderr or r.stdout or "").strip().splitlines()
- tail = detail[-1] if detail else "无输出"
- return "error", f"rdt 异常退出(exit {r.returncode}):{tail}。运行 `rdt status` 查看详情"
-
- # 进程正常退出 → rdt 本身是活的(无论登录与否)
+ return "warn", (
+ "rdt-cli 已安装,但 credential.json 无法安全读取;"
+ "Doctor 未执行会自动刷新 Cookie 的 `rdt status`。"
+ )
+ if payload is None:
+ return "warn", self._rdt_login_hint()
try:
- data = json.loads(r.stdout or "")
- except json.JSONDecodeError:
- data = None
+ data = json.loads(payload)
+ except (UnicodeError, json.JSONDecodeError, ValueError):
+ return "warn", (
+ "rdt-cli 已安装,但保存的 credential.json 无法安全解析;"
+ "Doctor 未执行会自动刷新 Cookie 的 `rdt status`。"
+ )
if not isinstance(data, dict):
- return "warn", "rdt-cli 可用但状态输出无法解析,运行 `rdt status` 查看登录状态"
-
- info = data.get("data")
- if not isinstance(info, dict):
- info = {}
- authenticated = info.get("authenticated", False)
- username = info.get("username") or ""
-
- if authenticated:
- suffix = f"(已登录:{username})" if username else ""
- return "ok", (
- f"rdt-cli 可用{suffix}(搜索帖子、阅读全文、查看评论;"
- "上游 2026-03 起停更,桌面用户建议迁移到 OpenCLI)"
+ return "warn", self._rdt_login_hint()
+ cookies = data.get("cookies")
+ if not isinstance(cookies, dict) or not cookies.get("reddit_session"):
+ return "warn", self._rdt_login_hint()
+
+ saved_at = data.get("saved_at")
+ if isinstance(saved_at, (int, float)) and (
+ time.time() - saved_at > _CREDENTIAL_TTL_SECONDS
+ ):
+ return "warn", (
+ "rdt-cli 已安装,保存的 Cookie 已超过 7 天;Doctor 不会让"
+ "上游自动读取浏览器或刷新文件,请用 Cookie-Editor 明确更新。"
)
-
return "warn", (
- "rdt-cli 已安装但未登录。Reddit 自 2024 年起要求认证,"
- "未登录时所有请求均返回 403。\n\n"
- "方法一(自动):运行 `rdt login`\n"
- " 先在浏览器登录 reddit.com,再运行此命令自动提取 Cookie。\n\n"
- "方法二(手动,适用于 Chrome/Edge 127+ 无法自动提取时):\n"
+ "rdt-cli 已安装并检测到显式保存的 Reddit Cookie;Doctor 为避免"
+ "上游自动刷新浏览器 Cookie,不执行 `rdt status`,因此未实时验证。"
+ )
+
+ @staticmethod
+ def _rdt_login_hint():
+ return (
+ "rdt-cli 已安装但没有可用的显式 Cookie。请使用 Cookie-Editor:\n"
" 1. Chrome 应用商店安装 Cookie-Editor 扩展:\n"
" https://chromewebstore.google.com/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm\n"
" 2. 在浏览器打开 reddit.com(确保已登录)\n"
@@ -160,5 +147,5 @@ class RedditChannel(Channel):
' {"cookies": {"reddit_session": "<粘贴 Value>"}, '
'"source": "manual", "username": "<你的用户名>", '
'"modhash": null, "saved_at": 0, "last_verified_at": null}\n\n'
- "验证:`rdt status --json` 确认 authenticated: true"
+ "Doctor 不会运行会自动读取浏览器并写文件的 `rdt status`。"
)
diff --git a/agent_reach/channels/twitter.py b/agent_reach/channels/twitter.py
index ebb02d5a..c21e6e78 100644
--- a/agent_reach/channels/twitter.py
+++ b/agent_reach/channels/twitter.py
@@ -2,8 +2,8 @@
"""Twitter/X — check if twitter-cli or bird CLI is available."""
import os
+import shutil
-from agent_reach.probe import probe_command
from agent_reach.utils.url import host_matches
from .base import Channel
@@ -67,7 +67,7 @@ class TwitterChannel(Channel):
for wanted in ("ok", "warn"):
for backend, status, message in findings:
if status == wanted:
- self.active_backend = backend
+ self.active_backend = backend if status == "ok" else None
return status, message
if findings: # 只剩 broken/timeout 候选
@@ -81,43 +81,32 @@ class TwitterChannel(Channel):
)
def _check_twitter_cli(self, config=None):
- """探测 twitter-cli。返回 None 表示未安装,否则返回 (status, message)。
+ """Inspect explicit credentials without starting twitter-cli.
- `twitter status` 才是健康信号:已登录时输出 "ok: true",
- 未登录时以非零退出码输出 "not_authenticated"——工具本身是活的,
- 所以 probe 的 error 状态也要看 output 内容再分类。
+ Upstream ``twitter status`` automatically reads browser cookies when
+ credentials are missing *or invalid*. Doctor cannot disable that
+ fallback, so executing it would violate the Cookie-Editor-only policy.
"""
- probe = probe_command(
- "twitter",
- ["status"],
- timeout=15,
- retries=1,
- package="twitter-cli",
- env=twitter_cli_child_env(config),
- )
- if probe.status == "missing":
+ if not shutil.which("twitter"):
return None
- if probe.status == "broken":
- return "error", "twitter-cli 命令存在但无法执行。\n" + probe.hint
- if probe.status == "timeout":
- return "error", "twitter-cli 健康检查超时(已重试 1 次)。\n" + probe.hint
-
- output = probe.output
- if "ok: true" in output:
- return "ok", (
- "twitter-cli 完整可用(搜索、读推文、时间线、长文/Article、"
- "用户查询、Thread)"
- )
- if "not_authenticated" in output:
+
+ child_env = twitter_cli_child_env(config)
+ auth_token = os.environ.get("TWITTER_AUTH_TOKEN") or child_env.get(
+ "TWITTER_AUTH_TOKEN"
+ )
+ ct0 = os.environ.get("TWITTER_CT0") or child_env.get("TWITTER_CT0")
+ if auth_token and ct0:
return "warn", (
- "twitter-cli 已安装但未认证。设置方式:\n"
- " export TWITTER_AUTH_TOKEN=\"xxx\"\n"
- " export TWITTER_CT0=\"yyy\"\n"
- "或确保已在浏览器中登录 x.com"
+ "twitter-cli 已安装,且 Cookie-Editor 凭据已配置;"
+ "Doctor 不会执行 `twitter status`,因为上游在验证失败时会"
+ "自动读取浏览器 Cookie。请在你明确同意时手动验证。"
)
return "warn", (
- "twitter-cli 已安装但认证检查失败。运行:\n"
- " twitter -v status 查看详细信息"
+ "twitter-cli 已安装但没有完整的显式凭据。请用 Cookie-Editor "
+ "从 x.com 导出后运行:\n"
+ " agent-reach configure twitter-cookies "
+ "'<Cookie-Editor Header String>'\n"
+ "Doctor 不会自动读取浏览器 Cookie。"
)
def _check_opencli(self):
@@ -130,45 +119,25 @@ class TwitterChannel(Channel):
if st.broken:
return "error", st.hint
if st.ready:
- return "ok", (
- "OpenCLI 可用(复用浏览器登录态)。用法:"
- "opencli twitter search/article/user-posts -f yaml"
+ return "warn", (
+ "OpenCLI 桥接已连接,但 Twitter/X 登录态和实际命令未实时验证;"
+ "Doctor 不执行平台命令,因此当前不标记为可用。"
)
return "warn", st.hint
def _check_bird(self):
- """探测 bird/birdx(legacy 回退)。返回 None 表示均未安装,否则返回 (status, message)。"""
- last_failure = None
+ """Inspect legacy bird credentials without launching browser fallback."""
for cmd in ("bird", "birdx"):
- probe = probe_command(
- cmd, ["check"], timeout=15, retries=1, package="@steipete/bird"
- )
- if probe.status == "missing":
+ if not shutil.which(cmd):
continue
- if probe.status == "broken":
- last_failure = (
- "error",
- f"{cmd} 命令存在但无法执行(bird 是 npm 包,可用 "
- "npm install -g @steipete/bird 重装)。\n" + probe.hint,
- )
- continue # bird 坏了再试 birdx
- if probe.status == "timeout":
- last_failure = (
- "error",
- f"{cmd} 健康检查超时(已重试 1 次)。\n" + probe.hint,
- )
- continue
-
- output = probe.output
- if probe.ok:
- return "ok", "bird CLI 可用(读取、搜索推文,含长文/X Article)"
- if "Missing credentials" in output or "missing" in output.lower():
- return "warn", (
- "bird CLI 已安装但未配置认证。设置环境变量:\n"
- " export AUTH_TOKEN=\"xxx\"\n"
- " export CT0=\"yyy\""
+ if os.environ.get("AUTH_TOKEN") and os.environ.get("CT0"):
+ return (
+ "warn",
+ f"{cmd} 已安装且显式环境凭据存在;Doctor 为避免上游"
+ "浏览器 Cookie 回退,不执行 `check`,未实时验证。",
)
return "warn", (
- "bird CLI 已安装但认证检查失败。"
+ f"{cmd} 已安装但未检测到显式 AUTH_TOKEN/CT0;"
+ "仅使用 Cookie-Editor 手动导出的凭据。"
)
- return last_failure
+ return None
diff --git a/agent_reach/channels/xiaohongshu.py b/agent_reach/channels/xiaohongshu.py
index ab651e74..cfd77507 100644
--- a/agent_reach/channels/xiaohongshu.py
+++ b/agent_reach/channels/xiaohongshu.py
@@ -4,19 +4,31 @@
Backend order encodes the recommendation, and probing order makes the
environment split automatic: OpenCLI needs a desktop Chrome so it simply
never probes alive on a server, where xiaohongshu-mcp (self-contained
-headless browser) takes over. xhs-cli (upstream unmaintained since
+headless browser) takes over after an explicit Cookie-Editor import.
+xhs-cli (upstream unmaintained since
2026-03) keeps working for existing installs as the last candidate.
"""
+import json
+import shutil
+import time
import urllib.error
import urllib.request
+from pathlib import Path
-from agent_reach.probe import probe_command
+from agent_reach.backends import opencli_status
+from agent_reach.utils.paths import (
+ PrivatePathError,
+ read_small_text_no_follow,
+)
from .base import Channel
+from .mcporter import McporterConfigError, inspect_mcporter_config
_MCP_ENDPOINT = "http://localhost:18060/mcp"
_MCP_INSTALL_URL = "https://github.com/xpzouying/xiaohongshu-mcp"
+_XHS_COOKIE_TTL_SECONDS = 7 * 86400
+_MAX_XHS_COOKIE_BYTES = 1024 * 1024
def _mcp_service_reachable(timeout: int = 3) -> bool:
@@ -181,7 +193,7 @@ class XiaoHongShuChannel(Channel):
for wanted in ("ok", "warn"):
for backend, status, message in findings:
if status == wanted:
- self.active_backend = backend
+ self.active_backend = backend if status == "ok" else None
return status, message
if findings: # only broken candidates left
@@ -191,22 +203,22 @@ class XiaoHongShuChannel(Channel):
"未安装任何小红书后端。推荐:\n"
" 桌面:agent-reach install --channels opencli\n"
" (复用 Chrome 登录态,刷过小红书即零配置可用)\n"
- f" 服务器:xiaohongshu-mcp(自带无头浏览器+扫码登录):{_MCP_INSTALL_URL}"
+ f" 服务器:xiaohongshu-mcp:{_MCP_INSTALL_URL}\n"
+ " 登录只使用 Cookie-Editor 明确导出:\n"
+ " agent-reach configure xhs-cookies '<Cookie-Editor export>'"
)
def _check_opencli(self):
"""OpenCLI candidate. None = not installed."""
- from agent_reach.backends import opencli_status
-
st = opencli_status()
if not st.installed:
return None
if st.broken:
return "error", st.hint
if st.ready:
- return "ok", (
- "OpenCLI 可用(复用浏览器登录态)。用法:"
- "opencli xiaohongshu search/note/comments/feed -f yaml"
+ return "warn", (
+ "OpenCLI 桥接已连接,但小红书登录态和实际命令未实时验证;"
+ "Doctor 不执行平台命令,因此当前不标记为可用。"
)
return "warn", st.hint
@@ -214,45 +226,79 @@ class XiaoHongShuChannel(Channel):
"""xiaohongshu-mcp candidate. None = service not running."""
if not _mcp_service_reachable():
return None
- mcporter = probe_command(
- "mcporter", ["config", "list"], timeout=10, package="mcporter"
- )
- if mcporter.ok and "xiaohongshu" in mcporter.output:
- return "ok", (
- "xiaohongshu-mcp 服务运行中"
- "(mcporter call 'xiaohongshu.search_feeds(keyword: \"...\")')。"
- "若未登录,让 agent 调 get_login_qrcode 扫码"
+ if not shutil.which("mcporter"):
+ return "warn", (
+ "xiaohongshu-mcp 服务可达,但 mcporter 未安装,Doctor 未接入"
+ "该服务。先安装:npm install -g mcporter"
+ )
+ try:
+ inspection = inspect_mcporter_config()
+ except McporterConfigError as exc:
+ return "error", f"mcporter 配置检查失败:{exc}"
+ if "xiaohongshu" in inspection.server_names:
+ return "warn", (
+ "xiaohongshu-mcp 服务可达且已接入 mcporter,但 Doctor "
+ "未验证登录态,不能据此宣称笔记功能可用。若未登录,用 "
+ "Cookie-Editor 导出后运行 agent-reach configure xhs-cookies"
+ )
+ if inspection.imports_unchecked:
+ return "warn", (
+ "xiaohongshu-mcp 服务可达;mcporter 本地配置未发现"
+ " xiaohongshu,且 editor imports 未展开,Doctor 当前未验证接入。"
)
return "warn", (
"xiaohongshu-mcp 服务在跑但 mcporter 未接入。运行:\n"
- f" mcporter config add xiaohongshu {_MCP_ENDPOINT}"
+ f" mcporter config add xiaohongshu {_MCP_ENDPOINT} --scope home"
)
def _check_xhs_cli(self):
- """Legacy xhs-cli candidate. None = not installed."""
- probe = probe_command(
- "xhs", ["status"], timeout=10, package="xiaohongshu-cli"
- )
- if probe.status == "missing":
+ """Inspect saved xhs-cli cookies without invoking browser extraction."""
+ if not shutil.which("xhs"):
return None
- if probe.status == "broken":
- return "error", "xhs 命令存在但无法执行\n" + probe.hint
- if probe.status == "timeout":
- return "warn", "xhs-cli 已安装但状态检测超时\n" + probe.hint
-
- # 进程是活的(执行成功或运行后非零退出)——按输出内容分类
- if probe.ok and "ok: true" in probe.output:
- return "ok", (
- "xhs-cli 可用(搜索、阅读、评论、热门;上游 2026-03 起停更,"
- "桌面用户建议迁移到 OpenCLI)"
+ cookie_path = Path.home() / ".xiaohongshu-cli" / "cookies.json"
+ try:
+ payload = read_small_text_no_follow(
+ cookie_path,
+ max_bytes=_MAX_XHS_COOKIE_BYTES,
)
- if "not_authenticated" in probe.output or "expired" in probe.output:
+ except PrivatePathError as exc:
return "warn", (
- "xhs-cli 已安装但未登录。运行:\n"
- " xhs login\n"
- "(自动从浏览器提取 Cookie,或扫码登录)"
+ f"xhs-cli 已安装,但 cookies.json 无法安全读取:{exc}。"
)
+ except OSError:
+ return "warn", (
+ "xhs-cli 已安装,但 cookies.json 无法安全读取;"
+ "Doctor 未执行会自动提取浏览器 Cookie 的 `xhs status`。"
+ )
+ if payload is None:
+ return self._xhs_cookie_hint()
+ try:
+ data = json.loads(payload)
+ except (UnicodeError, json.JSONDecodeError, ValueError):
+ return "warn", (
+ "xhs-cli 已安装,但保存的 cookies.json 无法安全解析;"
+ "Doctor 未执行会自动提取浏览器 Cookie 的 `xhs status`。"
+ )
+ if not isinstance(data, dict) or not data.get("a1"):
+ return self._xhs_cookie_hint()
+ saved_at = data.get("saved_at")
+ if isinstance(saved_at, (int, float)) and (
+ time.time() - saved_at > _XHS_COOKIE_TTL_SECONDS
+ ):
+ return "warn", (
+ "xhs-cli 已安装,保存的 Cookie 已超过 7 天;Doctor 不会让"
+ "上游自动读取浏览器或刷新文件,请用 Cookie-Editor 明确更新。"
+ )
+ return "warn", (
+ "xhs-cli 已安装并检测到显式保存的 Cookie;Doctor 为避免上游"
+ "自动读取浏览器或改写 Cookie,不执行 `xhs status`,未实时验证。"
+ )
+
+ @staticmethod
+ def _xhs_cookie_hint():
return "warn", (
- "xhs-cli 已安装但状态异常。运行:\n"
- " xhs -v status 查看详细信息"
+ "xhs-cli 已安装但没有可用的显式 Cookie。不要运行会自动读取"
+ "浏览器的 `xhs login/status`;请迁移到 xiaohongshu-mcp,"
+ "再用 Cookie-Editor 导出并运行 "
+ "agent-reach configure xhs-cookies。"
)
diff --git a/agent_reach/channels/xueqiu.py b/agent_reach/channels/xueqiu.py
index 1e65d866..0fc752d7 100644
--- a/agent_reach/channels/xueqiu.py
+++ b/agent_reach/channels/xueqiu.py
@@ -56,12 +56,12 @@ def _inject_cookie_string(cookie_str: str) -> None:
_cookie_jar.set_cookie(cookie)
-def _load_cookies_from_config() -> bool:
+def _load_cookies_from_config(config=None) -> bool:
"""Try to load Xueqiu cookies from agent-reach config file (xueqiu_cookie key)."""
try:
from ..config import Config
- cfg = Config()
+ cfg = config if config is not None else Config(read_only=True)
cookie_str = cfg.get("xueqiu_cookie")
if not cookie_str:
return False
@@ -71,7 +71,7 @@ def _load_cookies_from_config() -> bool:
return False
-def _ensure_cookies() -> None:
+def _ensure_cookies(config=None) -> None:
"""Populate session cookies without touching browser credential stores.
Priority order:
@@ -82,7 +82,7 @@ def _ensure_cookies() -> None:
global _cookies_initialized
if _cookies_initialized:
return
- if _load_cookies_from_config():
+ if _load_cookies_from_config(config):
_cookies_initialized = True
return
# Fallback: visit homepage to pick up acw_tc anti-DDoS cookie.
@@ -93,9 +93,9 @@ def _ensure_cookies() -> None:
_cookies_initialized = True
-def _get_json(url: str) -> Any:
+def _get_json(url: str, config=None) -> Any:
"""Fetch *url* with Xueqiu session cookies and return parsed JSON."""
- _ensure_cookies()
+ _ensure_cookies(config)
req = urllib.request.Request(
url, headers={"User-Agent": _UA, "Referer": _REFERER}
)
@@ -135,7 +135,8 @@ class XueqiuChannel(Channel):
try:
data = _get_json(
"https://stock.xueqiu.com/v5/stock/quote.json"
- "?symbol=SH601138&extend=detail"
+ "?symbol=SH601138&extend=detail",
+ config,
)
quote = (data.get("data") or {}).get("quote") or {}
if quote:
diff --git a/agent_reach/config.py b/agent_reach/config.py
index e34c7882..879781c1 100644
--- a/agent_reach/config.py
+++ b/agent_reach/config.py
@@ -13,7 +13,14 @@ from typing import Any, Optional
import yaml
-from agent_reach.utils.paths import make_private_dir
+from agent_reach.utils.paths import (
+ PrivatePathError,
+ ensure_no_symlink_path,
+ make_private_dir,
+ read_small_text_no_follow,
+)
+
+_MAX_CONFIG_BYTES = 1024 * 1024
class ConfigError(RuntimeError):
@@ -29,8 +36,10 @@ class ConfigSecurityError(ConfigError):
def _reject_symlink(path: Path, label: str) -> None:
- if path.is_symlink():
- raise ConfigSecurityError(f"{label}不能是符号链接:{path}")
+ try:
+ ensure_no_symlink_path(path, label)
+ except PrivatePathError as exc:
+ raise ConfigSecurityError(str(exc)) from exc
def _atomic_write_yaml(target: Path, data: dict) -> None:
@@ -123,20 +132,21 @@ class Config:
"""Load config from YAML file."""
_reject_symlink(self.config_dir, "配置目录")
_reject_symlink(self.config_path, "配置文件")
- if self.config_path.exists():
- flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
- try:
- fd = os.open(self.config_path, flags)
- except OSError as exc:
- if self.config_path.is_symlink():
- raise ConfigSecurityError(
- f"配置文件不能是符号链接:{self.config_path}"
- ) from exc
- raise
- with os.fdopen(fd, "r", encoding="utf-8") as handle:
- self.data = yaml.safe_load(handle) or {}
- else:
+ try:
+ payload = read_small_text_no_follow(
+ self.config_path,
+ max_bytes=_MAX_CONFIG_BYTES,
+ )
+ except PrivatePathError as exc:
+ raise ConfigSecurityError(str(exc)) from exc
+ if payload is None:
self.data = {}
+ return
+
+ loaded = yaml.safe_load(payload) or {}
+ if not isinstance(loaded, dict):
+ raise ConfigError("配置文件顶层必须是对象")
+ self.data = loaded
def save(self):
"""Save config atomically, refusing mutation in read-only mode."""
diff --git a/agent_reach/doctor.py b/agent_reach/doctor.py
index 6060f877..9ee98cf2 100644
--- a/agent_reach/doctor.py
+++ b/agent_reach/doctor.py
@@ -5,8 +5,12 @@ Each channel knows how to check itself. Doctor just collects the results.
"""
from typing import Dict
-from agent_reach.config import Config
+
+from rich.markup import escape
+
from agent_reach.channels import get_all_channels
+from agent_reach.config import Config
+from agent_reach.utils.text import scrub_url_credentials
def check_all(config: Config) -> Dict[str, dict]:
@@ -23,7 +27,13 @@ def check_all(config: Config) -> Dict[str, dict]:
except Exception as e: # noqa: BLE001 — doctor must survive any channel
# Channels are registry singletons: a stale active_backend from a
# previous check must not leak into an errored result.
- status, message, active = "error", f"体检异常:{e}", None
+ status = "error"
+ message = f"体检异常:{e}"
+ active = None
+ # Doctor is the final output boundary for both expected channel
+ # messages and unexpected exceptions. Upstream probe output can echo a
+ # configured URL, so scrub every path before JSON/text rendering.
+ message = scrub_url_credentials(message)
results[ch.name] = {
"status": status,
"name": ch.description,
@@ -46,11 +56,6 @@ def _name_msg(r: dict, escape) -> str:
def format_report(results: Dict[str, dict]) -> str:
"""Format results as a readable text report (with Rich markup)."""
- try:
- from rich.markup import escape
- except ImportError:
- escape = lambda x: x
-
lines = []
lines.append("[bold cyan]Agent Reach 状态[/bold cyan]")
lines.append("[cyan]" + "=" * 40 + "[/cyan]")
@@ -107,7 +112,6 @@ def format_report(results: Dict[str, dict]) -> str:
)
# Security check: config file permissions (Unix only)
- import os
import stat
import sys
diff --git a/agent_reach/integrations/mcp_server.py b/agent_reach/integrations/mcp_server.py
index bace664c..8452ef5f 100644
--- a/agent_reach/integrations/mcp_server.py
+++ b/agent_reach/integrations/mcp_server.py
@@ -14,11 +14,13 @@ import sys
from agent_reach.config import Config
from agent_reach.core import AgentReach
+from agent_reach.utils.text import scrub_url_credentials
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
- from mcp.types import Tool, TextContent
+ from mcp.types import TextContent, Tool
+
HAS_MCP = True
except ImportError:
HAS_MCP = False
@@ -30,7 +32,7 @@ def create_server():
sys.exit(1)
server = Server("agent-reach")
- config = Config()
+ config = Config(read_only=True)
eyes = AgentReach(config)
@server.list_tools()
@@ -52,7 +54,12 @@ def create_server():
text = json.dumps(result, ensure_ascii=False, indent=2) if isinstance(result, (dict, list)) else str(result)
return [TextContent(type="text", text=text)]
except Exception as e:
- return [TextContent(type="text", text=f"Error: {str(e)}")]
+ return [
+ TextContent(
+ type="text",
+ text=f"Error: {scrub_url_credentials(e)}",
+ )
+ ]
return server
diff --git a/agent_reach/utils/paths.py b/agent_reach/utils/paths.py
index 8344a9c6..bf0af68b 100644
--- a/agent_reach/utils/paths.py
+++ b/agent_reach/utils/paths.py
@@ -4,30 +4,179 @@ from __future__ import annotations
import os
import shlex
+import stat
import sys
+import tempfile
from pathlib import Path
+class PrivatePathError(RuntimeError):
+ """Raised when a private write could be redirected through a symlink."""
+
+
+def ensure_no_symlink_path(path: str | Path, label: str = "路径") -> Path:
+ """Reject any existing symlink component without resolving the path."""
+ target = Path(path)
+ absolute = Path(os.path.abspath(os.fspath(target)))
+ current = Path(absolute.anchor)
+ for part in absolute.parts[1:]:
+ current /= part
+ try:
+ mode = os.lstat(current).st_mode
+ except FileNotFoundError:
+ continue
+ if stat.S_ISLNK(mode):
+ raise PrivatePathError(f"{label}不能经过符号链接:{current}")
+ return target
+
+
def make_private_dir(path: str | Path) -> Path:
"""Create a directory restricted to the current user where supported."""
- target = Path(path)
+ target = ensure_no_symlink_path(path, "私密目录")
target.mkdir(mode=0o700, parents=True, exist_ok=True)
+ ensure_no_symlink_path(target, "私密目录")
if sys.platform != "win32":
- os.chmod(target, 0o700)
+ flags = (
+ os.O_RDONLY
+ | getattr(os, "O_DIRECTORY", 0)
+ | getattr(os, "O_NOFOLLOW", 0)
+ )
+ dir_fd = os.open(target, flags)
+ try:
+ ensure_no_symlink_path(target, "私密目录")
+ if hasattr(os, "fchmod"):
+ os.fchmod(dir_fd, 0o700)
+ finally:
+ os.close(dir_fd)
return target
+def atomic_write_private_text(
+ path: str | Path,
+ text: str,
+ *,
+ encoding: str = "utf-8",
+) -> Path:
+ """Atomically replace a private text file without following symlinks.
+
+ The parent is owner-only, the temporary file is created beside the target
+ with mode ``0o600``, and both the parent and target are checked before the
+ final rename. ``os.replace`` replaces a late target symlink itself rather
+ than following it into another file.
+ """
+ target = Path(path)
+ parent = target.parent
+ ensure_no_symlink_path(parent, "父目录")
+ make_private_dir(parent)
+ ensure_no_symlink_path(parent, "父目录")
+ ensure_no_symlink_path(target, "目标文件")
+
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(parent),
+ prefix=f".{target.name}.",
+ suffix=".tmp",
+ )
+ tmp_path = Path(tmp_name)
+ try:
+ if os.name != "nt" and hasattr(os, "fchmod"):
+ os.fchmod(fd, stat.S_IRUSR | stat.S_IWUSR)
+ handle = os.fdopen(fd, "w", encoding=encoding)
+ fd = -1
+ with handle:
+ handle.write(text)
+ handle.flush()
+ os.fsync(handle.fileno())
+
+ ensure_no_symlink_path(parent, "父目录")
+ ensure_no_symlink_path(target, "目标文件")
+ os.replace(tmp_path, target)
+
+ if os.name != "nt" and hasattr(os, "O_DIRECTORY"):
+ try:
+ dir_fd = os.open(
+ parent,
+ os.O_RDONLY
+ | os.O_DIRECTORY
+ | getattr(os, "O_NOFOLLOW", 0),
+ )
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
+ except OSError:
+ pass
+ except BaseException:
+ if fd >= 0:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ try:
+ tmp_path.unlink(missing_ok=True)
+ except OSError:
+ pass
+ raise
+ return target
+
+
+def read_small_text_no_follow(
+ path: str | Path,
+ *,
+ max_bytes: int,
+ encoding: str = "utf-8",
+) -> str | None:
+ """Read a bounded regular file while refusing every symlink component."""
+ if max_bytes < 0:
+ raise ValueError("max_bytes must be non-negative")
+
+ target = ensure_no_symlink_path(path, "读取路径")
+ flags = (
+ os.O_RDONLY
+ | getattr(os, "O_NOFOLLOW", 0)
+ | getattr(os, "O_NONBLOCK", 0)
+ | getattr(os, "O_CLOEXEC", 0)
+ )
+ try:
+ fd = os.open(target, flags)
+ except FileNotFoundError:
+ return None
+
+ try:
+ file_stat = os.fstat(fd)
+ if not stat.S_ISREG(file_stat.st_mode):
+ raise PrivatePathError(f"读取目标不是常规文件:{target}")
+ if file_stat.st_size > max_bytes:
+ raise PrivatePathError(f"读取目标超过大小上限:{target}")
+
+ chunks = []
+ remaining = max_bytes + 1
+ while remaining:
+ chunk = os.read(fd, remaining)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ payload = b"".join(chunks)
+ if len(payload) > max_bytes:
+ raise PrivatePathError(f"读取目标超过大小上限:{target}")
+ ensure_no_symlink_path(target, "读取路径")
+ finally:
+ os.close(fd)
+ return payload.decode(encoding)
+
+
def get_ytdlp_config_dir() -> Path:
- """Return the recommended yt-dlp user config directory for this OS."""
+ """Return yt-dlp's first user config directory.
- if sys.platform == "win32":
- appdata = os.environ.get("APPDATA")
- if appdata:
- return Path(appdata) / "yt-dlp"
- return Path.home() / "AppData" / "Roaming" / "yt-dlp"
- if sys.platform == "darwin":
- return Path.home() / "Library" / "Application Support" / "yt-dlp"
- return Path.home() / ".config" / "yt-dlp"
+ yt-dlp checks ``$XDG_CONFIG_HOME/yt-dlp`` first on every supported
+ platform, falling back to ``~/.config/yt-dlp`` when the variable is not
+ set. Writing anywhere else can make Agent Reach and Doctor agree with each
+ other while the real yt-dlp process silently ignores the setting.
+ """
+
+ xdg_config_home = os.environ.get("XDG_CONFIG_HOME")
+ config_home = Path(xdg_config_home) if xdg_config_home else Path.home() / ".config"
+ return config_home / "yt-dlp"
def get_ytdlp_config_path() -> Path:
diff --git a/agent_reach/utils/url.py b/agent_reach/utils/url.py
index e1cfd354..b31f6e82 100644
--- a/agent_reach/utils/url.py
+++ b/agent_reach/utils/url.py
@@ -27,6 +27,10 @@ def host_matches(url: str, *domains: str) -> bool:
try:
parsed = urlsplit(url)
host = (parsed.hostname or "").lower().rstrip(".")
+ # ``hostname`` is permissive: malformed or out-of-range ports only
+ # raise when ``port`` is accessed. Force that validation here so
+ # hostile authorities fail closed.
+ _ = parsed.port
except (TypeError, ValueError):
return False
diff --git a/tests/conftest.py b/tests/conftest.py
index e64e293b..1d0f1704 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -22,3 +22,14 @@ def isolated_home(tmp_path, monkeypatch):
monkeypatch.setattr(Config, "CONFIG_DIR", config_dir)
monkeypatch.setattr(Config, "CONFIG_FILE", config_dir / "config.yaml")
return home
+
+
[email protected](autouse=True)
+def isolated_xueqiu_cookie_jar(monkeypatch):
+ """Prevent the module-level Xueqiu session from leaking between tests."""
+ from agent_reach.channels import xueqiu
+
+ xueqiu._cookie_jar.clear()
+ monkeypatch.setattr(xueqiu, "_cookies_initialized", False)
+ yield
+ xueqiu._cookie_jar.clear()
diff --git a/tests/test_channels.py b/tests/test_channels.py
index ff5c3e94..0897559c 100644
--- a/tests/test_channels.py
+++ b/tests/test_channels.py
@@ -6,8 +6,11 @@ import shutil
import subprocess
from urllib.error import URLError
+import pytest
+
from agent_reach.backends import OpenCLIStatus
from agent_reach.channels import get_all_channels, get_channel
+from agent_reach.channels.bilibili import BilibiliChannel
from agent_reach.channels.facebook import FacebookChannel
from agent_reach.channels.instagram import InstagramChannel
from agent_reach.channels.v2ex import V2EXChannel
@@ -51,7 +54,9 @@ class TestOpenCLISiteChannels:
assert ch.can_handle("https://instagr.am/p/abc123/")
assert not ch.can_handle("https://facebook.com/openai")
- def test_opencli_ready_reports_ok(self, monkeypatch):
+ def test_opencli_bridge_ready_is_unverified_for_login_platform(
+ self, monkeypatch
+ ):
monkeypatch.setattr(
"agent_reach.backends.opencli_status",
lambda: OpenCLIStatus(
@@ -62,11 +67,19 @@ class TestOpenCLISiteChannels:
)
ch = FacebookChannel()
status, msg = ch.check()
- assert status == "ok"
- assert ch.active_backend == "OpenCLI"
- assert "opencli facebook search/profile/feed/groups -f yaml" in msg
+ assert status == "warn"
+ assert ch.active_backend is None
+ assert "桥接已连接" in msg
+ assert "登录态和实际命令未实时验证" in msg
assert "facebook.com" in msg
+ instagram = InstagramChannel()
+ status, msg = instagram.check()
+ assert status == "warn"
+ assert instagram.active_backend is None
+ assert "桥接已连接" in msg
+ assert "instagram.com" in msg
+
def test_opencli_missing_reports_off(self, monkeypatch):
monkeypatch.setattr(
"agent_reach.backends.opencli_status",
@@ -90,7 +103,7 @@ class TestOpenCLISiteChannels:
ch = InstagramChannel()
status, msg = ch.check()
assert status == "warn"
- assert ch.active_backend == "OpenCLI"
+ assert ch.active_backend is None
assert "Chrome 扩展" in msg
@@ -137,6 +150,46 @@ class TestV2EXChannel:
assert status == "warn"
assert "失败" in msg
+ def test_check_passes_its_read_only_config_to_cookie_loading(self, monkeypatch):
+ """Doctor's config object must flow through instead of reopening config."""
+ import agent_reach.channels.xueqiu as xueqiu_mod
+
+ supplied_config = object()
+ observed = []
+ monkeypatch.setattr(xueqiu_mod, "_cookies_initialized", False)
+
+ def fake_load(config=None):
+ observed.append(config)
+ return False
+
+ fake_response_data = {
+ "data": {"quote": {"symbol": "SH601138", "current": 52.0}}
+ }
+
+ class FakeResponse:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_):
+ pass
+
+ def read(self):
+ return json.dumps(fake_response_data).encode()
+
+ monkeypatch.setattr(
+ xueqiu_mod, "_load_cookies_from_config", fake_load
+ )
+ monkeypatch.setattr(
+ xueqiu_mod._opener,
+ "open",
+ lambda req, timeout=None: FakeResponse(),
+ )
+
+ status, _ = XueqiuChannel().check(supplied_config)
+
+ assert status == "ok"
+ assert observed == [supplied_config]
+
# ------------------------------------------------------------------ #
# get_hot_topics
# ------------------------------------------------------------------ #
@@ -670,7 +723,12 @@ class TestXueqiuChannel:
monkeypatch.setattr(
xq_mod,
"_load_cookies_from_config",
- lambda: (xq_mod._inject_cookie_string("xq_a_token=TESTTOKEN; xq_is_login=1") or True),
+ lambda config=None: (
+ xq_mod._inject_cookie_string(
+ "xq_a_token=TESTTOKEN; xq_is_login=1"
+ )
+ or True
+ ),
)
# Patch opener so no real HTTP call is made
@@ -690,7 +748,11 @@ class TestXueqiuChannel:
import agent_reach.channels.xueqiu as xueqiu_mod
monkeypatch.setattr(xueqiu_mod, "_cookies_initialized", False)
- monkeypatch.setattr(xueqiu_mod, "_load_cookies_from_config", lambda: False)
+ monkeypatch.setattr(
+ xueqiu_mod,
+ "_load_cookies_from_config",
+ lambda config=None: False,
+ )
requested = []
class FakeResponse:
@@ -701,8 +763,6 @@ class TestXueqiuChannel:
"open",
lambda req, timeout=None: requested.append(req.full_url) or FakeResponse(),
)
- assert {cookie.name for cookie in xueqiu_mod._cookie_jar} == {"xq_a_token"}
-
xueqiu_mod._ensure_cookies()
assert requested == ["https://xueqiu.com"]
@@ -762,98 +822,47 @@ class TestRedditChannel:
assert status == "ok"
assert ch.active_backend == "OpenCLI"
- def test_reports_ok_when_authenticated(self, monkeypatch):
+ def test_saved_rdt_cookie_is_unverified_not_active(
+ self, monkeypatch, isolated_home
+ ):
self._isolate(monkeypatch)
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/rdt")
- fake_output = json.dumps({
- "ok": True,
- "schema_version": "1",
- "data": {"authenticated": True, "username": "testuser", "cookie_count": 1},
- })
-
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, fake_output, "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
+ credential_path = (
+ isolated_home / ".config" / "rdt-cli" / "credential.json"
+ )
+ credential_path.parent.mkdir(parents=True)
+ credential_path.write_text(
+ json.dumps(
+ {
+ "cookies": {"reddit_session": "explicit"},
+ "saved_at": __import__("time").time(),
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute rdt status"
+ ),
+ )
from agent_reach.channels.reddit import RedditChannel
ch = RedditChannel()
status, msg = ch.check()
- assert status == "ok"
- assert "testuser" in msg
- assert ch.active_backend == "rdt-cli"
+ assert status == "warn"
+ assert "未实时验证" in msg
+ assert ch.active_backend is None
- def test_reports_warn_when_not_authenticated(self, monkeypatch):
+ def test_reports_warn_when_cookie_is_missing(self, monkeypatch):
self._isolate(monkeypatch)
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/rdt")
- fake_output = json.dumps({
- "ok": True,
- "schema_version": "1",
- "data": {"authenticated": False, "username": None, "cookie_count": 0},
- })
-
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, fake_output, "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.reddit import RedditChannel
ch = RedditChannel()
status, msg = ch.check()
assert status == "warn"
- assert "403" in msg
- assert "rdt login" in msg
assert "Cookie-Editor" in msg
assert "chromewebstore.google.com" in msg
- # 未登录是业务态:进程活着,后端仍然算可用
- assert ch.active_backend == "rdt-cli"
-
- def test_reports_error_when_status_check_fails(self, monkeypatch):
- """rdt 非零退出且输出不可解析 → 工具异常(error),不再算 warn。"""
- self._isolate(monkeypatch)
- monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/rdt")
-
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 1, "not valid json{{{", "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
- from agent_reach.channels.reddit import RedditChannel
- ch = RedditChannel()
- status, msg = ch.check()
- assert status == "error"
- assert "rdt 异常退出" in msg
- assert ch.active_backend is None
-
- def test_reports_error_with_reinstall_hint_when_broken(self, monkeypatch):
- """which 命中但 exec 抛 FileNotFoundError(venv 断链)→ error + 重装处方。"""
- self._isolate(monkeypatch)
- monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/rdt")
-
- def fake_run(cmd, **kwargs):
- raise FileNotFoundError("/usr/local/bin/rdt")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
- from agent_reach.channels.reddit import RedditChannel
- ch = RedditChannel()
- status, msg = ch.check()
- assert status == "error"
- assert "无法执行" in msg
- assert "pipx install --force" in msg # rdt 专用 git 源重装处方
- assert "git+https://github.com/public-clis/rdt-cli.git" in msg
- assert ch.active_backend is None
-
- def test_reports_error_with_reinstall_hint_on_exit_127(self, monkeypatch):
- """退出码 127(找到但跑不动)同样按断链处理。"""
- self._isolate(monkeypatch)
- monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/rdt")
-
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 127, "", "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
- from agent_reach.channels.reddit import RedditChannel
- ch = RedditChannel()
- status, msg = ch.check()
- assert status == "error"
- assert "pipx install --force" in msg
assert ch.active_backend is None
def test_can_handle_reddit_urls(self):
@@ -883,20 +892,69 @@ class TestXiaoHongShuChannel:
xhs_mod, "_mcp_service_reachable", lambda timeout=3: mcp_reachable
)
- def test_reports_ok_when_cli_authenticated(self, monkeypatch):
- self._isolate(monkeypatch)
- monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/xhs")
+ def test_opencli_bridge_ready_is_unverified(self, monkeypatch):
+ monkeypatch.setattr(
+ "agent_reach.backends.opencli_status",
+ lambda: OpenCLIStatus(
+ installed=True,
+ extension_connected=True,
+ version="1.8.6",
+ ),
+ )
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, "ok: true\nusername: testuser\n", "")
+ status, message = XiaoHongShuChannel()._check_opencli()
- monkeypatch.setattr(subprocess, "run", fake_run)
+ assert status == "warn"
+ assert "桥接已连接" in message
+ assert "登录态和实际命令未实时验证" in message
+
+ def test_saved_cli_cookie_is_unverified_not_active(
+ self, monkeypatch, isolated_home
+ ):
+ self._isolate(monkeypatch)
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/xhs")
+ cookie_path = isolated_home / ".xiaohongshu-cli" / "cookies.json"
+ cookie_path.parent.mkdir()
+ cookie_path.write_text(
+ json.dumps(
+ {"a1": "explicit", "saved_at": __import__("time").time()}
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute xhs status"
+ ),
+ )
ch = XiaoHongShuChannel()
status, msg = ch.check()
- assert status == "ok"
- assert "xhs-cli 可用" in msg
- assert ch.active_backend == "xhs-cli (xiaohongshu-cli)"
+ assert status == "warn"
+ assert "未实时验证" in msg
+ assert ch.active_backend is None
+
+ def test_saved_cli_cookie_refuses_ancestor_symlink(
+ self, monkeypatch, isolated_home
+ ):
+ self._isolate(monkeypatch)
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/xhs")
+ victim_dir = isolated_home / "victim-xhs"
+ victim_dir.mkdir()
+ (victim_dir / "cookies.json").write_text(
+ json.dumps({"a1": "do-not-read"}),
+ encoding="utf-8",
+ )
+ (isolated_home / ".xiaohongshu-cli").symlink_to(
+ victim_dir,
+ target_is_directory=True,
+ )
+
+ status, message = XiaoHongShuChannel()._check_xhs_cli()
+
+ assert status == "warn"
+ assert "符号链接" in message
def test_reports_warn_when_not_authenticated(self, monkeypatch):
self._isolate(monkeypatch)
@@ -910,9 +968,9 @@ class TestXiaoHongShuChannel:
ch = XiaoHongShuChannel()
status, msg = ch.check()
assert status == "warn"
- assert "xhs login" in msg
- # 未登录是业务态:工具进程活着,后端仍可用
- assert ch.active_backend == "xhs-cli (xiaohongshu-cli)"
+ assert "Cookie-Editor" in msg
+ assert "configure xhs-cookies" in msg
+ assert ch.active_backend is None
def test_reports_off_when_nothing_installed(self, monkeypatch):
self._isolate(monkeypatch)
@@ -925,24 +983,6 @@ class TestXiaoHongShuChannel:
assert "xiaohongshu-mcp" in msg
assert ch.active_backend is None
- def test_reports_error_with_reinstall_hint_when_broken(self, monkeypatch):
- """which 命中但 exec 抛 FileNotFoundError(venv 断链)→ error + 重装处方。"""
- self._isolate(monkeypatch)
- monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/xhs")
-
- def fake_run(cmd, **kwargs):
- raise FileNotFoundError("/usr/local/bin/xhs")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
-
- ch = XiaoHongShuChannel()
- status, msg = ch.check()
- assert status == "error"
- assert "无法执行" in msg
- assert "uv tool install --force xiaohongshu-cli" in msg
- assert "pipx reinstall xiaohongshu-cli" in msg
- assert ch.active_backend is None
-
def test_opencli_ready_wins_over_cli(self, monkeypatch):
"""OpenCLI 完整可用时按序获胜,即使 xhs-cli 也完整可用。"""
self._isolate(monkeypatch, opencli=("ok", "OpenCLI 可用(复用浏览器登录态)"))
@@ -958,8 +998,9 @@ class TestXiaoHongShuChannel:
assert status == "ok"
assert ch.active_backend == "OpenCLI"
- def test_opencli_warn_loses_to_usable_cli(self, monkeypatch):
- """OpenCLI 装了但扩展未连(warn)时,完整可用的 xhs-cli 获胜。"""
+ def test_opencli_warn_remains_first_when_cli_is_only_unverified(
+ self, monkeypatch
+ ):
self._isolate(monkeypatch, opencli=("warn", "扩展未连接"))
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/xhs")
@@ -970,50 +1011,150 @@ class TestXiaoHongShuChannel:
ch = XiaoHongShuChannel()
status, msg = ch.check()
- assert status == "ok"
- assert ch.active_backend == "xhs-cli (xiaohongshu-cli)"
+ assert status == "warn"
+ assert msg == "扩展未连接"
+ assert ch.active_backend is None
- def test_mcp_service_wins_when_opencli_absent(self, monkeypatch):
+ def test_mcp_service_wins_when_opencli_absent(
+ self, monkeypatch, tmp_path
+ ):
"""服务器场景:OpenCLI 未装、mcp 服务可达且 mcporter 已接入 → mcp 获胜。"""
self._isolate(monkeypatch, mcp_reachable=True)
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"xiaohongshu": {"baseUrl": "http://local"}},
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
def fake_which(name):
return "/usr/local/bin/mcporter" if name == "mcporter" else None
monkeypatch.setattr(shutil, "which", fake_which)
-
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, "exa\nxiaohongshu\n", "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute mcporter"
+ ),
+ )
ch = XiaoHongShuChannel()
status, msg = ch.check()
- assert status == "ok"
- assert ch.active_backend == "xiaohongshu-mcp"
- assert "search_feeds" in msg
+ assert status == "warn"
+ assert ch.active_backend is None
+ assert "未验证登录态" in msg
- def test_mcp_reachable_but_mcporter_unconfigured_warns(self, monkeypatch):
+ def test_mcp_reachable_but_mcporter_unconfigured_warns(
+ self, monkeypatch, tmp_path
+ ):
self._isolate(monkeypatch, mcp_reachable=True)
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"exa": {"baseUrl": "https://example.test"}},
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
def fake_which(name):
return "/usr/local/bin/mcporter" if name == "mcporter" else None
monkeypatch.setattr(shutil, "which", fake_which)
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, "exa\n", "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute mcporter"
+ ),
+ )
ch = XiaoHongShuChannel()
status, msg = ch.check()
assert status == "warn"
assert "mcporter config add xiaohongshu" in msg
- assert ch.active_backend == "xiaohongshu-mcp"
+ assert ch.active_backend is None
+
+ def test_mcp_metadata_containing_xiaohongshu_is_not_configured(
+ self, monkeypatch, tmp_path
+ ):
+ """Paths and URLs are not valid server-name health signals."""
+ self._isolate(monkeypatch, mcp_reachable=True)
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "unrelated": {
+ "baseUrl": "http://xiaohongshu-project.test/mcp"
+ }
+ },
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ shutil,
+ "which",
+ lambda name: "/usr/local/bin/mcporter"
+ if name == "mcporter"
+ else None,
+ )
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute mcporter"
+ ),
+ )
+
+ ch = XiaoHongShuChannel()
+ status, message = ch.check()
+
+ assert status == "warn"
+ assert "未接入" in message
+ assert ch.active_backend is None
+
+ def test_all_xhs_auth_hints_exclude_qr_and_automatic_cookie_read(
+ self, monkeypatch
+ ):
+ """XHS remediation must remain on the explicit Cookie-Editor path."""
+ self._isolate(monkeypatch)
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/xhs")
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(
+ cmd, 1, "", "not_authenticated"
+ ),
+ )
+
+ status, message = XiaoHongShuChannel().check()
+
+ assert status == "warn"
+ assert "Cookie-Editor" in message
+ assert "configure xhs-cookies" in message
+ assert "扫码" not in message
+ assert "自动从浏览器" not in message
- def test_backend_override_prefers_cli(self, monkeypatch):
- """config xiaohongshu_backend=xhs-cli 时,即使 OpenCLI ready 也用 xhs-cli。"""
+ def test_unverified_cli_override_cannot_hide_working_opencli(
+ self, monkeypatch
+ ):
self._isolate(monkeypatch, opencli=("ok", "OpenCLI 可用"))
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/xhs")
@@ -1029,7 +1170,7 @@ class TestXiaoHongShuChannel:
ch = XiaoHongShuChannel()
status, _ = ch.check(_Cfg())
assert status == "ok"
- assert ch.active_backend == "xhs-cli (xiaohongshu-cli)"
+ assert ch.active_backend == "OpenCLI"
class TestBilibiliChannel:
@@ -1061,6 +1202,22 @@ class TestBilibiliChannel:
assert "bili-cli 可用" in msg
assert ch.active_backend == "bili-cli"
+ def test_opencli_bridge_ready_is_unverified(self, monkeypatch):
+ monkeypatch.setattr(
+ "agent_reach.backends.opencli_status",
+ lambda: OpenCLIStatus(
+ installed=True,
+ extension_connected=True,
+ version="1.8.6",
+ ),
+ )
+
+ status, message = BilibiliChannel()._check_opencli()
+
+ assert status == "warn"
+ assert "桥接已连接" in message
+ assert "实际命令未实时验证" in message
+
def test_bili_broken_falls_back_to_api_with_hint_kept(self, monkeypatch):
"""bili 断链 → API 兜底获胜,但重装处方必须保留在消息里。"""
self._isolate(monkeypatch, api_ok=True)
@@ -1099,14 +1256,32 @@ class TestBilibiliChannel:
assert "uv tool install --force bilibili-cli" in msg
assert ch.active_backend is None
- def test_opencli_serves_when_bili_missing(self, monkeypatch):
- self._isolate(monkeypatch, opencli=("ok", "OpenCLI 可用(字幕)"), api_ok=True)
+ def test_unverified_opencli_falls_back_to_verified_api(self, monkeypatch):
+ self._isolate(
+ monkeypatch,
+ opencli=("warn", "OpenCLI 桥接已连接但未验证"),
+ api_ok=True,
+ )
monkeypatch.setattr(shutil, "which", lambda _: None)
from agent_reach.channels.bilibili import BilibiliChannel
ch = BilibiliChannel()
status, msg = ch.check()
assert status == "ok"
- assert ch.active_backend == "OpenCLI"
+ assert ch.active_backend == "B站搜索 API"
+
+ def test_unverified_opencli_alone_has_no_active_backend(self, monkeypatch):
+ self._isolate(
+ monkeypatch,
+ opencli=("warn", "OpenCLI 桥接已连接但未验证"),
+ api_ok=False,
+ )
+ monkeypatch.setattr(shutil, "which", lambda _: None)
+
+ ch = BilibiliChannel()
+ status, _ = ch.check()
+
+ assert status == "warn"
+ assert ch.active_backend is None
def test_api_only_still_ok_with_install_nudge(self, monkeypatch):
self._isolate(monkeypatch, api_ok=True)
@@ -1148,10 +1323,11 @@ class TestYouTubeChannel:
class TestGitHubChannel:
def test_reports_error_with_reinstall_hint_when_broken(self, monkeypatch):
- """gh which 命中但 exec 失败 → error + brew 重装处方(gh 不是 pip 包)。"""
+ """gh --version 断链时给出二进制重装处方。"""
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/gh")
def fake_run(cmd, **kwargs):
+ assert cmd[-1:] == ["--version"]
raise FileNotFoundError(cmd[0])
monkeypatch.setattr(subprocess, "run", fake_run)
@@ -1163,25 +1339,40 @@ class TestGitHubChannel:
assert "brew reinstall gh" in msg
assert ch.active_backend is None
- def test_active_backend_set_when_authenticated(self, monkeypatch):
+ def test_explicit_auth_is_unverified_and_never_marked_active(
+ self, monkeypatch
+ ):
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/gh")
+ monkeypatch.setenv("GH_TOKEN", "configured-secret")
def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, "Logged in to github.com", "")
+ assert cmd[-1:] == ["--version"]
+ assert "auth" not in cmd
+ assert kwargs["env"]["GH_TELEMETRY"] == "false"
+ assert kwargs["env"]["DO_NOT_TRACK"] == "true"
+ return subprocess.CompletedProcess(cmd, 0, "gh version 2.92.0", "")
monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.github import GitHubChannel
ch = GitHubChannel()
status, msg = ch.check()
- assert status == "ok"
- assert ch.active_backend == "gh CLI"
+ assert status == "warn"
+ assert "显式认证配置" in msg
+ assert "configured-secret" not in msg
+ assert ch.active_backend is None
- def test_active_backend_set_when_unauthenticated(self, monkeypatch):
- """gh auth status 非零退出是正常业务态(未登录):warn 但后端可用。"""
+ def test_no_auth_metadata_remains_warn_and_inactive(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.chdir(tmp_path)
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/gh")
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 1, "", "You are not logged in")
+ assert cmd[-1:] == ["--version"]
+ assert "auth" not in cmd
+ return subprocess.CompletedProcess(cmd, 0, "gh version 2.92.0", "")
monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.github import GitHubChannel
@@ -1189,61 +1380,146 @@ class TestGitHubChannel:
status, msg = ch.check()
assert status == "warn"
assert "gh auth login" in msg
- assert ch.active_backend == "gh CLI"
+ assert ch.active_backend is None
+ def test_hosts_metadata_is_read_without_exposing_token(
+ self, monkeypatch, isolated_home
+ ):
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/gh")
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ hosts = isolated_home / ".config" / "gh" / "hosts.yml"
+ hosts.parent.mkdir(parents=True)
+ hosts.write_text(
+ "github.com:\n"
+ " user: alice\n"
+ " oauth_token: super-secret-token\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(
+ cmd, 0, "gh version 2.92.0", ""
+ ),
+ )
-class TestLinkedInChannel:
- def test_reports_error_with_reinstall_hint_when_broken(self, monkeypatch):
- """mcporter which 命中但 exec 失败 → error + npm 重装处方。"""
- monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
+ from agent_reach.channels.github import GitHubChannel
- def fake_run(cmd, **kwargs):
- raise FileNotFoundError(cmd[0])
+ status, message = GitHubChannel().check()
- monkeypatch.setattr(subprocess, "run", fake_run)
+ assert status == "warn"
+ assert "显式认证配置" in message
+ assert "alice" not in message
+ assert "super-secret-token" not in message
+
+ def test_hosts_metadata_refuses_ancestor_symlink(
+ self, monkeypatch, isolated_home
+ ):
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/gh")
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ real_config = isolated_home / "real-config"
+ hosts = real_config / "gh" / "hosts.yml"
+ hosts.parent.mkdir(parents=True)
+ hosts.write_text(
+ "github.com:\n oauth_token: do-not-read\n",
+ encoding="utf-8",
+ )
+ (isolated_home / ".config").symlink_to(
+ real_config,
+ target_is_directory=True,
+ )
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(
+ cmd, 0, "gh version 2.92.0", ""
+ ),
+ )
+
+ from agent_reach.channels.github import GitHubChannel
+
+ channel = GitHubChannel()
+ status, message = channel.check()
+
+ assert status == "warn"
+ assert "无法安全确认" in message
+ assert "do-not-read" not in message
+ assert channel.active_backend is None
+
+
+class TestLinkedInChannel:
+ def test_mcporter_is_never_executed(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute mcporter"
+ ),
+ )
from agent_reach.channels.linkedin import LinkedInChannel
ch = LinkedInChannel()
status, msg = ch.check()
- assert status == "error"
- assert "npm install -g mcporter" in msg
+ assert status == "off"
assert ch.active_backend is None
- def test_active_backend_set_when_linkedin_configured(self, monkeypatch):
+ def test_configured_linkedin_is_not_false_positive_active(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "linkedin-scraper": {"command": "linkedin-mcp"}
+ },
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
-
- def fake_run(cmd, **kwargs):
- assert cmd[-3:] == ["config", "list", "--json"]
- return subprocess.CompletedProcess(
- cmd,
- 0,
- json.dumps({"servers": [{"name": "linkedin-scraper"}]}),
- "",
- )
-
- monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute mcporter"
+ ),
+ )
from agent_reach.channels.linkedin import LinkedInChannel
ch = LinkedInChannel()
status, msg = ch.check()
- assert status == "ok"
- assert ch.active_backend == "linkedin-scraper-mcp"
+ assert status == "warn"
+ assert "未启动" in msg
+ assert ch.active_backend is None
- def test_config_path_containing_linkedin_is_not_a_backend(self, monkeypatch):
+ def test_config_metadata_containing_linkedin_is_not_a_backend(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "unrelated": {
+ "baseUrl": "http://linkedin-project.test/mcp"
+ }
+ },
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
-
- def fake_run(cmd, **kwargs):
- payload = {
- "servers": [
- {
- "name": "unrelated",
- "source": {
- "path": "/tmp/linkedin-project/config/mcporter.json",
- },
- }
- ]
- }
- return subprocess.CompletedProcess(cmd, 0, json.dumps(payload), "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.linkedin import LinkedInChannel
ch = LinkedInChannel()
@@ -1251,18 +1527,22 @@ class TestLinkedInChannel:
assert status == "off"
assert ch.active_backend is None
- def test_off_without_backend_when_linkedin_not_configured(self, monkeypatch):
+ def test_off_without_backend_when_linkedin_not_configured(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"exa": {"baseUrl": "https://example.test"}},
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
-
- def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(
- cmd,
- 0,
- json.dumps({"servers": [{"name": "exa"}]}),
- "",
- )
-
- monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.linkedin import LinkedInChannel
ch = LinkedInChannel()
status, msg = ch.check()
@@ -1271,57 +1551,67 @@ class TestLinkedInChannel:
class TestExaSearchChannel:
- def test_reports_error_with_reinstall_hint_when_broken(self, monkeypatch):
- """mcporter which 命中但 exec 失败 → error + npm 重装处方。"""
+ def test_mcporter_is_never_executed(self, monkeypatch, tmp_path):
+ monkeypatch.chdir(tmp_path)
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
-
- def fake_run(cmd, **kwargs):
- raise FileNotFoundError(cmd[0])
-
- monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute mcporter"
+ ),
+ )
from agent_reach.channels.exa_search import ExaSearchChannel
ch = ExaSearchChannel()
status, msg = ch.check()
- assert status == "error"
- assert "npm install -g mcporter" in msg
+ assert status == "off"
assert ch.active_backend is None
- def test_active_backend_set_when_exa_configured(self, monkeypatch):
+ def test_configured_exa_is_not_false_positive_active(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "exa": {"baseUrl": "https://mcp.example.test"}
+ },
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
-
- def fake_run(cmd, **kwargs):
- assert cmd[-3:] == ["config", "list", "--json"]
- return subprocess.CompletedProcess(
- cmd,
- 0,
- json.dumps({"servers": [{"name": "exa"}]}),
- "",
- )
-
- monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.exa_search import ExaSearchChannel
ch = ExaSearchChannel()
status, msg = ch.check()
- assert status == "ok"
- assert ch.active_backend == "Exa via mcporter"
+ assert status == "warn"
+ assert "未启动" in msg
+ assert ch.active_backend is None
- def test_config_path_containing_exa_is_not_a_backend(self, monkeypatch):
+ def test_config_metadata_containing_exa_is_not_a_backend(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "unrelated": {
+ "baseUrl": "https://example.test/exa-project"
+ }
+ },
+ "imports": [],
+ }
+ ),
+ encoding="utf-8",
+ )
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
-
- def fake_run(cmd, **kwargs):
- payload = {
- "servers": [
- {
- "name": "unrelated",
- "source": {
- "path": "/tmp/example-project/config/mcporter.json",
- },
- }
- ]
- }
- return subprocess.CompletedProcess(cmd, 0, json.dumps(payload), "")
-
- monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.exa_search import ExaSearchChannel
ch = ExaSearchChannel()
@@ -1330,17 +1620,18 @@ class TestExaSearchChannel:
assert ch.active_backend is None
def test_invalid_mcporter_json_is_reported_as_error_not_unconfigured(
- self, monkeypatch
+ self, monkeypatch, tmp_path
):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text("not-json", encoding="utf-8")
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
monkeypatch.setattr(
subprocess,
"run",
- lambda cmd, **kwargs: subprocess.CompletedProcess(
- cmd,
- 0,
- "Project config: /tmp/example/config/mcporter.json",
- "",
+ lambda *_args, **_kwargs: pytest.fail(
+ "Doctor must not execute mcporter"
),
)
from agent_reach.channels.exa_search import ExaSearchChannel
diff --git a/tests/test_config.py b/tests/test_config.py
index 3ecfa1ff..6ae4697c 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -187,6 +187,39 @@ class TestConfig:
Config(config_path=linked_dir / "config.yaml")
assert list(real_dir.iterdir()) == []
+ def test_config_ancestor_symlink_is_rejected(self, tmp_path):
+ real_dir = tmp_path / "real"
+ real_dir.mkdir()
+ linked_root = tmp_path / "linked-root"
+ try:
+ linked_root.symlink_to(real_dir, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+
+ with pytest.raises(ConfigSecurityError, match="符号链接"):
+ Config(config_path=linked_root / "nested" / "config.yaml")
+
+ def test_config_load_refuses_non_regular_file(self, tmp_path):
+ import os
+
+ if not hasattr(os, "mkfifo"):
+ pytest.skip("FIFOs are not supported on this platform")
+ config_file = tmp_path / "config.yaml"
+ os.mkfifo(config_file)
+
+ with pytest.raises(ConfigSecurityError, match="常规文件"):
+ Config(config_path=config_file)
+
+ def test_config_load_is_bounded(self, tmp_path, monkeypatch):
+ import agent_reach.config as config_module
+
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text("secret: too-long\n", encoding="utf-8")
+ monkeypatch.setattr(config_module, "_MAX_CONFIG_BYTES", 4)
+
+ with pytest.raises(ConfigSecurityError, match="大小上限"):
+ Config(config_path=config_file)
+
def test_save_preserves_previous_file_on_serialization_failure(
self, tmp_path, monkeypatch
):
diff --git a/tests/test_doctor.py b/tests/test_doctor.py
index 7ce7013a..e181dd9a 100644
--- a/tests/test_doctor.py
+++ b/tests/test_doctor.py
@@ -1,6 +1,14 @@
# -*- coding: utf-8 -*-
"""Tests for doctor module."""
+import hashlib
+import json
+import os
+import shutil
+import subprocess
+from argparse import Namespace
+from pathlib import Path
+
import pytest
import agent_reach.doctor as doctor
@@ -124,3 +132,194 @@ def test_stale_active_backend_does_not_leak_into_errored_result(monkeypatch):
results = doctor.check_all(config=None)
assert results["boom"]["status"] == "error"
assert results["boom"]["active_backend"] is None
+
+
+def test_channel_exception_credentials_are_scrubbed(monkeypatch):
+ """Doctor is the final trust boundary for unexpected channel errors."""
+
+ class _ExplodingChannel:
+ name = "secret"
+ description = "敏感渠道"
+ tier = 0
+ backends = ["secret-backend"]
+ active_backend = None
+
+ def check(self, config=None):
+ raise RuntimeError(
+ "request https://alice:[email protected]/data"
+ "?access_token=top-secret failed"
+ )
+
+ monkeypatch.setattr(doctor, "get_all_channels", lambda: [_ExplodingChannel()])
+
+ message = doctor.check_all(config=None)["secret"]["message"]
+
+ assert "alice" not in message
+ assert "password" not in message
+ assert "top-secret" not in message
+ assert "https://***@example.test/data?access_token=***" in message
+
+
+def test_channel_success_message_credentials_are_scrubbed(monkeypatch):
+ """Expected channel messages must pass through the same trust boundary."""
+ channel = _StubChannel(
+ "configured",
+ "已配置渠道",
+ 0,
+ "warn",
+ (
+ "upstream returned https://alice:[email protected]/data"
+ "?api_key=top-secret"
+ ),
+ ["upstream"],
+ )
+ monkeypatch.setattr(doctor, "get_all_channels", lambda: [channel])
+
+ message = doctor.check_all(config=None)["configured"]["message"]
+
+ assert "alice" not in message
+ assert "password" not in message
+ assert "top-secret" not in message
+ assert "https://***@example.test/data?api_key=***" in message
+
+
+def _snapshot_user_roots() -> tuple:
+ entries = []
+ seen = set()
+ for variable in (
+ "HOME",
+ "USERPROFILE",
+ "XDG_CONFIG_HOME",
+ "APPDATA",
+ "LOCALAPPDATA",
+ ):
+ root = Path(os.environ[variable])
+ if root in seen:
+ continue
+ seen.add(root)
+ if not root.exists():
+ entries.append((variable, ".", "missing"))
+ continue
+ for path in sorted(root.rglob("*")):
+ relative = path.relative_to(root).as_posix()
+ if path.is_symlink():
+ detail = ("symlink", os.readlink(path))
+ elif path.is_dir():
+ detail = ("directory", path.stat().st_mode & 0o777)
+ elif path.is_file():
+ detail = (
+ "file",
+ path.stat().st_mode & 0o777,
+ hashlib.sha256(path.read_bytes()).hexdigest(),
+ )
+ else:
+ detail = ("other",)
+ entries.append((variable, relative, detail))
+ return tuple(entries)
+
+
+def test_real_doctor_path_is_zero_write_and_never_runs_risky_status_commands(
+ monkeypatch, tmp_path, capsys
+):
+ """Run the real Doctor collector with deterministic external probes."""
+ import agent_reach.backends.opencli as opencli
+ import agent_reach.channels.bilibili as bilibili
+ import agent_reach.channels.v2ex as v2ex
+ import agent_reach.channels.xiaohongshu as xiaohongshu
+ import agent_reach.channels.xueqiu as xueqiu
+ from agent_reach import cli
+
+ workdir = tmp_path / "empty-workdir"
+ workdir.mkdir()
+ monkeypatch.chdir(workdir)
+ monkeypatch.delenv("MCPORTER_CONFIG", raising=False)
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+
+ available = {
+ "gh",
+ "opencli",
+ "yt-dlp",
+ "bili",
+ "ffmpeg",
+ "mcporter",
+ "twitter",
+ "rdt",
+ "xhs",
+ "deno",
+ "node",
+ }
+ monkeypatch.setattr(
+ shutil,
+ "which",
+ lambda name: f"/audit-bin/{name}" if name in available else None,
+ )
+
+ calls = []
+
+ def fake_run(command, **kwargs):
+ argv = [str(item) for item in command]
+ calls.append(argv)
+ name = Path(argv[0]).name
+ assert name != "mcporter"
+ assert argv[1:] not in (
+ ["auth", "status"],
+ ["status"],
+ ["daemon", "status"],
+ )
+ if name == "gh":
+ assert argv[1:] == ["--version"]
+ assert kwargs["env"]["GH_TELEMETRY"] == "false"
+ assert kwargs["env"]["DO_NOT_TRACK"] == "true"
+ output = "gh version 2.92.0"
+ elif name == "opencli":
+ assert argv[1:] == ["--version"]
+ output = "1.8.6"
+ elif name == "yt-dlp":
+ output = "2026.01.01"
+ elif name == "bili":
+ output = "0.3.0"
+ elif name == "ffmpeg":
+ output = "ffmpeg version 7.0"
+ else:
+ pytest.fail(f"unexpected Doctor subprocess: {argv}")
+ return subprocess.CompletedProcess(argv, 0, output, "")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(opencli, "_fetch_daemon_status", lambda timeout=2: None)
+ monkeypatch.setattr(opencli, "_extension_installed_on_disk", lambda: False)
+ monkeypatch.setattr(
+ opencli, "_unpacked_extension_files_present", lambda: False
+ )
+ monkeypatch.setattr(bilibili, "_search_api_ok", lambda: False)
+ monkeypatch.setattr(
+ xiaohongshu, "_mcp_service_reachable", lambda timeout=3: False
+ )
+ monkeypatch.setattr(v2ex, "_get_json", lambda _url: [])
+ monkeypatch.setattr(
+ xueqiu,
+ "_get_json",
+ lambda _url, _config=None: {
+ "data": {"quote": {"symbol": "SH601138"}}
+ },
+ )
+
+ before = _snapshot_user_roots()
+ cli._cmd_doctor(Namespace(json=True))
+ after = _snapshot_user_roots()
+
+ assert after == before
+ assert calls
+ assert all(Path(call[0]).name != "mcporter" for call in calls)
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["github"]["status"] == "warn"
+ assert payload["github"]["active_backend"] is None
+ for channel_name in (
+ "twitter",
+ "reddit",
+ "facebook",
+ "instagram",
+ "xiaohongshu",
+ ):
+ assert payload[channel_name]["status"] == "warn"
+ assert payload[channel_name]["active_backend"] is None
diff --git a/tests/test_doctor_credential_boundaries.py b/tests/test_doctor_credential_boundaries.py
new file mode 100644
index 00000000..82f3cf00
--- /dev/null
+++ b/tests/test_doctor_credential_boundaries.py
@@ -0,0 +1,172 @@
+"""Doctor must not trigger upstream browser-cookie refresh or persistence."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import time
+
+from agent_reach.channels.reddit import RedditChannel
+from agent_reach.channels.twitter import TwitterChannel
+from agent_reach.channels.xiaohongshu import XiaoHongShuChannel
+
+
+def _forbid_subprocess(*_args, **_kwargs):
+ raise AssertionError("credential-backed health checks must not execute upstream CLIs")
+
+
+def test_twitter_doctor_does_not_start_cli_without_explicit_credentials(
+ monkeypatch,
+):
+ monkeypatch.delenv("TWITTER_AUTH_TOKEN", raising=False)
+ monkeypatch.delenv("TWITTER_CT0", raising=False)
+ monkeypatch.setattr(
+ "shutil.which",
+ lambda name: "/usr/local/bin/twitter" if name == "twitter" else None,
+ )
+ monkeypatch.setattr(subprocess, "run", _forbid_subprocess)
+
+ channel = TwitterChannel()
+ status, message = channel.check()
+
+ assert status == "warn"
+ assert channel.active_backend is None
+ assert "Cookie-Editor" in message
+ assert "浏览器" not in message or "不会" in message
+
+
+def test_twitter_doctor_still_avoids_upstream_fallback_with_saved_credentials(
+ monkeypatch,
+):
+ class Config:
+ def get(self, key, default=None):
+ return {
+ "twitter_auth_token": "explicit-auth",
+ "twitter_ct0": "explicit-ct0",
+ }.get(key, default)
+
+ monkeypatch.setattr(
+ "shutil.which",
+ lambda name: "/usr/local/bin/twitter" if name == "twitter" else None,
+ )
+ monkeypatch.setattr(subprocess, "run", _forbid_subprocess)
+
+ status, message = TwitterChannel().check(Config())
+
+ assert status == "warn"
+ assert "已配置" in message
+ assert "不会执行" in message
+
+
+def test_reddit_doctor_does_not_create_or_refresh_missing_credentials(
+ isolated_home, monkeypatch
+):
+ monkeypatch.setattr(
+ "shutil.which",
+ lambda name: "/usr/local/bin/rdt" if name == "rdt" else None,
+ )
+ monkeypatch.setattr(subprocess, "run", _forbid_subprocess)
+
+ channel = RedditChannel()
+ status, message = channel.check()
+
+ assert status == "warn"
+ assert channel.active_backend is None
+ assert "Cookie-Editor" in message
+ assert not (isolated_home / ".config" / "rdt-cli").exists()
+
+
+def test_reddit_doctor_reports_stale_saved_credential_without_refresh(
+ isolated_home, monkeypatch
+):
+ credential_path = (
+ isolated_home / ".config" / "rdt-cli" / "credential.json"
+ )
+ credential_path.parent.mkdir(parents=True)
+ credential_path.write_text(
+ json.dumps(
+ {
+ "cookies": {"reddit_session": "explicit-cookie"},
+ "saved_at": time.time() - 8 * 86400,
+ }
+ ),
+ encoding="utf-8",
+ )
+ original = credential_path.read_bytes()
+ monkeypatch.setattr(
+ "shutil.which",
+ lambda name: "/usr/local/bin/rdt" if name == "rdt" else None,
+ )
+ monkeypatch.setattr(subprocess, "run", _forbid_subprocess)
+
+ status, message = RedditChannel().check()
+
+ assert status == "warn"
+ assert "超过 7 天" in message
+ assert credential_path.read_bytes() == original
+
+
+def test_xhs_doctor_does_not_create_or_extract_missing_cookies(
+ isolated_home, monkeypatch
+):
+ monkeypatch.setattr(
+ "shutil.which",
+ lambda name: "/usr/local/bin/xhs" if name == "xhs" else None,
+ )
+ monkeypatch.setattr(subprocess, "run", _forbid_subprocess)
+ monkeypatch.setattr(
+ XiaoHongShuChannel,
+ "_check_opencli",
+ lambda self: None,
+ )
+ monkeypatch.setattr(
+ XiaoHongShuChannel,
+ "_check_mcp",
+ lambda self: None,
+ )
+
+ channel = XiaoHongShuChannel()
+ status, message = channel.check()
+
+ assert status == "warn"
+ assert channel.active_backend is None
+ assert "Cookie-Editor" in message
+ assert not (isolated_home / ".xiaohongshu-cli").exists()
+
+
+def test_xhs_doctor_reports_stale_cookie_without_refresh(
+ isolated_home, monkeypatch
+):
+ cookie_path = isolated_home / ".xiaohongshu-cli" / "cookies.json"
+ cookie_path.parent.mkdir(parents=True)
+ cookie_path.write_text(
+ json.dumps(
+ {
+ "a1": "explicit-cookie",
+ "saved_at": time.time() - 8 * 86400,
+ }
+ ),
+ encoding="utf-8",
+ )
+ original = cookie_path.read_bytes()
+ monkeypatch.setattr(
+ "shutil.which",
+ lambda name: "/usr/local/bin/xhs" if name == "xhs" else None,
+ )
+ monkeypatch.setattr(subprocess, "run", _forbid_subprocess)
+ monkeypatch.setattr(
+ XiaoHongShuChannel,
+ "_check_opencli",
+ lambda self: None,
+ )
+ monkeypatch.setattr(
+ XiaoHongShuChannel,
+ "_check_mcp",
+ lambda self: None,
+ )
+
+ status, message = XiaoHongShuChannel().check()
+
+ assert status == "warn"
+ assert "超过 7 天" in message
+ assert cookie_path.read_bytes() == original
diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py
new file mode 100644
index 00000000..d70f3917
--- /dev/null
+++ b/tests/test_mcp_server.py
@@ -0,0 +1,101 @@
+"""Security boundaries for the optional Agent Reach MCP server."""
+
+import asyncio
+from types import SimpleNamespace
+
+import agent_reach.integrations.mcp_server as mcp_server
+
+
+class _FakeServer:
+ def __init__(self, name):
+ self.name = name
+ self.list_tools_handler = None
+ self.call_tool_handler = None
+
+ def list_tools(self):
+ def register(handler):
+ self.list_tools_handler = handler
+ return handler
+
+ return register
+
+ def call_tool(self):
+ def register(handler):
+ self.call_tool_handler = handler
+ return handler
+
+ return register
+
+
+def _install_fake_mcp(monkeypatch):
+ monkeypatch.setattr(mcp_server, "HAS_MCP", True)
+ monkeypatch.setattr(mcp_server, "Server", _FakeServer, raising=False)
+ monkeypatch.setattr(
+ mcp_server,
+ "Tool",
+ lambda **kwargs: SimpleNamespace(**kwargs),
+ raising=False,
+ )
+ monkeypatch.setattr(
+ mcp_server,
+ "TextContent",
+ lambda **kwargs: SimpleNamespace(**kwargs),
+ raising=False,
+ )
+
+
+def test_mcp_status_uses_read_only_config(monkeypatch):
+ _install_fake_mcp(monkeypatch)
+ created_configs = []
+
+ class _RecordingConfig:
+ def __init__(self, *, read_only=False):
+ self.read_only = read_only
+ created_configs.append(self)
+
+ class _AgentReach:
+ def __init__(self, config):
+ self.config = config
+
+ def doctor_report(self):
+ return "ok"
+
+ monkeypatch.setattr(mcp_server, "Config", _RecordingConfig)
+ monkeypatch.setattr(mcp_server, "AgentReach", _AgentReach)
+
+ server = mcp_server.create_server()
+ result = asyncio.run(server.call_tool_handler("get_status", {}))
+
+ assert len(created_configs) == 1
+ assert created_configs[0].read_only is True
+ assert result[0].text == "ok"
+
+
+def test_mcp_status_exception_credentials_are_scrubbed(monkeypatch):
+ _install_fake_mcp(monkeypatch)
+
+ class _Config:
+ def __init__(self, *, read_only=False):
+ self.read_only = read_only
+
+ class _ExplodingAgentReach:
+ def __init__(self, config):
+ self.config = config
+
+ def doctor_report(self):
+ raise RuntimeError(
+ "request https://alice:[email protected]/data"
+ "?token=top-secret failed"
+ )
+
+ monkeypatch.setattr(mcp_server, "Config", _Config)
+ monkeypatch.setattr(mcp_server, "AgentReach", _ExplodingAgentReach)
+
+ server = mcp_server.create_server()
+ result = asyncio.run(server.call_tool_handler("get_status", {}))
+ text = result[0].text
+
+ assert "alice" not in text
+ assert "password" not in text
+ assert "top-secret" not in text
+ assert "https://***@example.test/data?token=***" in text
diff --git a/tests/test_mcporter_config.py b/tests/test_mcporter_config.py
new file mode 100644
index 00000000..fe864105
--- /dev/null
+++ b/tests/test_mcporter_config.py
@@ -0,0 +1,158 @@
+"""Read-only mcporter configuration inspection tests."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from agent_reach.channels.mcporter import (
+ McporterConfigError,
+ configured_server_names,
+ inspect_mcporter_config,
+)
+
+
+def _write_config(path, servers, *, imports=()):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps({"mcpServers": servers, "imports": list(imports)}),
+ encoding="utf-8",
+ )
+
+
+def test_home_and_project_layers_are_merged(
+ monkeypatch, tmp_path, isolated_home
+):
+ monkeypatch.chdir(tmp_path)
+ _write_config(
+ isolated_home / ".mcporter" / "mcporter.json",
+ {
+ "home-only": {"baseUrl": "https://home.example.test"},
+ "shared": {"baseUrl": "https://home-shared.example.test"},
+ },
+ )
+ _write_config(
+ tmp_path / "config" / "mcporter.json",
+ {
+ "project-only": {"command": "project-mcp"},
+ "shared": {"baseUrl": "https://project-shared.example.test"},
+ },
+ )
+
+ inspection = inspect_mcporter_config()
+
+ assert inspection.server_names == {
+ "home-only",
+ "project-only",
+ "shared",
+ }
+ assert inspection.source == "home+project"
+ assert inspection.imports_unchecked is False
+
+
+def test_explicit_config_is_the_only_layer(
+ monkeypatch, tmp_path, isolated_home
+):
+ monkeypatch.chdir(tmp_path)
+ _write_config(
+ isolated_home / ".mcporter" / "mcporter.json",
+ {"home-only": {"command": "home"}},
+ )
+ _write_config(
+ tmp_path / "config" / "mcporter.json",
+ {"project-only": {"command": "project"}},
+ )
+ _write_config(
+ tmp_path / "explicit.json",
+ {"explicit-only": {"command": "explicit"}},
+ )
+ monkeypatch.setenv("MCPORTER_CONFIG", "explicit.json")
+
+ inspection = inspect_mcporter_config()
+
+ assert inspection.server_names == {"explicit-only"}
+ assert inspection.source == "explicit"
+
+
+def test_missing_explicit_config_fails_closed(monkeypatch, tmp_path):
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("MCPORTER_CONFIG", "missing.json")
+
+ with pytest.raises(McporterConfigError, match="不存在"):
+ inspect_mcporter_config()
+
+
+def test_symlink_config_is_rejected(monkeypatch, tmp_path):
+ monkeypatch.chdir(tmp_path)
+ target = tmp_path / "real.json"
+ _write_config(target, {"exa": {"baseUrl": "https://example.test"}})
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ try:
+ config_path.symlink_to(target)
+ except OSError:
+ pytest.skip("symlinks are unavailable on this platform")
+
+ with pytest.raises(McporterConfigError, match="符号链接"):
+ inspect_mcporter_config()
+
+
+def test_ancestor_symlink_config_is_rejected(monkeypatch, tmp_path):
+ real_root = tmp_path / "real-root"
+ _write_config(
+ real_root / "config" / "mcporter.json",
+ {"exa": {"baseUrl": "https://example.test"}},
+ )
+ linked_root = tmp_path / "linked-root"
+ try:
+ linked_root.symlink_to(real_root, target_is_directory=True)
+ except OSError:
+ pytest.skip("symlinks are unavailable on this platform")
+ monkeypatch.setenv(
+ "MCPORTER_CONFIG",
+ str(linked_root / "config" / "mcporter.json"),
+ )
+
+ with pytest.raises(McporterConfigError, match="安全读取"):
+ inspect_mcporter_config()
+
+
+def test_invalid_json_fails_closed(monkeypatch, tmp_path):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text("{not-json", encoding="utf-8")
+
+ with pytest.raises(McporterConfigError, match="UTF-8 JSON"):
+ inspect_mcporter_config()
+
+
+def test_omitted_imports_are_reported_but_not_expanded(
+ monkeypatch, tmp_path
+):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "config" / "mcporter.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps({"mcpServers": {"exa": {"command": "exa"}}}),
+ encoding="utf-8",
+ )
+
+ inspection = inspect_mcporter_config()
+
+ assert inspection.server_names == {"exa"}
+ assert inspection.imports_unchecked is True
+
+
+def test_machine_output_parser_remains_available_for_install_flows():
+ output = json.dumps(
+ {
+ "servers": [
+ {"name": "Exa", "baseUrl": "https://example.test"},
+ {"name": "linkedin-scraper"},
+ ]
+ }
+ )
+
+ assert configured_server_names(output) == {"exa", "linkedin-scraper"}
diff --git a/tests/test_opencli_backend.py b/tests/test_opencli_backend.py
index 92709180..5eeb19f3 100644
--- a/tests/test_opencli_backend.py
+++ b/tests/test_opencli_backend.py
@@ -14,20 +14,22 @@ from agent_reach.probe import ProbeResult
def _status_with(
version_probe,
- daemon_probe=None,
+ daemon_status=None,
ext_on_disk=False,
unpacked_files=False,
):
- """Run opencli_status with probe_command and disk check patched."""
+ """Run opencli_status with the CLI version and HTTP status patched."""
calls = []
def fake_probe(cmd, args=("--version",), **kwargs):
calls.append(list(args))
- if list(args) == ["--version"]:
- return version_probe
- return daemon_probe or ProbeResult("missing")
+ return version_probe
with patch("agent_reach.backends.opencli.probe_command", side_effect=fake_probe), \
+ patch(
+ "agent_reach.backends.opencli._fetch_daemon_status",
+ return_value=daemon_status,
+ ), \
patch(
"agent_reach.backends.opencli._extension_installed_on_disk",
return_value=ext_on_disk,
@@ -54,10 +56,14 @@ def test_broken_node_env_gives_npm_hint():
def test_daemon_running_extension_connected_is_ready():
- daemon_out = "Daemon: running (PID 37389)\nVersion: v1.8.3\nExtension: connected\n"
+ daemon_status = {
+ "ok": True,
+ "pid": 37389,
+ "extensionConnected": True,
+ }
st, _ = _status_with(
ProbeResult("ok", output="1.8.3"),
- ProbeResult("ok", output=daemon_out),
+ daemon_status,
)
assert st.installed and st.daemon_running and st.extension_connected
assert st.ready
@@ -65,10 +71,10 @@ def test_daemon_running_extension_connected_is_ready():
def test_extension_never_installed_not_ready_with_store_guide():
- daemon_out = "Daemon: running (PID 1)\nExtension: disconnected\n"
+ daemon_status = {"ok": True, "pid": 1, "extensionConnected": False}
st, _ = _status_with(
ProbeResult("ok", output="1.8.3"),
- ProbeResult("ok", output=daemon_out),
+ daemon_status,
ext_on_disk=False,
)
assert st.daemon_running and not st.extension_connected
@@ -78,10 +84,10 @@ def test_extension_never_installed_not_ready_with_store_guide():
def test_extension_files_on_disk_are_not_reported_as_loaded_or_ready():
"""A disabled/stale extension leaves files behind, so disk != loaded."""
- daemon_out = "Daemon: running (PID 1)\nExtension: disconnected\n"
+ daemon_status = {"ok": True, "pid": 1, "extensionConnected": False}
st, _ = _status_with(
ProbeResult("ok", output="1.8.3"),
- ProbeResult("ok", output=daemon_out),
+ daemon_status,
ext_on_disk=True,
)
assert not st.extension_connected
@@ -92,10 +98,10 @@ def test_extension_files_on_disk_are_not_reported_as_loaded_or_ready():
def test_unpacked_source_files_are_not_reported_as_loaded_or_ready():
- daemon_out = "Daemon: running (PID 1)\nExtension: disconnected\n"
+ daemon_status = {"ok": True, "pid": 1, "extensionConnected": False}
st, _ = _status_with(
ProbeResult("ok", output="1.8.3"),
- ProbeResult("ok", output=daemon_out),
+ daemon_status,
unpacked_files=True,
)
assert st.unpacked_extension_files
@@ -108,7 +114,7 @@ def test_unpacked_source_files_are_not_reported_as_loaded_or_ready():
def test_daemon_not_running_parsed_correctly():
st, _ = _status_with(
ProbeResult("ok", output="1.8.3"),
- ProbeResult("ok", output="Daemon: not running\n"),
+ None,
)
assert st.installed
assert not st.daemon_running
@@ -116,15 +122,13 @@ def test_daemon_not_running_parsed_correctly():
assert "自动启动" in opencli_summary(st)
-def test_probe_uses_daemon_status_not_doctor():
- """`opencli doctor` auto-starts the daemon (side effect) — health checks
- must only ever call `daemon status`."""
+def test_probe_never_executes_any_daemon_or_doctor_command():
+ """Even `daemon status` mutates ~/.opencli in current upstream releases."""
_, calls = _status_with(
ProbeResult("ok", output="1.8.3"),
- ProbeResult("ok", output="Daemon: not running\n"),
+ None,
)
- assert ["daemon", "status"] in calls
- assert ["doctor"] not in calls
+ assert calls == [["--version"]]
def test_opencli_probes_strip_deprecated_app_env_only_from_children(monkeypatch):
@@ -143,11 +147,12 @@ def test_opencli_probes_strip_deprecated_app_env_only_from_children(monkeypatch)
"error",
output="OPENCLI_DAEMON_PORT is no longer supported",
)
- if list(args) == ["--version"]:
- return ProbeResult("ok", output="1.8.6")
- return ProbeResult("ok", output="Daemon: not running\n")
+ return ProbeResult("ok", output="1.8.6")
with patch("agent_reach.backends.opencli.probe_command", side_effect=fake_probe), patch(
+ "agent_reach.backends.opencli._fetch_daemon_status",
+ return_value=None,
+ ), patch(
"agent_reach.backends.opencli._extension_installed_on_disk",
return_value=False,
):
@@ -156,7 +161,6 @@ def test_opencli_probes_strip_deprecated_app_env_only_from_children(monkeypatch)
assert status.installed and not status.broken
assert calls == [
(["--version"], ("OPENCLI_DAEMON_PORT",)),
- (["daemon", "status"], ("OPENCLI_DAEMON_PORT",)),
]
assert "OPENCLI_DAEMON_PORT" in __import__("os").environ
diff --git a/tests/test_reddit_channel.py b/tests/test_reddit_channel.py
index 32bbe7fe..f4232758 100644
--- a/tests/test_reddit_channel.py
+++ b/tests/test_reddit_channel.py
@@ -1,218 +1,226 @@
# -*- coding: utf-8 -*-
-"""Dedicated tests for the ``reddit`` channel.
-
-Reddit is a tier-1, multi-backend channel (OpenCLI → rdt-cli) with no
-zero-config path, so its ``check`` has the richest branching of the text
-channels: per-backend probing, ok/warn/error/off precedence, and a
-hand-rolled ``rdt status --json`` parse that must map every subprocess
-outcome onto the probe vocabulary. Follow-up to #331 — completes dedicated
-coverage after rss (#360), github (#361) and web (#363).
-"""
+"""Dedicated tests for Reddit's read-only multi-backend health check."""
+import json
+import time
from unittest.mock import Mock, patch
from agent_reach.channels.reddit import RedditChannel
-def _cp(stdout="", stderr="", returncode=0):
- m = Mock()
- m.stdout = stdout
- m.stderr = stderr
- m.returncode = returncode
- return m
-
-
-# --- can_handle ---
-
def test_can_handle_matches_reddit_hosts():
- ch = RedditChannel()
+ channel = RedditChannel()
for url in [
"https://reddit.com/r/python",
"https://www.reddit.com/r/python/comments/abc/title/",
"https://old.reddit.com/r/python",
"https://redd.it/abc123",
- "HTTPS://REDDIT.COM/r/Python", # case-insensitive netloc
+ "HTTPS://REDDIT.COM/r/Python",
]:
- assert ch.can_handle(url) is True, url
+ assert channel.can_handle(url) is True, url
def test_can_handle_rejects_non_reddit():
- ch = RedditChannel()
- # Matching is netloc-substring based (the codebase-wide convention), so
- # use hosts that genuinely don't contain the reddit markers.
+ channel = RedditChannel()
for url in ["https://example.com/r/python", "https://twitter.com/u", ""]:
- assert ch.can_handle(url) is False, url
+ assert channel.can_handle(url) is False, url
-# --- _check_rdt: map every subprocess outcome onto the probe vocabulary ---
-
def test_check_rdt_returns_none_when_not_installed():
- ch = RedditChannel()
with patch("shutil.which", return_value=None):
- assert ch._check_rdt() is None
+ assert RedditChannel()._check_rdt() is None
-def test_check_rdt_authenticated_with_username_is_ok():
- ch = RedditChannel()
- payload = '{"data": {"authenticated": true, "username": "alice"}}'
- with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", return_value=_cp(stdout=payload, returncode=0)
- ):
- status, message = ch._check_rdt()
- assert status == "ok"
- assert "alice" in message
-
+def test_check_rdt_missing_credential_is_warn():
+ with patch("shutil.which", return_value="/usr/local/bin/rdt"):
+ status, message = RedditChannel()._check_rdt()
-def test_check_rdt_authenticated_without_username_is_ok_no_suffix():
- ch = RedditChannel()
- payload = '{"data": {"authenticated": true}}'
+ assert status == "warn"
+ assert "Cookie-Editor" in message
+
+
+def test_check_rdt_saved_credential_is_unverified_not_false_ok(
+ isolated_home,
+):
+ path = isolated_home / ".config" / "rdt-cli" / "credential.json"
+ path.parent.mkdir(parents=True)
+ path.write_text(
+ json.dumps(
+ {
+ "cookies": {"reddit_session": "explicit"},
+ "saved_at": time.time(),
+ }
+ ),
+ encoding="utf-8",
+ )
with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", return_value=_cp(stdout=payload, returncode=0)
- ):
- status, message = ch._check_rdt()
- assert status == "ok"
- assert "已登录" not in message
-
+ "subprocess.run"
+ ) as run:
+ status, message = RedditChannel()._check_rdt()
-def test_check_rdt_not_authenticated_is_warn():
- ch = RedditChannel()
- payload = '{"data": {"authenticated": false}}'
- with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", return_value=_cp(stdout=payload, returncode=0)
- ):
- status, message = ch._check_rdt()
assert status == "warn"
- assert "未登录" in message
-
-
-def test_check_rdt_unparseable_status_is_warn():
- ch = RedditChannel()
+ assert "未实时验证" in message
+ run.assert_not_called()
+
+
+def test_check_rdt_stale_credential_is_not_refreshed(isolated_home):
+ path = isolated_home / ".config" / "rdt-cli" / "credential.json"
+ path.parent.mkdir(parents=True)
+ path.write_text(
+ json.dumps(
+ {
+ "cookies": {"reddit_session": "explicit"},
+ "saved_at": time.time() - 8 * 86400,
+ }
+ ),
+ encoding="utf-8",
+ )
+ before = path.read_bytes()
with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", return_value=_cp(stdout="not json", returncode=0)
- ):
- status, message = ch._check_rdt()
+ "subprocess.run"
+ ) as run:
+ status, message = RedditChannel()._check_rdt()
+
assert status == "warn"
- assert "无法解析" in message
+ assert "超过 7 天" in message
+ assert path.read_bytes() == before
+ run.assert_not_called()
-def test_check_rdt_broken_exit_code_is_error_with_venv_hint():
- ch = RedditChannel()
- with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", return_value=_cp(stderr="", returncode=127)
- ):
- status, message = ch._check_rdt()
- assert status == "error"
- assert "强制重装" in message # the venv-relink prescription
+def test_check_rdt_unparseable_credential_is_warn(isolated_home):
+ path = isolated_home / ".config" / "rdt-cli" / "credential.json"
+ path.parent.mkdir(parents=True)
+ path.write_text("not json", encoding="utf-8")
+ with patch("shutil.which", return_value="/usr/local/bin/rdt"):
+ status, message = RedditChannel()._check_rdt()
+ assert status == "warn"
+ assert "无法安全解析" in message
-def test_check_rdt_nonzero_exit_reports_tail():
- ch = RedditChannel()
- with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", return_value=_cp(stderr="boom: network down", returncode=1)
- ):
- status, message = ch._check_rdt()
- assert status == "error"
- assert "exit 1" in message
- assert "boom: network down" in message
+def test_check_rdt_refuses_symlink_credential(isolated_home):
+ victim = isolated_home / "victim.json"
+ victim.write_text('{"secret": "do-not-read"}', encoding="utf-8")
+ path = isolated_home / ".config" / "rdt-cli" / "credential.json"
+ path.parent.mkdir(parents=True)
+ path.symlink_to(victim)
+ with patch("shutil.which", return_value="/usr/local/bin/rdt"):
+ status, message = RedditChannel()._check_rdt()
-def test_check_rdt_timeout_is_error():
- import subprocess
- ch = RedditChannel()
- with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", side_effect=subprocess.TimeoutExpired(cmd="rdt", timeout=10)
- ):
- status, message = ch._check_rdt()
- assert status == "error"
- assert "超时" in message
+ assert status == "warn"
+ assert "符号链接" in message
-def test_check_rdt_oserror_is_broken():
- ch = RedditChannel()
- with patch("shutil.which", return_value="/usr/local/bin/rdt"), patch(
- "subprocess.run", side_effect=OSError("exec format error")
- ):
- status, message = ch._check_rdt()
- assert status == "error"
- assert "强制重装" in message
+def test_check_rdt_refuses_ancestor_symlink(isolated_home):
+ victim_dir = isolated_home / "victim-config"
+ credential_path = victim_dir / "rdt-cli" / "credential.json"
+ credential_path.parent.mkdir(parents=True)
+ credential_path.write_text(
+ '{"cookies": {"reddit_session": "do-not-read"}}',
+ encoding="utf-8",
+ )
+ (isolated_home / ".config").symlink_to(
+ victim_dir,
+ target_is_directory=True,
+ )
+ with patch("shutil.which", return_value="/usr/local/bin/rdt"):
+ status, message = RedditChannel()._check_rdt()
+
+ assert status == "warn"
+ assert "符号链接" in message
-# --- _check_opencli: maps OpenCLIStatus onto the probe vocabulary ---
def _opencli(installed=True, broken=False, ready=True, hint=""):
return Mock(installed=installed, broken=broken, ready=ready, hint=hint)
def test_check_opencli_not_installed_is_none():
- ch = RedditChannel()
- with patch("agent_reach.backends.opencli_status", return_value=_opencli(installed=False)):
- assert ch._check_opencli() is None
+ with patch(
+ "agent_reach.backends.opencli_status",
+ return_value=_opencli(installed=False),
+ ):
+ assert RedditChannel()._check_opencli() is None
def test_check_opencli_broken_is_error():
- ch = RedditChannel()
- with patch("agent_reach.backends.opencli_status",
- return_value=_opencli(broken=True, hint="reinstall opencli")):
- status, message = ch._check_opencli()
+ with patch(
+ "agent_reach.backends.opencli_status",
+ return_value=_opencli(broken=True, hint="reinstall opencli"),
+ ):
+ status, message = RedditChannel()._check_opencli()
assert status == "error"
assert message == "reinstall opencli"
-def test_check_opencli_ready_is_ok():
- ch = RedditChannel()
- with patch("agent_reach.backends.opencli_status", return_value=_opencli(ready=True)):
- status, message = ch._check_opencli()
- assert status == "ok"
- assert "OpenCLI" in message
+def test_check_opencli_bridge_ready_is_unverified():
+ with patch(
+ "agent_reach.backends.opencli_status",
+ return_value=_opencli(ready=True),
+ ):
+ status, message = RedditChannel()._check_opencli()
+ assert status == "warn"
+ assert "桥接已连接" in message
+ assert "登录态和实际命令未实时验证" in message
def test_check_opencli_installed_not_ready_is_warn():
- ch = RedditChannel()
- with patch("agent_reach.backends.opencli_status",
- return_value=_opencli(ready=False, hint="connect the extension")):
- status, message = ch._check_opencli()
+ with patch(
+ "agent_reach.backends.opencli_status",
+ return_value=_opencli(ready=False, hint="connect the extension"),
+ ):
+ status, message = RedditChannel()._check_opencli()
assert status == "warn"
assert message == "connect the extension"
-# --- check(): precedence across backends + active_backend selection ---
-
def test_check_prefers_ok_over_warn_regardless_of_probe_order():
- # OpenCLI probes first and only warns; rdt-cli is fully ok. The ok
- # backend must win and become active even though it was probed second.
- ch = RedditChannel()
- with patch.object(ch, "_check_opencli", return_value=("warn", "opencli sleepy")), \
- patch.object(ch, "_check_rdt", return_value=("ok", "rdt ready")):
- status, message = ch.check()
+ channel = RedditChannel()
+ with patch.object(
+ channel, "_check_opencli", return_value=("warn", "opencli sleepy")
+ ), patch.object(
+ channel, "_check_rdt", return_value=("ok", "rdt ready")
+ ):
+ status, message = channel.check()
+
assert status == "ok"
assert message == "rdt ready"
- assert ch.active_backend == "rdt-cli"
+ assert channel.active_backend == "rdt-cli"
-def test_check_first_ok_backend_becomes_active():
- ch = RedditChannel()
- with patch.object(ch, "_check_opencli", return_value=("ok", "opencli ready")), \
- patch.object(ch, "_check_rdt", return_value=("warn", "rdt not logged in")):
- status, _ = ch.check()
- assert status == "ok"
- assert ch.active_backend == "OpenCLI"
+def test_check_warn_has_no_active_backend():
+ channel = RedditChannel()
+ with patch.object(
+ channel, "_check_opencli", return_value=("warn", "not ready")
+ ), patch.object(
+ channel, "_check_rdt", return_value=("warn", "unverified")
+ ):
+ status, message = channel.check()
+
+ assert status == "warn"
+ assert message == "not ready"
+ assert channel.active_backend is None
def test_check_all_errors_returns_error_and_no_active_backend():
- ch = RedditChannel()
- with patch.object(ch, "_check_opencli", return_value=("error", "e1")), \
- patch.object(ch, "_check_rdt", return_value=("error", "e2")):
- status, message = ch.check()
+ channel = RedditChannel()
+ with patch.object(
+ channel, "_check_opencli", return_value=("error", "e1")
+ ), patch.object(channel, "_check_rdt", return_value=("error", "e2")):
+ status, message = channel.check()
+
assert status == "error"
assert "e1" in message and "e2" in message
- assert ch.active_backend is None
+ assert channel.active_backend is None
def test_check_no_backend_installed_is_off():
- ch = RedditChannel()
- with patch.object(ch, "_check_opencli", return_value=None), \
- patch.object(ch, "_check_rdt", return_value=None):
- status, message = ch.check()
+ channel = RedditChannel()
+ with patch.object(channel, "_check_opencli", return_value=None), patch.object(
+ channel, "_check_rdt", return_value=None
+ ):
+ status, message = channel.check()
+
assert status == "off"
- assert "零配置" in message # "no zero-config path" guidance
- assert ch.active_backend is None
+ assert "零配置" in message
+ assert channel.active_backend is None
diff --git a/tests/test_scrub_credentials.py b/tests/test_scrub_credentials.py
index 2e669ae5..4687326c 100644
--- a/tests/test_scrub_credentials.py
+++ b/tests/test_scrub_credentials.py
@@ -63,7 +63,7 @@ def test_leaves_non_secret_urls_and_plain_text_unchanged():
],
)
def test_channel_health_messages_scrub_url_secrets(module, channel, monkeypatch):
- def fail(_url):
+ def fail(_url, *_args, **_kwargs):
raise RuntimeError(
"proxy http://user:[email protected]:8080 refused "
"https://api.test/data?access_token=top-secret"
diff --git a/tests/test_twitter_channel.py b/tests/test_twitter_channel.py
index b77d26e8..12dc2251 100644
--- a/tests/test_twitter_channel.py
+++ b/tests/test_twitter_channel.py
@@ -1,38 +1,36 @@
# -*- coding: utf-8 -*-
+"""Twitter health checks must never trigger upstream browser-cookie fallback."""
import os
from unittest.mock import Mock, patch
-from agent_reach.channels.twitter import TwitterChannel
+from agent_reach.backends import OpenCLIStatus
+from agent_reach.channels.twitter import (
+ TwitterChannel,
+ twitter_cli_child_env,
+)
-def _cp(stdout="", stderr="", returncode=0):
- m = Mock()
- m.stdout = stdout
- m.stderr = stderr
- m.returncode = returncode
- return m
+def _which(*present):
+ return lambda name: f"/usr/local/bin/{name}" if name in present else None
-# --- twitter-cli tests ---
-
-def test_check_twitter_cli_found_and_auth_ok():
- """twitter-cli found + twitter status ok → ok."""
+def test_twitter_cli_without_explicit_auth_is_unverified():
channel = TwitterChannel()
- with patch("shutil.which", side_effect=lambda name: "/usr/local/bin/twitter" if name == "twitter" else None), patch(
+ with patch("shutil.which", side_effect=_which("twitter")), patch(
"subprocess.run",
- return_value=_cp(stdout="ok: true\nusername: testuser\n", returncode=0),
+ side_effect=AssertionError("twitter status must not run"),
):
status, message = channel.check()
- assert status == "ok"
- assert "twitter-cli" in message
- assert "完整可用" in message
- assert channel.active_backend == "twitter-cli"
+ assert status == "warn"
+ assert "Cookie-Editor" in message
+ assert channel.active_backend is None
-def test_check_uses_credentials_saved_by_agent_reach_only_in_child_env(monkeypatch):
- """Saved cookies must make the independent doctor probe authenticated."""
- channel = TwitterChannel()
+
+def test_saved_credentials_are_recognised_without_starting_upstream(
+ monkeypatch,
+):
config = Mock()
config.get.side_effect = lambda key: {
"twitter_auth_token": "saved-auth-token",
@@ -41,25 +39,24 @@ def test_check_uses_credentials_saved_by_agent_reach_only_in_child_env(monkeypat
monkeypatch.delenv("TWITTER_AUTH_TOKEN", raising=False)
monkeypatch.delenv("TWITTER_CT0", raising=False)
- with patch(
- "shutil.which",
- side_effect=lambda name: "/usr/local/bin/twitter" if name == "twitter" else None,
- ), patch(
- "subprocess.run",
- return_value=_cp(stdout="ok: true\n", returncode=0),
+ with patch("shutil.which", side_effect=_which("twitter")), patch(
+ "subprocess.run"
) as run:
- status, _ = channel.check(config)
+ channel = TwitterChannel()
+ status, message = channel.check(config)
- child_env = run.call_args.kwargs["env"]
- assert status == "ok"
- assert child_env["TWITTER_AUTH_TOKEN"] == "saved-auth-token"
- assert child_env["TWITTER_CT0"] == "saved-ct0"
+ assert status == "warn"
+ assert "已配置" in message
+ assert "不会执行" in message
+ assert channel.active_backend is None
+ run.assert_not_called()
assert "TWITTER_AUTH_TOKEN" not in os.environ
assert "TWITTER_CT0" not in os.environ
-def test_existing_twitter_env_takes_priority_over_saved_config(monkeypatch):
- channel = TwitterChannel()
+def test_child_env_keeps_existing_shell_credentials_authoritative(
+ monkeypatch,
+):
config = Mock()
config.get.side_effect = lambda key: {
"twitter_auth_token": "saved-auth-token",
@@ -68,173 +65,107 @@ def test_existing_twitter_env_takes_priority_over_saved_config(monkeypatch):
monkeypatch.setenv("TWITTER_AUTH_TOKEN", "shell-auth-token")
monkeypatch.setenv("TWITTER_CT0", "shell-ct0")
- with patch(
- "shutil.which",
- side_effect=lambda name: "/usr/local/bin/twitter" if name == "twitter" else None,
- ), patch(
- "subprocess.run",
- return_value=_cp(stdout="ok: true\n", returncode=0),
- ) as run:
- status, _ = channel.check(config)
-
- child_env = run.call_args.kwargs["env"]
- assert status == "ok"
- assert child_env["TWITTER_AUTH_TOKEN"] == "shell-auth-token"
- assert child_env["TWITTER_CT0"] == "shell-ct0"
+ assert twitter_cli_child_env(config) == {}
assert os.environ["TWITTER_AUTH_TOKEN"] == "shell-auth-token"
assert os.environ["TWITTER_CT0"] == "shell-ct0"
-def test_check_twitter_cli_found_auth_missing():
- """twitter-cli found + not_authenticated → warn about auth."""
- channel = TwitterChannel()
- with patch("shutil.which", side_effect=lambda name: "/usr/local/bin/twitter" if name == "twitter" else None), patch(
- "subprocess.run",
- return_value=_cp(
- stderr="ok: false\nerror:\n code: not_authenticated\n",
- returncode=1,
- ),
- ):
- status, message = channel.check()
- assert status == "warn"
- assert "未认证" in message
- # 未认证是业务态:工具进程活着,后端仍可用
- assert channel.active_backend == "twitter-cli"
+def test_child_env_supplies_only_missing_saved_credentials(monkeypatch):
+ config = Mock()
+ config.get.side_effect = lambda key: {
+ "twitter_auth_token": "saved-auth-token",
+ "twitter_ct0": "saved-ct0",
+ }.get(key)
+ monkeypatch.setenv("TWITTER_AUTH_TOKEN", "shell-auth-token")
+ monkeypatch.delenv("TWITTER_CT0", raising=False)
+ assert twitter_cli_child_env(config) == {"TWITTER_CT0": "saved-ct0"}
-# --- bird CLI fallback tests ---
-def test_check_bird_fallback_auth_ok():
- """No twitter-cli, but bird found + bird check ok → ok."""
- channel = TwitterChannel()
- def which_side_effect(name):
- if name == "bird":
- return "/usr/local/bin/bird"
- return None
- with patch("shutil.which", side_effect=which_side_effect), patch(
+def test_bird_with_explicit_env_remains_unverified(monkeypatch):
+ monkeypatch.setenv("AUTH_TOKEN", "explicit-auth")
+ monkeypatch.setenv("CT0", "explicit-ct0")
+ with patch("shutil.which", side_effect=_which("bird")), patch(
"subprocess.run",
- return_value=_cp(stdout="Authenticated as @user\n", returncode=0),
+ side_effect=AssertionError("bird check must not run"),
):
+ channel = TwitterChannel()
status, message = channel.check()
- assert status == "ok"
- assert "bird" in message
- assert channel.active_backend == "bird CLI (legacy)"
-
-def test_check_bird_fallback_auth_missing():
- """No twitter-cli, bird found but Missing credentials → warn."""
- channel = TwitterChannel()
- def which_side_effect(name):
- if name == "bird":
- return "/usr/local/bin/bird"
- return None
- with patch("shutil.which", side_effect=which_side_effect), patch(
- "subprocess.run",
- return_value=_cp(stderr="Missing credentials\n", returncode=1),
- ):
- status, message = channel.check()
assert status == "warn"
- assert "未配置认证" in message
-
+ assert "未实时验证" in message
+ assert channel.active_backend is None
-# --- neither installed ---
-def test_check_nothing_installed():
- """Neither twitter-cli nor bird → warn with install hint."""
- channel = TwitterChannel()
- with patch("shutil.which", return_value=None):
+def test_bird_without_explicit_env_is_warn(monkeypatch):
+ monkeypatch.delenv("AUTH_TOKEN", raising=False)
+ monkeypatch.delenv("CT0", raising=False)
+ with patch("shutil.which", side_effect=_which("bird")):
+ channel = TwitterChannel()
status, message = channel.check()
+
assert status == "warn"
- assert "twitter-cli" in message
+ assert "未检测到显式" in message
assert channel.active_backend is None
-# --- twitter-cli preferred over bird ---
-
-def test_twitter_cli_preferred_over_bird():
- """When both are installed, twitter-cli is used."""
+def test_nothing_installed_returns_install_hint():
channel = TwitterChannel()
- def which_side_effect(name):
- if name == "twitter":
- return "/usr/local/bin/twitter"
- if name == "bird":
- return "/usr/local/bin/bird"
- return None
- with patch("shutil.which", side_effect=which_side_effect), patch(
- "subprocess.run",
- return_value=_cp(stdout="ok: true\n", returncode=0),
- ):
+ with patch("shutil.which", return_value=None):
status, message = channel.check()
- assert status == "ok"
- assert "twitter-cli" in message
- assert channel.active_backend == "twitter-cli"
-
-# --- broken install (stale venv shim) ---
-
-def test_check_twitter_cli_broken_reports_error_with_reinstall_hint():
- """which 命中但 exec 抛 FileNotFoundError(venv 断链)→ error + 重装处方。"""
- channel = TwitterChannel()
- with patch(
- "shutil.which",
- side_effect=lambda name: "/usr/local/bin/twitter" if name == "twitter" else None,
- ), patch("subprocess.run", side_effect=FileNotFoundError("/usr/local/bin/twitter")):
- status, message = channel.check()
- assert status == "error"
- assert "无法执行" in message
- assert "uv tool install --force twitter-cli" in message
- assert "pipx reinstall twitter-cli" in message
+ assert status == "warn"
+ assert "twitter-cli" in message
assert channel.active_backend is None
-def test_check_twitter_cli_broken_falls_back_to_bird():
- """twitter-cli 断链但 bird 健康 → 回退到 bird,后端正确归属。"""
- channel = TwitterChannel()
-
- def which_side_effect(name):
- if name in ("twitter", "bird"):
- return f"/usr/local/bin/{name}"
- return None
-
- def run_side_effect(cmd, **kwargs):
- if "twitter" in cmd[0]:
- raise FileNotFoundError(cmd[0])
- return _cp(stdout="Authenticated as @user\n", returncode=0)
-
- with patch("shutil.which", side_effect=which_side_effect), patch(
- "subprocess.run", side_effect=run_side_effect
+def test_opencli_bridge_ready_is_unverified_for_twitter():
+ with patch(
+ "agent_reach.backends.opencli_status",
+ return_value=OpenCLIStatus(
+ installed=True,
+ extension_connected=True,
+ version="1.8.6",
+ ),
):
- status, message = channel.check()
- assert status == "ok"
- assert "bird" in message
- assert channel.active_backend == "bird CLI (legacy)"
+ status, message = TwitterChannel()._check_opencli()
+ assert status == "warn"
+ assert "桥接已连接" in message
+ assert "登录态和实际命令未实时验证" in message
-def test_unauthenticated_twitter_cli_does_not_block_working_opencli():
- """warn 候选不得屏蔽排在后面的 ok 候选(Codex review 发现)。"""
+
+def test_verified_backend_result_wins_over_unverified_twitter_cli():
channel = TwitterChannel()
with patch.object(
- TwitterChannel, "_check_twitter_cli",
- return_value=("warn", "twitter-cli 已安装但未认证"),
+ TwitterChannel,
+ "_check_twitter_cli",
+ return_value=("warn", "twitter-cli 未验证"),
), patch.object(
- TwitterChannel, "_check_opencli",
- return_value=("ok", "OpenCLI 可用(复用浏览器登录态)"),
+ TwitterChannel,
+ "_check_opencli",
+ return_value=("ok", "OpenCLI 可用"),
), patch.object(TwitterChannel, "_check_bird", return_value=None):
- status, msg = channel.check()
+ status, message = channel.check()
+
assert status == "ok"
+ assert message == "OpenCLI 可用"
assert channel.active_backend == "OpenCLI"
-def test_all_warn_falls_back_to_first_warn():
+def test_all_warn_returns_first_warning_without_active_backend():
channel = TwitterChannel()
with patch.object(
- TwitterChannel, "_check_twitter_cli",
- return_value=("warn", "twitter-cli 未认证"),
+ TwitterChannel,
+ "_check_twitter_cli",
+ return_value=("warn", "twitter-cli 未验证"),
), patch.object(
- TwitterChannel, "_check_opencli",
+ TwitterChannel,
+ "_check_opencli",
return_value=("warn", "扩展未连接"),
), patch.object(TwitterChannel, "_check_bird", return_value=None):
- status, msg = channel.check()
+ status, message = channel.check()
+
assert status == "warn"
- assert channel.active_backend == "twitter-cli"
- assert "未认证" in msg
+ assert message == "twitter-cli 未验证"
+ assert channel.active_backend is None
diff --git a/tests/test_url_security.py b/tests/test_url_security.py
index c8330bd7..e7f5255e 100644
--- a/tests/test_url_security.py
+++ b/tests/test_url_security.py
@@ -14,6 +14,7 @@ from agent_reach.channels.xiaohongshu import XiaoHongShuChannel
from agent_reach.channels.xiaoyuzhou import XiaoyuzhouChannel
from agent_reach.channels.xueqiu import XueqiuChannel
from agent_reach.channels.youtube import YouTubeChannel
+from agent_reach.utils.url import host_matches
@pytest.mark.parametrize(
@@ -123,3 +124,16 @@ def test_fixed_domain_channels_reject_suffix_lookalikes_and_userinfo(
assert not channel.can_handle(f"https://{official_domain}.evil.test/path")
assert not channel.can_handle(f"https://{official_domain}@evil.test/path")
assert not channel.can_handle(f"https://user:pass@{official_domain}/path")
+
+
+ "malicious_url",
+ [
+ "https://x.com:not-a-port/path",
+ "https://x.com:65536/path",
+ "https://x.com:-1/path",
+ "https://x.com:999999999999/path",
+ ],
+)
+def test_host_matches_rejects_invalid_ports(malicious_url):
+ assert not host_matches(malicious_url, "x.com")
diff --git a/tests/test_xueqiu_channel.py b/tests/test_xueqiu_channel.py
index 8922f546..9b8fda66 100644
--- a/tests/test_xueqiu_channel.py
+++ b/tests/test_xueqiu_channel.py
@@ -43,7 +43,7 @@ def test_check_validates_detail_quote_endpoint():
with patch.object(
xq,
"_get_json",
- side_effect=lambda url: requested.append(url)
+ side_effect=lambda url, config=None: requested.append(url)
or {"data": {"quote": {"symbol": "SH601138", "pe_ttm": 38.1}}},
):
status, message = ch.check()
@@ -82,7 +82,11 @@ def test_check_never_reads_browser_cookie_store_implicitly(monkeypatch):
)
monkeypatch.setitem(sys.modules, "rookiepy", fake_rookiepy)
monkeypatch.setattr(xq, "_cookies_initialized", False)
- monkeypatch.setattr(xq, "_load_cookies_from_config", lambda: False)
+ monkeypatch.setattr(
+ xq,
+ "_load_cookies_from_config",
+ lambda config=None: False,
+ )
class FakeResponse:
def __enter__(self):