feat(network): centralize proxy settings and add MCP routing (NAN-315) (#6372)
* feat(network): share proxy settings across features and MCP (NAN-315) * fix(network): address shared proxy review regressions * test(network): align rebased OAuth fixtures with runtime admission * fix(webui): configure shared proxy without leaving connection drafts * feat(webui): add optional shared proxy authentication editor * fix(webui): align proxy save tests and loading skeleton
This commit is contained in:
1 parent
872a83340d
commit
084b6bb394
181 files changed
+3740
-807
No files matched your search
@@ -61,6 +61,7 @@ from nanobot.bus.outbound_events import (
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
|
||||
from nanobot.command.router import command_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
|
||||
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
|
||||
from nanobot.llm_usage.context import source_from_request
|
||||
@@ -301,6 +302,7 @@ class AgentLoop:
|
||||
unified_session: bool = False,
|
||||
disabled_skills: list[str] | None = None,
|
||||
tools_config: ToolsConfig | None = None,
|
||||
network_config: NetworkConfig | None = None,
|
||||
provider_snapshot_loader: Callable[..., ProviderSnapshot] | None = None,
|
||||
provider_signature: tuple[object, ...] | None = None,
|
||||
model_presets: dict[str, ModelPresetConfig] | None = None,
|
||||
@@ -367,6 +369,7 @@ class AgentLoop:
|
||||
else defaults.tool_hint_max_length
|
||||
)
|
||||
self.tools_config = _tc
|
||||
self.network_config = network_config or NetworkConfig()
|
||||
self.web_config = _tc.web
|
||||
self.exec_config = _tc.exec
|
||||
self.cron_service = cron_service
|
||||
@@ -406,6 +409,7 @@ class AgentLoop:
|
||||
workspace=workspace,
|
||||
bus=bus,
|
||||
tools_config=_tc,
|
||||
network_config=self.network_config,
|
||||
max_tool_result_chars=self.max_tool_result_chars,
|
||||
restrict_to_workspace=restrict_to_workspace,
|
||||
disabled_skills=disabled_skills,
|
||||
@@ -519,6 +523,7 @@ class AgentLoop:
|
||||
session_ttl_minutes=defaults.session_ttl_minutes,
|
||||
idle_compact_check_interval_seconds=defaults.idle_compact_check_interval_seconds,
|
||||
tools_config=config.tools,
|
||||
network_config=config.network,
|
||||
model_presets=preset_helpers.configured_model_presets(config),
|
||||
model_preset=defaults.model_preset,
|
||||
dream_model_preset=defaults.dream.model_override,
|
||||
@@ -656,6 +661,7 @@ class AgentLoop:
|
||||
self.register_runtime_context_provider(runtime_control.workspace_context)
|
||||
ctx = ToolContext(
|
||||
config=self.tools_config,
|
||||
network=self.network_config,
|
||||
workspace=str(self.workspace),
|
||||
bus=self.bus,
|
||||
subagent_manager=self.subagents,
|
||||
|
||||
@@ -38,6 +38,7 @@ from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventContext, SubagentTaskChanged
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import AgentDefaults, ToolsConfig
|
||||
from nanobot.events import AgentEvent, EventSink
|
||||
from nanobot.llm_usage.context import LLMUsageSource, current_llm_usage_source
|
||||
@@ -220,6 +221,7 @@ class SubagentManager:
|
||||
max_concurrent_subagents: int | None = None,
|
||||
*,
|
||||
consolidator: Consolidator,
|
||||
network_config: NetworkConfig | None = None,
|
||||
session_manager: SessionManager | None = None,
|
||||
):
|
||||
if cast(object, consolidator) is None:
|
||||
@@ -252,6 +254,7 @@ class SubagentManager:
|
||||
self.workspace = workspace
|
||||
self.bus = bus
|
||||
self.tools_config = tools_config or ToolsConfig()
|
||||
self.network_config = network_config or NetworkConfig()
|
||||
self.max_tool_result_chars = max_tool_result_chars
|
||||
self.restrict_to_workspace = restrict_to_workspace
|
||||
self.disabled_skills = set(disabled_skills or [])
|
||||
@@ -526,6 +529,7 @@ class SubagentManager:
|
||||
cfg = tools_config if tools_config is not None else self._subagent_tools_config()
|
||||
ctx = ToolContext(
|
||||
config=cfg,
|
||||
network=self.network_config,
|
||||
workspace=str(root.resolve()),
|
||||
exec_session_manager=exec_manager or self._exec_session_manager,
|
||||
file_state_store=FileStates(),
|
||||
|
||||
@@ -7,6 +7,8 @@ from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable
|
||||
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.exec_session import ExecSessionManager
|
||||
@@ -92,6 +94,7 @@ def current_request_session_key() -> str | None:
|
||||
class ToolContext:
|
||||
config: ToolsConfig
|
||||
workspace: str
|
||||
network: NetworkConfig = field(default_factory=NetworkConfig)
|
||||
bus: MessageBus | None = None
|
||||
subagent_manager: SubagentManager | None = None
|
||||
cron_service: CronService | None = None
|
||||
|
||||
@@ -17,6 +17,7 @@ from nanobot.agent.tools.schema import (
|
||||
StringSchema,
|
||||
tool_parameters_schema,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.providers.image_generation import (
|
||||
ImageGenerationError,
|
||||
@@ -81,6 +82,7 @@ class ImageGenerationTool(Tool):
|
||||
workspace=ctx.workspace,
|
||||
config=ctx.config.image_generation,
|
||||
provider_configs=image_gen_provider_configs(ctx.providers_config),
|
||||
network=ctx.network,
|
||||
)
|
||||
|
||||
def __init__(
|
||||
@@ -90,9 +92,11 @@ class ImageGenerationTool(Tool):
|
||||
config: ImageGenerationToolConfig,
|
||||
provider_config: ProviderConfig | None = None,
|
||||
provider_configs: dict[str, ProviderConfig] | None = None,
|
||||
network: NetworkConfig | None = None,
|
||||
) -> None:
|
||||
self.workspace = Path(workspace).expanduser()
|
||||
self.config = config
|
||||
self.network = network or NetworkConfig()
|
||||
self.provider_configs = dict(provider_configs or {})
|
||||
if provider_config is not None and "openrouter" not in self.provider_configs:
|
||||
self.provider_configs["openrouter"] = provider_config
|
||||
@@ -126,7 +130,7 @@ class ImageGenerationTool(Tool):
|
||||
"api_base": provider.api_base if provider and isinstance(provider.api_base, str) else None,
|
||||
"extra_headers": headers or None,
|
||||
"extra_body": body or None,
|
||||
"proxy": provider.proxy if provider and isinstance(provider.proxy, str) else None,
|
||||
"proxy": self.network.resolve_proxy(provider.use_proxy) if provider else None,
|
||||
}
|
||||
return cls(**kwargs)
|
||||
|
||||
@@ -218,6 +222,7 @@ def register_image_generation_tool(
|
||||
|
||||
ctx = ToolContext(
|
||||
config=config.tools,
|
||||
network=config.network,
|
||||
workspace=str(workspace),
|
||||
providers_config=config.providers,
|
||||
)
|
||||
|
||||
+56
-17
@@ -8,6 +8,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import traceback
|
||||
import urllib.parse
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mapping
|
||||
from contextlib import AsyncExitStack, suppress
|
||||
@@ -19,6 +20,7 @@ from loguru import logger
|
||||
from nanobot.agent.tools.base import Tool, ToolResult
|
||||
from nanobot.agent.tools.context import tool_log_content_allowed
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.security.network import (
|
||||
PinnedDNSAsyncTransport,
|
||||
env_proxy_applies_to_url,
|
||||
@@ -60,7 +62,7 @@ _HTTP_READ_TIMEOUT = 300.0
|
||||
# Replace anything outside [a-zA-Z0-9_-] with underscore and collapse runs.
|
||||
_SANITIZE_RE = re.compile(r"_+")
|
||||
_ReconnectCallback = Callable[[str, str, Tool], Awaitable[Tool | None]]
|
||||
MCPServerLoader = Callable[[], Mapping[str, "MCPServerConfig"]]
|
||||
MCPServerLoader = Callable[[], tuple[Mapping[str, "MCPServerConfig"], NetworkConfig]]
|
||||
MCPRuntimeStatus = Literal["connecting", "connected", "failed"]
|
||||
|
||||
|
||||
@@ -216,8 +218,26 @@ def _is_transient_connection_failure(exc: BaseException) -> bool:
|
||||
return isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)) or _is_transient(exc)
|
||||
|
||||
|
||||
def _log_mcp_connection_failure(name: str, exc: BaseException, hint: str = "") -> None:
|
||||
exception = exc if tool_log_content_allowed() else False
|
||||
def _log_mcp_connection_failure(
|
||||
name: str, exc: BaseException, hint: str = "", *, proxy: str | None = None,
|
||||
) -> None:
|
||||
exception: Exception | bool = False
|
||||
if tool_log_content_allowed():
|
||||
details = "".join(traceback.TracebackException.from_exception(
|
||||
exc, capture_locals=False,
|
||||
).format())
|
||||
if proxy:
|
||||
for value in (proxy, urllib.parse.unquote(proxy)):
|
||||
details = details.replace(value, _redact_url(proxy))
|
||||
# Match userinfo only with its URL delimiter, never isolated short
|
||||
# credentials that could rewrite exception types or stack text.
|
||||
userinfo = urllib.parse.urlsplit(proxy).netloc.rpartition("@")[0]
|
||||
if userinfo:
|
||||
for value in (userinfo, urllib.parse.unquote(userinfo)):
|
||||
details = details.replace(f"{value}@", "[redacted]@")
|
||||
# Keep exception-aware sinks, but never give Loguru live frames or a raw
|
||||
# exception chain: diagnose=True would render credential-bearing locals.
|
||||
exception = Exception("\n" + details.rstrip())
|
||||
if _is_transient_connection_failure(exc):
|
||||
logger.warning("MCP server '{}': transient connection failure", name)
|
||||
logger.opt(exception=exception).debug(
|
||||
@@ -242,7 +262,7 @@ def _is_session_terminated(exc: BaseException) -> bool:
|
||||
)
|
||||
|
||||
|
||||
async def _probe_http_url(url: str, timeout: float = 3.0) -> bool:
|
||||
async def _probe_http_url(url: str, timeout: float = 3.0, *, proxy: str | None = None) -> bool:
|
||||
"""Quick TCP probe to check if an HTTP MCP server is reachable.
|
||||
|
||||
Avoids entering ``streamable_http_client`` / ``sse_client`` when the port is
|
||||
@@ -258,7 +278,7 @@ async def _probe_http_url(url: str, timeout: float = 3.0) -> bool:
|
||||
ok, _, resolved_ips = resolve_url_target(url)
|
||||
if not ok:
|
||||
return False
|
||||
if env_proxy_applies_to_url(url):
|
||||
if proxy or env_proxy_applies_to_url(url):
|
||||
return True
|
||||
for target_host in resolved_ips or (host,):
|
||||
try:
|
||||
@@ -294,7 +314,9 @@ def _redact_url(url: str) -> str:
|
||||
return "<redacted-url>"
|
||||
|
||||
|
||||
def _pinned_transport_kwargs() -> dict[str, Any]:
|
||||
def _pinned_transport_kwargs(proxy: str | None = None) -> dict[str, Any]:
|
||||
if proxy:
|
||||
return {"transport": httpx.AsyncHTTPTransport(proxy=proxy), "trust_env": False}
|
||||
kwargs: dict[str, Any] = {"transport": PinnedDNSAsyncTransport()}
|
||||
mounts = httpx_env_proxy_mounts()
|
||||
if mounts:
|
||||
@@ -1008,6 +1030,7 @@ async def connect_mcp_servers(
|
||||
registry: ToolRegistry,
|
||||
*,
|
||||
oauth_handlers: Mapping[str, MCPOAuthHandlers] | None = None,
|
||||
network: NetworkConfig | None = None,
|
||||
) -> dict[str, MCPConnection]:
|
||||
"""Connect to configured MCP servers and register their tools, resources, prompts.
|
||||
|
||||
@@ -1020,6 +1043,10 @@ async def connect_mcp_servers(
|
||||
from mcp.client.stdio import stdio_client
|
||||
from mcp.client.streamable_http import streamable_http_client
|
||||
|
||||
# Stack-exit failures are logged outside open_single_server; retain the exact
|
||||
# selected value there too, including credentials resolved from environment refs.
|
||||
selected_proxies: dict[str, str | None] = {}
|
||||
|
||||
async def open_single_server(
|
||||
name: str, cfg: MCPServerConfig, server_stack: AsyncExitStack
|
||||
) -> bool:
|
||||
@@ -1047,6 +1074,10 @@ async def connect_mcp_servers(
|
||||
)
|
||||
return False
|
||||
|
||||
if cfg.use_proxy and transport_type == "stdio":
|
||||
raise ValueError("The shared proxy is available for HTTP and SSE MCP connections")
|
||||
proxy = (network or NetworkConfig()).resolve_proxy(cfg.use_proxy)
|
||||
selected_proxies[name] = proxy
|
||||
oauth_auth: httpx.Auth | None = None
|
||||
if cfg.auth == "oauth":
|
||||
if transport_type not in {"sse", "streamableHttp"}:
|
||||
@@ -1084,7 +1115,7 @@ async def connect_mcp_servers(
|
||||
)
|
||||
read, write = await server_stack.enter_async_context(stdio_client(params))
|
||||
elif transport_type == "sse":
|
||||
if not await _probe_http_url(cfg.url):
|
||||
if not await _probe_http_url(cfg.url, proxy=proxy):
|
||||
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
|
||||
return False
|
||||
|
||||
@@ -1104,7 +1135,7 @@ async def connect_mcp_servers(
|
||||
follow_redirects=True,
|
||||
timeout=timeout,
|
||||
auth=auth,
|
||||
**_pinned_transport_kwargs(),
|
||||
**_pinned_transport_kwargs(proxy),
|
||||
)
|
||||
|
||||
sse_kwargs: dict[str, Any] = {
|
||||
@@ -1116,7 +1147,7 @@ async def connect_mcp_servers(
|
||||
sse_client(cfg.url, **sse_kwargs)
|
||||
)
|
||||
elif transport_type == "streamableHttp":
|
||||
if not await _probe_http_url(cfg.url):
|
||||
if not await _probe_http_url(cfg.url, proxy=proxy):
|
||||
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
|
||||
return False
|
||||
|
||||
@@ -1131,7 +1162,7 @@ async def connect_mcp_servers(
|
||||
connect=10.0,
|
||||
read=max(_HTTP_READ_TIMEOUT, cfg.tool_timeout),
|
||||
),
|
||||
**_pinned_transport_kwargs(),
|
||||
**_pinned_transport_kwargs(proxy),
|
||||
}
|
||||
if oauth_auth is not None:
|
||||
http_client_kwargs["auth"] = oauth_auth
|
||||
@@ -1300,7 +1331,7 @@ async def connect_mcp_servers(
|
||||
" Hint: this looks like stdio protocol pollution. Make sure the MCP server writes "
|
||||
"only JSON-RPC to stdout and sends logs/debug output to stderr instead."
|
||||
)
|
||||
_log_mcp_connection_failure(name, e, hint)
|
||||
_log_mcp_connection_failure(name, e, hint, proxy=selected_proxies.get(name))
|
||||
return False
|
||||
|
||||
async def connect_single_server(
|
||||
@@ -1350,7 +1381,7 @@ async def connect_mcp_servers(
|
||||
try:
|
||||
result = await connect_single_server(name, cfg)
|
||||
except Exception as e:
|
||||
_log_mcp_connection_failure(name, e)
|
||||
_log_mcp_connection_failure(name, e, proxy=selected_proxies.get(name))
|
||||
continue
|
||||
if result[1] is not None:
|
||||
server_stacks[result[0]] = result[1]
|
||||
@@ -1384,10 +1415,11 @@ def _configured_servers(config: Config) -> dict[str, MCPServerConfig]:
|
||||
)
|
||||
|
||||
|
||||
def _load_current_servers() -> dict[str, MCPServerConfig]:
|
||||
def _load_current_servers() -> tuple[dict[str, MCPServerConfig], NetworkConfig]:
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars
|
||||
|
||||
return _configured_servers(resolve_config_env_vars(load_config()))
|
||||
config = resolve_config_env_vars(load_config())
|
||||
return _configured_servers(config), config.network
|
||||
|
||||
|
||||
class MCPProvider:
|
||||
@@ -1399,8 +1431,10 @@ class MCPProvider:
|
||||
registry: ToolRegistry,
|
||||
*,
|
||||
server_loader: MCPServerLoader | None = None,
|
||||
network: NetworkConfig | None = None,
|
||||
) -> None:
|
||||
self._servers = dict(servers)
|
||||
self._network = (network or NetworkConfig()).model_copy(deep=True)
|
||||
self._registry = registry
|
||||
self._server_loader = server_loader or _load_current_servers
|
||||
self._connections: dict[str, MCPConnection] = {}
|
||||
@@ -1420,6 +1454,7 @@ class MCPProvider:
|
||||
_configured_servers(config),
|
||||
registry,
|
||||
server_loader=server_loader,
|
||||
network=config.network,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -1491,7 +1526,7 @@ class MCPProvider:
|
||||
return
|
||||
self._set_runtime_status(missing_servers, "connecting")
|
||||
try:
|
||||
connected = await connect_mcp_servers(missing_servers, self._registry)
|
||||
connected = await connect_mcp_servers(missing_servers, self._registry, network=self._network)
|
||||
if self._closing:
|
||||
await _close_mcp_connections(connected)
|
||||
return
|
||||
@@ -1526,7 +1561,8 @@ class MCPProvider:
|
||||
if self._closing:
|
||||
return self._closing_result()
|
||||
try:
|
||||
next_servers = dict(self._server_loader())
|
||||
loaded_servers, next_network = self._server_loader()
|
||||
next_servers = dict(loaded_servers)
|
||||
except Exception as exc:
|
||||
logger.warning("MCP hot reload could not read config: {}", exc)
|
||||
return {
|
||||
@@ -1553,6 +1589,7 @@ class MCPProvider:
|
||||
for name in current_names & next_names
|
||||
if _server_signature(current_servers[name])
|
||||
!= _server_signature(next_servers[name])
|
||||
or (next_servers[name].use_proxy and self._network.proxy != next_network.proxy)
|
||||
)
|
||||
|
||||
tools_removed = 0
|
||||
@@ -1564,6 +1601,7 @@ class MCPProvider:
|
||||
self._runtime_statuses.pop(name, None)
|
||||
|
||||
self._servers = next_servers
|
||||
self._network = next_network.model_copy(deep=True)
|
||||
retry_missing = sorted(
|
||||
name
|
||||
for name in next_names
|
||||
@@ -1580,7 +1618,7 @@ class MCPProvider:
|
||||
if to_connect:
|
||||
self._set_runtime_status(to_connect, "connecting")
|
||||
try:
|
||||
connected = await connect_mcp_servers(to_connect, self._registry)
|
||||
connected = await connect_mcp_servers(to_connect, self._registry, network=self._network)
|
||||
except BaseException:
|
||||
self._set_runtime_status(to_connect, "failed")
|
||||
raise
|
||||
@@ -1695,6 +1733,7 @@ class MCPProvider:
|
||||
connected = await connect_mcp_servers(
|
||||
{server_name: cfg},
|
||||
self._registry,
|
||||
network=self._network,
|
||||
)
|
||||
if self._closing:
|
||||
await _close_mcp_connections(connected)
|
||||
|
||||
@@ -282,8 +282,7 @@ def _snapshot_model_presets(
|
||||
def _snapshot_web_config(config: WebToolsConfig) -> dict[str, object]:
|
||||
return {
|
||||
"enable": config.enable,
|
||||
# Proxy URLs may embed credentials. Presence is enough for diagnosis.
|
||||
"proxy": "<configured>" if config.proxy else config.proxy,
|
||||
"use_proxy": config.use_proxy,
|
||||
"user_agent": config.user_agent,
|
||||
"search": {
|
||||
"provider": config.search.provider,
|
||||
|
||||
@@ -416,7 +416,7 @@ class WebSearchTool(Tool):
|
||||
config_loader = _load_search_config
|
||||
return cls(
|
||||
config=ctx.config.web.search,
|
||||
proxy=ctx.config.web.proxy,
|
||||
proxy=ctx.network.resolve_proxy(ctx.config.web.use_proxy),
|
||||
user_agent=ctx.config.web.user_agent,
|
||||
config_loader=config_loader,
|
||||
)
|
||||
@@ -1296,7 +1296,7 @@ class WebFetchTool(Tool):
|
||||
def create(cls, ctx: ToolContext) -> Tool:
|
||||
return cls(
|
||||
config=ctx.config.web.fetch,
|
||||
proxy=ctx.config.web.proxy,
|
||||
proxy=ctx.network.resolve_proxy(ctx.config.web.use_proxy),
|
||||
user_agent=ctx.config.web.user_agent,
|
||||
)
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ class WebFetchConfig(Base):
|
||||
class WebToolsConfig(Base):
|
||||
"""Web tools configuration."""
|
||||
enable: bool = True
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
user_agent: str | None = None
|
||||
search: WebSearchConfig = Field(default_factory=WebSearchConfig)
|
||||
fetch: WebFetchConfig = Field(default_factory=WebFetchConfig)
|
||||
@@ -10,6 +10,7 @@ from loguru import logger
|
||||
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.pairing import (
|
||||
PAIRING_CODE_META_KEY,
|
||||
format_pairing_reply,
|
||||
@@ -29,20 +30,26 @@ class BaseChannel(ABC):
|
||||
|
||||
name: str = "base"
|
||||
display_name: str = "Base"
|
||||
# Opt-in construction capability, not a channel configuration field.
|
||||
uses_shared_proxy: bool = False
|
||||
send_progress: bool = True
|
||||
send_tool_hints: bool = True
|
||||
show_reasoning: bool = True
|
||||
show_compaction_notices: bool = False
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize the channel.
|
||||
|
||||
Args:
|
||||
config: Channel-specific configuration.
|
||||
bus: The message bus for communication.
|
||||
network: Instance-scoped shared network settings.
|
||||
"""
|
||||
self.config = config
|
||||
self.network = network if network is not None else NetworkConfig()
|
||||
self.logger = logger.bind(channel=self.name)
|
||||
self.bus = bus
|
||||
self._running = False
|
||||
|
||||
@@ -6,9 +6,12 @@ import json
|
||||
from collections.abc import Iterable
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import field as dataclass_field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, Literal, TypeGuard, cast
|
||||
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
|
||||
@@ -21,6 +24,7 @@ class ChannelValidationContext:
|
||||
"""Host policy passed to package-owned setup validators."""
|
||||
|
||||
allow_local_service_access: bool = False
|
||||
network: NetworkConfig = dataclass_field(default_factory=NetworkConfig)
|
||||
|
||||
|
||||
# Keep callback contracts precise for static consumers. The public adapters below
|
||||
|
||||
@@ -8,9 +8,7 @@ from nanobot.channels.plugin import ChannelPlugin
|
||||
SETUP_SPEC = ChannelSetupSpec(
|
||||
fields={
|
||||
"token": field("secret"),
|
||||
"proxy": field(),
|
||||
"proxyUsername": field(),
|
||||
"proxyPassword": field("secret"),
|
||||
"useProxy": field("bool", default=False),
|
||||
"allowFrom": field("list", snapshot=False),
|
||||
"allowChannels": field("list"),
|
||||
"groupPolicy": field("enum", choices=DIRECT_GROUP_POLICIES, default="mention"),
|
||||
|
||||
@@ -19,6 +19,7 @@ from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.utils.helpers import safe_filename, split_message
|
||||
@@ -64,9 +65,7 @@ class DiscordConfig(Base):
|
||||
working_emoji_delay: float = 2.0
|
||||
streaming: bool = True
|
||||
reply_to_message: bool = False
|
||||
proxy: str | None = None
|
||||
proxy_username: str | None = None
|
||||
proxy_password: str | None = None
|
||||
use_proxy: bool = False
|
||||
|
||||
|
||||
if DISCORD_AVAILABLE:
|
||||
@@ -378,6 +377,7 @@ class DiscordChannel(BaseChannel):
|
||||
|
||||
name = "discord"
|
||||
display_name = "Discord"
|
||||
uses_shared_proxy = True
|
||||
_STREAM_EDIT_INTERVAL = 0.8
|
||||
|
||||
@classmethod
|
||||
@@ -443,11 +443,14 @@ class DiscordChannel(BaseChannel):
|
||||
partial = cast(Any, channel).get_partial_message(message_id)
|
||||
return partial.to_reference(fail_if_not_exists=fail_if_not_exists), mention_settings
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = DiscordConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: DiscordConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self._client: DiscordBotClient | None = None
|
||||
self._typing_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
self._bot_user_id: str | None = None
|
||||
@@ -478,30 +481,10 @@ class DiscordChannel(BaseChannel):
|
||||
intents = discord.Intents.none()
|
||||
intents.value = self.config.intents
|
||||
|
||||
proxy_auth = None
|
||||
has_user = bool(self.config.proxy_username)
|
||||
has_pass = bool(self.config.proxy_password)
|
||||
if has_user and has_pass:
|
||||
import aiohttp
|
||||
|
||||
proxy_auth = aiohttp.BasicAuth(
|
||||
login=cast(str, self.config.proxy_username),
|
||||
password=cast(str, self.config.proxy_password),
|
||||
)
|
||||
elif has_user != has_pass:
|
||||
self.logger.warning(
|
||||
"proxy auth incomplete: both proxy_username and "
|
||||
"proxy_password must be set; ignoring partial credentials",
|
||||
)
|
||||
|
||||
proxy = self.config.proxy
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
self._client = DiscordBotClient(
|
||||
self,
|
||||
intents=intents,
|
||||
proxy=proxy,
|
||||
proxy_auth=proxy_auth,
|
||||
proxy=self._proxy,
|
||||
)
|
||||
except Exception:
|
||||
self.logger.exception("Failed to initialize client")
|
||||
|
||||
@@ -22,6 +22,7 @@ from nanobot.channels.discord.runtime import (
|
||||
DiscordConfig,
|
||||
)
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
# Minimal Discord client test double used to control startup/readiness behavior.
|
||||
@@ -1566,25 +1567,20 @@ async def test_start_typing_uses_typing_context_when_trigger_typing_missing() ->
|
||||
assert channel._typing_tasks == {}
|
||||
|
||||
|
||||
def test_config_accepts_proxy_fields() -> None:
|
||||
config = DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_username="user",
|
||||
proxy_password="pass",
|
||||
)
|
||||
assert config.proxy == "http://127.0.0.1:7890"
|
||||
assert config.proxy_username == "user"
|
||||
assert config.proxy_password == "pass"
|
||||
def test_config_accepts_proxy_opt_in() -> None:
|
||||
config = DiscordConfig.model_validate({
|
||||
"enabled": True,
|
||||
"token": "token",
|
||||
"allowFrom": ["*"],
|
||||
"useProxy": True,
|
||||
})
|
||||
assert config.use_proxy is True
|
||||
assert config.model_dump(by_alias=True)["useProxy"] is True
|
||||
|
||||
|
||||
def test_config_proxy_defaults_to_none() -> None:
|
||||
def test_config_proxy_defaults_to_disabled() -> None:
|
||||
config = DiscordConfig(enabled=True, token="token", allow_from=["*"])
|
||||
assert config.proxy is None
|
||||
assert config.proxy_username is None
|
||||
assert config.proxy_password is None
|
||||
assert config.use_proxy is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1595,9 +1591,10 @@ async def test_start_passes_proxy_to_client(monkeypatch) -> None:
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
use_proxy=True,
|
||||
),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(proxy="http://127.0.0.1:7890"),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
@@ -1610,19 +1607,15 @@ async def test_start_passes_proxy_to_client(monkeypatch) -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_passes_proxy_auth_when_credentials_provided(monkeypatch) -> None:
|
||||
async def test_start_passes_shared_url_credentials_to_aiohttp(monkeypatch) -> None:
|
||||
aiohttp = pytest.importorskip("aiohttp")
|
||||
|
||||
_FakeDiscordClient.instances.clear()
|
||||
network = NetworkConfig(proxy="http://user:p%40ss@127.0.0.1:7890")
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_username="user",
|
||||
proxy_password="pass",
|
||||
),
|
||||
DiscordConfig(enabled=True, token="token", allow_from=["*"], use_proxy=True),
|
||||
MessageBus(),
|
||||
network=network,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
@@ -1630,54 +1623,51 @@ async def test_start_passes_proxy_auth_when_credentials_provided(monkeypatch) ->
|
||||
|
||||
assert channel.is_running is False
|
||||
assert len(_FakeDiscordClient.instances) == 1
|
||||
assert _FakeDiscordClient.instances[0].proxy == "http://127.0.0.1:7890"
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth is not None
|
||||
assert isinstance(_FakeDiscordClient.instances[0].proxy_auth, aiohttp.BasicAuth)
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth.login == "user"
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth.password == "pass"
|
||||
client = _FakeDiscordClient.instances[0]
|
||||
assert client.proxy == network.proxy
|
||||
# aiohttp extracts URL credentials for the proxy connection, not the destination request.
|
||||
proxy_connection = AsyncMock(side_effect=RuntimeError("stop before opening proxy socket"))
|
||||
monkeypatch.setattr(aiohttp.TCPConnector, "_create_direct_connection", proxy_connection)
|
||||
async with aiohttp.ClientSession() as session:
|
||||
with pytest.raises(RuntimeError, match="stop before opening proxy socket"):
|
||||
await session.get(
|
||||
"https://discord.com/api/v10/users/@me",
|
||||
proxy=client.proxy, proxy_auth=client.proxy_auth,
|
||||
)
|
||||
|
||||
proxy_connection.assert_awaited_once()
|
||||
request = proxy_connection.await_args.args[0]
|
||||
assert request.url.host == "127.0.0.1"
|
||||
assert request.url.port == 7890
|
||||
auth = aiohttp.BasicAuth.decode(request.headers["Proxy-Authorization"])
|
||||
assert auth.login == "user"
|
||||
assert auth.password == "p@ss"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_no_proxy_auth_when_only_username(monkeypatch) -> None:
|
||||
async def test_start_without_opt_in_ignores_shared_proxy_credentials(monkeypatch) -> None:
|
||||
_FakeDiscordClient.instances.clear()
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_username="user",
|
||||
),
|
||||
DiscordConfig(enabled=True, token="token", allow_from=["*"], use_proxy=False),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(proxy="http://user:pass@127.0.0.1:7890"),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
await channel.start()
|
||||
|
||||
assert channel.is_running is False
|
||||
assert _FakeDiscordClient.instances[0].proxy is None
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_no_proxy_auth_when_only_password(monkeypatch) -> None:
|
||||
_FakeDiscordClient.instances.clear()
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_password="pass",
|
||||
),
|
||||
MessageBus(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
await channel.start()
|
||||
|
||||
assert channel.is_running is False
|
||||
assert _FakeDiscordClient.instances[0].proxy == "http://127.0.0.1:7890"
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth is None
|
||||
def test_proxy_opt_in_without_shared_address_fails_before_start() -> None:
|
||||
with pytest.raises(ValueError, match="Advanced"):
|
||||
DiscordChannel(
|
||||
DiscordConfig(enabled=True, token="token", use_proxy=True),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -10,15 +10,20 @@ from nanobot.channels.validation import (
|
||||
http_get,
|
||||
payload,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("discord", values)
|
||||
try:
|
||||
proxy = resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("discord", checks, missing)
|
||||
token = string_value(values.get("token"))
|
||||
proxy = string_value(values.get("proxy"))
|
||||
if token:
|
||||
try:
|
||||
data = http_get(
|
||||
@@ -61,9 +66,9 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict
|
||||
f"Discord rejected the token: HTTP {exc.response.status_code}",
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception:
|
||||
checks.append(
|
||||
check("bot_token", "Bot token", "warn", f"Could not reach Discord now: {exc}")
|
||||
check("bot_token", "Bot token", "warn", "Could not reach Discord now. Try again later.")
|
||||
)
|
||||
return status_from_checks("discord", checks, missing)
|
||||
|
||||
|
||||
@@ -12,9 +12,7 @@ export default {
|
||||
docsUrl: chatAppGuideUrl("discord"),
|
||||
fields: [
|
||||
{ key: "channels.discord.token", section: "credentials" },
|
||||
{ key: "channels.discord.proxy", section: "connection" },
|
||||
{ key: "channels.discord.proxyUsername", section: "connection" },
|
||||
{ key: "channels.discord.proxyPassword", section: "connection" },
|
||||
{ key: "channels.discord.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.discord.allowFrom", section: "access" },
|
||||
{ key: "channels.discord.allowChannels", section: "access" },
|
||||
{ key: "channels.discord.groupPolicy", section: "behavior" },
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Allowed users",
|
||||
"placeholder": "User IDs, comma separated"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Proxy username"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Proxy password"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Gateway intents"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Usuarios permitidos",
|
||||
"placeholder": "ID de usuario separados por comas"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "proxy de red"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Usuario del proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Contraseña de proxy"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Intentos de puerta de enlace"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Utilisateurs autorisés",
|
||||
"placeholder": "ID utilisateur séparés par des virgules"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Mandataire réseau"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Utilisateur du proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Mot de passe proxy"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Intentions de passerelle"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Pengguna diizinkan",
|
||||
"placeholder": "ID pengguna, dipisahkan koma"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proksi jaringan"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Nama pengguna proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Kata sandi proksi"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Maksud gerbang"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "許可ユーザー",
|
||||
"placeholder": "ユーザー ID(カンマ区切り)"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "プロキシのユーザー名"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "プロキシパスワード"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
},
|
||||
"intents": {
|
||||
"label": "ゲートウェイの意図"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "허용 사용자",
|
||||
"placeholder": "사용자 ID, 쉼표로 구분"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "프록시 사용자 이름"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "프록시 비밀번호"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
},
|
||||
"intents": {
|
||||
"label": "게이트웨이 인텐트"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Usuários permitidos",
|
||||
"placeholder": "IDs de usuário separados por vírgulas"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Usuário do proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Senha proxy"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Intenções de gateway"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Người dùng được phép",
|
||||
"placeholder": "ID người dùng, phân tách bằng dấu phẩy"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Tên người dùng proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Mật khẩu proxy"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Ý định của cổng"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "允许用户",
|
||||
"placeholder": "用户 ID,用逗号分隔"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "代理账号"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "代理密码"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Gateway Intents"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "允許使用者",
|
||||
"placeholder": "使用者 ID,以逗號分隔"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "代理賬號"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "代理密碼"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Gateway Intents"
|
||||
|
||||
@@ -202,6 +202,8 @@ class ChannelManager:
|
||||
runtime_name: str | None = None,
|
||||
) -> BaseChannel:
|
||||
kwargs: dict[str, Any] = {}
|
||||
if cls.uses_shared_proxy:
|
||||
kwargs["network"] = self.config.network
|
||||
if cls.name == "websocket":
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
@@ -22,7 +22,7 @@ SETUP_SPEC = ChannelSetupSpec(
|
||||
"groupAllowFrom": field("list"),
|
||||
"allowRoomMentions": field("bool", default=False),
|
||||
"streaming": field("bool", default=False),
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
},
|
||||
required=(
|
||||
*required_fields("homeserver", "userId"),
|
||||
|
||||
@@ -63,6 +63,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_data_dir, get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -303,7 +304,7 @@ class MatrixConfig(Base):
|
||||
group_allow_from: list[str] = Field(default_factory=list)
|
||||
allow_room_mentions: bool = False
|
||||
streaming: bool = False
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
|
||||
|
||||
class MatrixChannel(BaseChannel):
|
||||
@@ -311,6 +312,7 @@ class MatrixChannel(BaseChannel):
|
||||
|
||||
name = "matrix"
|
||||
display_name = "Matrix"
|
||||
uses_shared_proxy = True
|
||||
_STREAM_EDIT_INTERVAL = 2 # min seconds between edit_message_text calls
|
||||
monotonic_time: Callable[[], float] = staticmethod(time.monotonic)
|
||||
|
||||
@@ -323,12 +325,15 @@ class MatrixChannel(BaseChannel):
|
||||
config: Any,
|
||||
bus: MessageBus,
|
||||
*,
|
||||
network: NetworkConfig | None = None,
|
||||
restrict_to_workspace: bool = False,
|
||||
workspace: str | Path | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = MatrixConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: MatrixConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self.client: AsyncClient | None = None
|
||||
self._sync_task: asyncio.Task[None] | None = None
|
||||
self._typing_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
@@ -359,14 +364,11 @@ class MatrixChannel(BaseChannel):
|
||||
# Replace ':' with '_' to produce a Windows-safe filename
|
||||
safe_store_name = self.config.user_id.replace(":", "_") + f"_{self.config.device_id}.db"
|
||||
|
||||
proxy = self.config.proxy.strip() if self.config.proxy else ""
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
self.client = AsyncClient(
|
||||
homeserver=self.config.homeserver,
|
||||
user=self.config.user_id,
|
||||
store_path=str(self.store_path),
|
||||
proxy=proxy or None,
|
||||
proxy=self._proxy,
|
||||
config=AsyncClientConfig(
|
||||
store_sync_tokens=True,
|
||||
encryption_enabled=self.config.e2ee_enabled,
|
||||
|
||||
@@ -25,6 +25,7 @@ from nanobot.channels.matrix.runtime import (
|
||||
MatrixConfig,
|
||||
_build_matrix_text_content,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
_ROOM_SEND_UNSET = object()
|
||||
|
||||
@@ -328,8 +329,9 @@ async def test_start_skips_load_store_when_device_id_missing(
|
||||
)
|
||||
|
||||
channel = MatrixChannel(
|
||||
_make_config(device_id="", e2ee_enabled=True, proxy="127.0.0.1:7890"),
|
||||
_make_config(device_id="", e2ee_enabled=True, use_proxy=True),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(proxy="127.0.0.1:7890"),
|
||||
)
|
||||
await channel.start()
|
||||
|
||||
|
||||
@@ -3,11 +3,22 @@
|
||||
from typing import Any
|
||||
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
from nanobot.channels.validation import check, required_checks, status_from_checks, string_value
|
||||
from nanobot.channels.validation import (
|
||||
check,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("matrix", values)
|
||||
try:
|
||||
resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("matrix", checks, missing)
|
||||
password = string_value(values.get("password"))
|
||||
access_token = string_value(values.get("accessToken"))
|
||||
device_id = string_value(values.get("deviceId"))
|
||||
|
||||
@@ -12,6 +12,7 @@ export default {
|
||||
docsUrl: chatAppGuideUrl("matrix"),
|
||||
fields: [
|
||||
{ key: "channels.matrix.homeserver", section: "connection" },
|
||||
{ key: "channels.matrix.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.matrix.userId", section: "account" },
|
||||
{ key: "channels.matrix.password", section: "credentials" },
|
||||
{ key: "channels.matrix.accessToken", section: "credentials" },
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Off"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Apagado"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Désactivé"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Mati"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "オフ"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "끄기"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Desligado"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Tắt"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "关闭"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "關閉"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ SETUP_SPEC = ChannelSetupSpec(
|
||||
"dm.enabled": field("bool", default=True),
|
||||
"dm.policy": field("enum", choices={"open", "allowlist"}, default="open"),
|
||||
"dm.allowFrom": field("list"),
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
},
|
||||
required=required_fields("appToken", "botToken"),
|
||||
official_url="https://api.slack.com/apps",
|
||||
|
||||
@@ -19,6 +19,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -84,7 +85,7 @@ class SlackConfig(Base):
|
||||
# instead of every message). No effect for "mention"/"open" policies.
|
||||
group_require_mention: bool = False
|
||||
dm: SlackDMConfig = Field(default_factory=SlackDMConfig)
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
|
||||
|
||||
SLACK_MAX_MESSAGE_LEN = 39_000 # Slack API allows ~40k; leave margin
|
||||
@@ -109,6 +110,7 @@ class SlackChannel(BaseChannel):
|
||||
|
||||
name = "slack"
|
||||
display_name = "Slack"
|
||||
uses_shared_proxy = True
|
||||
_SLACK_ID_RE = re.compile(r"^[CDGUW][A-Z0-9]{2,}$")
|
||||
_SLACK_CHANNEL_REF_RE = re.compile(r"^<#([A-Z0-9]+)(?:\|[^>]+)?>$")
|
||||
_SLACK_USER_REF_RE = re.compile(r"^<@([A-Z0-9]+)(?:\|[^>]+)?>$")
|
||||
@@ -119,11 +121,14 @@ class SlackChannel(BaseChannel):
|
||||
|
||||
_THREAD_CONTEXT_CACHE_LIMIT = 10_000
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = SlackConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: SlackConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self._web_client: AsyncWebClient | None = None
|
||||
self._socket_client: SocketModeClient | None = None
|
||||
self._bot_user_id: str | None = None
|
||||
@@ -148,10 +153,7 @@ class SlackChannel(BaseChannel):
|
||||
|
||||
self._running = True
|
||||
|
||||
proxy = self.config.proxy.strip() if self.config.proxy else ""
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
proxy = proxy or None
|
||||
proxy = self._proxy
|
||||
self._web_client = AsyncWebClient(token=self.config.bot_token, proxy=proxy)
|
||||
self._socket_client = SocketModeClient(
|
||||
app_token=self.config.app_token,
|
||||
@@ -592,14 +594,10 @@ class SlackChannel(BaseChannel):
|
||||
mounts=(
|
||||
{
|
||||
"all://": httpx.AsyncHTTPTransport(
|
||||
proxy=httpx.Proxy(
|
||||
self.config.proxy
|
||||
if "://" in self.config.proxy
|
||||
else f"http://{self.config.proxy}"
|
||||
)
|
||||
proxy=httpx.Proxy(self._proxy)
|
||||
)
|
||||
}
|
||||
if self.config.proxy
|
||||
if self._proxy
|
||||
else httpx_env_proxy_mounts()
|
||||
),
|
||||
event_hooks={"request": [_validate_slack_download_request]},
|
||||
|
||||
@@ -17,6 +17,7 @@ except ImportError:
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.slack.runtime import SLACK_MAX_MESSAGE_LEN, SlackChannel, SlackConfig
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
class _FakeAsyncWebClient:
|
||||
@@ -984,3 +985,74 @@ async def test_download_follows_safe_redirect(
|
||||
assert validated == [url, "https://cdn.example/file.bin"]
|
||||
assert requests[0].headers["Authorization"] == "Bearer xoxb-test"
|
||||
assert "Authorization" not in requests[1].headers
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_proxy", [True, False])
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_uses_shared_proxy_for_web_api_and_socket_mode(monkeypatch, use_proxy) -> None:
|
||||
network = NetworkConfig(proxy="http://127.0.0.1:7890")
|
||||
channel = SlackChannel(
|
||||
SlackConfig(bot_token="xoxb-test", app_token="xapp-test", use_proxy=use_proxy),
|
||||
MessageBus(),
|
||||
network=network,
|
||||
)
|
||||
captured = {}
|
||||
|
||||
def web_client(**kwargs):
|
||||
captured["web"] = kwargs
|
||||
return SimpleNamespace(auth_test=AsyncMock(return_value={"user_id": "U42"}))
|
||||
|
||||
async def connect():
|
||||
channel._running = False
|
||||
|
||||
def socket_client(**kwargs):
|
||||
captured["socket"] = kwargs
|
||||
return SimpleNamespace(socket_mode_request_listeners=[], connect=connect)
|
||||
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.AsyncWebClient", web_client)
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.SocketModeClient", socket_client)
|
||||
|
||||
await channel.start()
|
||||
|
||||
expected = network.proxy if use_proxy else None
|
||||
assert captured["web"] == {"token": "xoxb-test", "proxy": expected}
|
||||
assert captured["socket"]["proxy"] == expected
|
||||
assert captured["socket"]["web_client"] is channel._web_client
|
||||
assert channel._bot_user_id == "U42"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_uses_shared_proxy_and_keeps_redirect_validation(monkeypatch, tmp_path) -> None:
|
||||
proxies = []
|
||||
requests = []
|
||||
validated = []
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
return httpx.Response(302, headers={"location": "http://169.254.169.254/secret"})
|
||||
|
||||
def proxy_transport(*, proxy):
|
||||
proxies.append(proxy)
|
||||
return httpx.MockTransport(handler)
|
||||
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.httpx.AsyncHTTPTransport", proxy_transport)
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.PinnedDNSAsyncTransport", lambda: httpx.MockTransport(handler))
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.get_media_dir", lambda _name: tmp_path)
|
||||
_patch_download_validation(monkeypatch, validated)
|
||||
channel = SlackChannel(
|
||||
SlackConfig(bot_token="xoxb-test", use_proxy=True), MessageBus(), network=network,
|
||||
)
|
||||
url = "https://files.slack.com/file.bin"
|
||||
|
||||
path, _marker = await channel._download_slack_file({
|
||||
"id": "F1", "name": "file.bin", "url_private_download": url,
|
||||
})
|
||||
|
||||
assert path is None
|
||||
assert len(proxies) == 1
|
||||
assert proxies[0].url == httpx.URL("http://127.0.0.1:7890")
|
||||
assert proxies[0].raw_auth == (b"user", b"pass")
|
||||
assert len(requests) == 1
|
||||
assert validated == [url, "http://169.254.169.254/secret"]
|
||||
assert requests[0].headers["Authorization"] == "Bearer xoxb-test"
|
||||
@@ -10,16 +10,21 @@ from nanobot.channels.validation import (
|
||||
official_action,
|
||||
payload,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("slack", values)
|
||||
try:
|
||||
proxy = resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("slack", checks, missing)
|
||||
app_token = string_value(values.get("appToken"))
|
||||
bot_token = string_value(values.get("botToken"))
|
||||
proxy = string_value(values.get("proxy"))
|
||||
if app_token:
|
||||
checks.append(
|
||||
check(
|
||||
@@ -76,13 +81,13 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict
|
||||
message_from_response(data, "Slack rejected the bot token."),
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception:
|
||||
checks.append(
|
||||
check(
|
||||
"auth_test",
|
||||
"Workspace identity",
|
||||
"warn",
|
||||
f"Could not reach Slack now: {exc}",
|
||||
"Could not reach Slack now. Try again later.",
|
||||
)
|
||||
)
|
||||
return status_from_checks("slack", checks, missing)
|
||||
|
||||
@@ -56,6 +56,7 @@ export default {
|
||||
fields: [
|
||||
{ key: "channels.slack.appToken", section: "credentials" },
|
||||
{ key: "channels.slack.botToken", section: "credentials" },
|
||||
{ key: "channels.slack.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.slack.groupPolicy", section: "behavior" },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Allowed DM users"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Usuarios de DM permitidos"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Utilisateurs de DM autorisés"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Pengguna DM diizinkan"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "許可する DM ユーザー"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "허용 DM 사용자"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Usuários de DM permitidos"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Người dùng DM được phép"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "私聊用户"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "私聊使用者"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ from nanobot.channels.telegram.validation import validate
|
||||
SETUP_SPEC = ChannelSetupSpec(
|
||||
fields={
|
||||
"token": field("secret"),
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
"allowFrom": field("list"),
|
||||
"groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"),
|
||||
"mode": field("enum", choices={"polling", "webhook"}, default="polling"),
|
||||
|
||||
@@ -35,6 +35,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -495,7 +496,7 @@ class TelegramConfig(Base):
|
||||
token: str = ""
|
||||
mode: Literal["polling", "webhook"] = "polling"
|
||||
allow_from: list[str] = Field(default_factory=list)
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
reply_to_message: bool = False
|
||||
react_emoji: str = "👀"
|
||||
group_policy: Literal["open", "mention"] = "mention"
|
||||
@@ -588,6 +589,7 @@ class TelegramChannel(BaseChannel):
|
||||
|
||||
name = "telegram"
|
||||
display_name = "Telegram"
|
||||
uses_shared_proxy = True
|
||||
|
||||
# Commands registered with Telegram's command menu
|
||||
BOT_COMMANDS: list[BotCommand] = [
|
||||
@@ -623,11 +625,14 @@ class TelegramChannel(BaseChannel):
|
||||
def default_config(cls) -> dict[str, Any]:
|
||||
return TelegramConfig().model_dump(by_alias=True)
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = TelegramConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: TelegramConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self._app: TelegramApplication | None = None
|
||||
self._typing_tasks: dict[str, asyncio.Task[None]] = {} # chat_id -> typing loop task
|
||||
self._media_group_buffers: dict[str, dict[str, Any]] = {}
|
||||
@@ -735,9 +740,7 @@ class TelegramChannel(BaseChannel):
|
||||
|
||||
async def _start_app(self) -> None:
|
||||
"""Build, initialize and start the Telegram application."""
|
||||
proxy = self.config.proxy or None
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
proxy = self._proxy
|
||||
|
||||
# Separate pools so long-polling (getUpdates) never starves outbound sends.
|
||||
api_request = HTTPXRequest(
|
||||
|
||||
@@ -28,6 +28,7 @@ from nanobot.channels.telegram.runtime import (
|
||||
_StreamBuf,
|
||||
_telegram_command_text,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
|
||||
|
||||
@@ -349,10 +350,11 @@ async def test_start_creates_separate_pools_with_proxy(monkeypatch) -> None:
|
||||
enabled=True,
|
||||
token="123:abc",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
use_proxy=True,
|
||||
)
|
||||
bus = MessageBus()
|
||||
channel = TelegramChannel(config, bus)
|
||||
network = NetworkConfig(proxy="http://127.0.0.1:7890")
|
||||
channel = TelegramChannel(config, bus, network=network)
|
||||
app = _FakeApp(lambda: setattr(channel, "_running", False))
|
||||
builder = _FakeBuilder(app)
|
||||
|
||||
@@ -366,8 +368,8 @@ async def test_start_creates_separate_pools_with_proxy(monkeypatch) -> None:
|
||||
|
||||
assert len(_FakeHTTPXRequest.instances) == 2
|
||||
api_req, poll_req = _FakeHTTPXRequest.instances
|
||||
assert api_req.kwargs["proxy"] == config.proxy
|
||||
assert poll_req.kwargs["proxy"] == config.proxy
|
||||
assert api_req.kwargs["proxy"] == network.proxy
|
||||
assert poll_req.kwargs["proxy"] == network.proxy
|
||||
assert api_req.kwargs["connection_pool_size"] == 32
|
||||
assert poll_req.kwargs["connection_pool_size"] == 4
|
||||
assert builder.request_value is api_req
|
||||
|
||||
@@ -10,11 +10,12 @@ from nanobot.config.loader import save_config
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
def test_telegram_setup_exposes_proxy_as_an_optional_field() -> None:
|
||||
proxy = SETUP_SPEC.fields["proxy"]
|
||||
def test_telegram_setup_exposes_proxy_opt_in_as_an_optional_field() -> None:
|
||||
use_proxy = SETUP_SPEC.fields["useProxy"]
|
||||
|
||||
assert proxy.kind == "string"
|
||||
assert "proxy" not in SETUP_SPEC.simple_required_fields
|
||||
assert use_proxy.kind == "bool"
|
||||
assert use_proxy.default is False
|
||||
assert "useProxy" not in SETUP_SPEC.simple_required_fields
|
||||
|
||||
|
||||
def test_get_me_builds_http_client_with_explicit_proxy(
|
||||
@@ -169,7 +170,7 @@ def test_validate_telegram_marks_proxy_transport_failures_without_exposing_proxy
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token, "proxy": proxy}}}
|
||||
{"network": {"proxy": proxy}, "channels": {"telegram": {"token": token, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -197,7 +198,7 @@ def test_validate_telegram_uses_saved_proxy_without_exposing_it(
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token, "proxy": proxy}}}
|
||||
{"network": {"proxy": proxy}, "channels": {"telegram": {"token": token, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -230,7 +231,7 @@ def test_validate_telegram_resolves_saved_secret_env_refs_without_exposing_them(
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token_ref, "proxy": proxy_ref}}}
|
||||
{"network": {"proxy": proxy_ref}, "channels": {"telegram": {"token": token_ref, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -263,7 +264,7 @@ def test_validate_telegram_rejects_unset_proxy_env_ref_without_connecting(
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token, "proxy": proxy_ref}}}
|
||||
{"network": {"proxy": proxy_ref}, "channels": {"telegram": {"token": token, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -279,17 +280,17 @@ def test_validate_telegram_rejects_unset_proxy_env_ref_without_connecting(
|
||||
assert result["status"] == "invalid"
|
||||
assert result["can_enable"] is False
|
||||
assert proxy_ref not in str(result)
|
||||
assert any(check["id"] == "proxy_env" for check in result["checks"])
|
||||
assert any(check["id"] == "network_proxy" for check in result["checks"])
|
||||
|
||||
|
||||
def test_validate_telegram_uses_proxy_submitted_with_new_token(
|
||||
def test_validate_telegram_uses_shared_proxy_when_opt_in_is_submitted_with_new_token(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
token = "123456:abcdefghijklmnopqrstuvwxyz"
|
||||
proxy = "http://127.0.0.1:7890"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
save_config(Config.model_validate({"network": {"proxy": proxy}}), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
captured: dict[str, str | None] = {}
|
||||
|
||||
@@ -303,7 +304,7 @@ def test_validate_telegram_uses_proxy_submitted_with_new_token(
|
||||
"telegram",
|
||||
{
|
||||
"channels.telegram.token": token,
|
||||
"channels.telegram.proxy": proxy,
|
||||
"channels.telegram.useProxy": True,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -319,7 +320,10 @@ def test_validate_telegram_rejects_invalid_proxy_without_trying_token(
|
||||
) -> None:
|
||||
token = "123456:abcdefghijklmnopqrstuvwxyz"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
monkeypatch.setenv("NETWORK_PROXY_TEST", proxy)
|
||||
save_config(
|
||||
Config.model_validate({"network": {"proxy": "${NETWORK_PROXY_TEST}"}}), config_path,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
def fail_get_me(*_args) -> dict:
|
||||
@@ -331,11 +335,11 @@ def test_validate_telegram_rejects_invalid_proxy_without_trying_token(
|
||||
"telegram",
|
||||
{
|
||||
"channels.telegram.token": token,
|
||||
"channels.telegram.proxy": proxy,
|
||||
"channels.telegram.useProxy": True,
|
||||
},
|
||||
)
|
||||
|
||||
assert result["status"] == "invalid"
|
||||
assert result["can_enable"] is False
|
||||
assert proxy not in str(result)
|
||||
assert any(check["id"] == "proxy_format" for check in result["checks"])
|
||||
assert any(check["id"] == "network_proxy" for check in result["checks"])
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import re
|
||||
from typing import Any, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -12,25 +11,13 @@ from nanobot.channels.validation import (
|
||||
message_from_response,
|
||||
payload,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
from nanobot.config.loader import resolve_env_refs
|
||||
|
||||
_TIMEOUT_SECONDS = 4.0
|
||||
_SUPPORTED_PROXY_SCHEMES = {"http", "https", "socks5", "socks5h"}
|
||||
|
||||
|
||||
def _proxy_url_is_valid(proxy: str) -> bool:
|
||||
if "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
try:
|
||||
parsed = urlparse(proxy)
|
||||
hostname = parsed.hostname
|
||||
parsed.port
|
||||
except ValueError:
|
||||
return False
|
||||
return parsed.scheme.lower() in _SUPPORTED_PROXY_SCHEMES and bool(hostname)
|
||||
|
||||
|
||||
def _get_me(token: str, proxy: str | None) -> dict[str, Any]:
|
||||
@@ -46,12 +33,15 @@ def _get_me(token: str, proxy: str | None) -> dict[str, Any]:
|
||||
return cast(dict[str, Any], data) if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("telegram", values)
|
||||
try:
|
||||
proxy = resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("telegram", checks, missing)
|
||||
raw_token = string_value(values.get("token"))
|
||||
raw_proxy = string_value(values.get("proxy"))
|
||||
token = string_value(resolve_env_refs(raw_token))
|
||||
proxy = string_value(resolve_env_refs(raw_proxy))
|
||||
if raw_token and not token:
|
||||
checks.append(
|
||||
check(
|
||||
@@ -61,26 +51,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict
|
||||
"Set every environment variable referenced by the bot token.",
|
||||
)
|
||||
)
|
||||
if raw_proxy and not proxy:
|
||||
checks.append(
|
||||
check(
|
||||
"proxy_env",
|
||||
"Proxy environment variable",
|
||||
"fail",
|
||||
"Set every environment variable referenced by the network proxy.",
|
||||
)
|
||||
)
|
||||
if (raw_token and not token) or (raw_proxy and not proxy):
|
||||
return status_from_checks("telegram", checks, missing)
|
||||
if proxy and not _proxy_url_is_valid(proxy):
|
||||
checks.append(
|
||||
check(
|
||||
"proxy_format",
|
||||
"Network proxy",
|
||||
"fail",
|
||||
"Enter a valid HTTP or SOCKS proxy.",
|
||||
)
|
||||
)
|
||||
if raw_token and not token:
|
||||
return status_from_checks("telegram", checks, missing)
|
||||
if token:
|
||||
if not re.match(r"^\d+:[A-Za-z0-9_-]{20,}$", token):
|
||||
|
||||
@@ -12,7 +12,7 @@ export default {
|
||||
docsUrl: chatAppGuideUrl("telegram"),
|
||||
fields: [
|
||||
{ key: "channels.telegram.token", section: "credentials" },
|
||||
{ key: "channels.telegram.proxy", section: "connection" },
|
||||
{ key: "channels.telegram.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.telegram.allowFrom", section: "access" },
|
||||
{ key: "channels.telegram.groupPolicy", section: "behavior" },
|
||||
],
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Bot token",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Allowed users",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token del bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Usuarios permitidos",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Jeton du bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Utilisateurs autorisés",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Pengguna diizinkan",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "ボットトークン",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "許可ユーザー",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "봇 토큰",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "허용 사용자",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token do bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Usuários permitidos",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Người dùng được phép",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "机器人令牌",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "允许用户",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "機器人權杖",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "允許使用者",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Cross-channel Python tests."""
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Shared proxy ownership at channel construction and setup boundaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.registry import load_channel_plugin
|
||||
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
_CHANNEL_VALUES = {
|
||||
"telegram": {"token": "123456:abcdefghijklmnopqrstuvwxyz"},
|
||||
"discord": {"token": "discord-token"},
|
||||
"slack": {"appToken": "xapp-test", "botToken": "xoxb-test"},
|
||||
"matrix": {
|
||||
"homeserver": "https://matrix.example",
|
||||
"userId": "@bot:matrix.example",
|
||||
"password": "matrix-password",
|
||||
},
|
||||
"whatsapp": {"enabled": True},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", _CHANNEL_VALUES)
|
||||
def test_setup_refuses_proxy_opt_in_without_shared_address(name, monkeypatch) -> None:
|
||||
def fail_client(*_args, **_kwargs):
|
||||
pytest.fail("missing shared proxy must not fall back to a direct connection")
|
||||
|
||||
monkeypatch.setattr("httpx.Client", fail_client)
|
||||
validator = load_channel_plugin(name).setup.validator
|
||||
|
||||
result = validator(
|
||||
{**_CHANNEL_VALUES[name], "useProxy": True}, ChannelValidationContext(),
|
||||
)
|
||||
|
||||
assert result["status"] == "invalid"
|
||||
assert result["can_enable"] is False
|
||||
proxy_check = next(check for check in result["checks"] if check["id"] == "network_proxy")
|
||||
assert proxy_check["status"] == "fail"
|
||||
assert "Advanced" in proxy_check["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "request_method", "response"),
|
||||
[
|
||||
("telegram", "_get_me", {"ok": True, "result": {"id": 42}}),
|
||||
("discord", "http_get", {"id": "42", "username": "bot"}),
|
||||
("slack", "http_post", {"ok": True, "user_id": "U42"}),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("use_proxy", [True, False, "false"])
|
||||
def test_identity_validation_respects_shared_proxy_opt_in(
|
||||
name, request_method, response, use_proxy, monkeypatch,
|
||||
) -> None:
|
||||
module = importlib.import_module(f"nanobot.channels.{name}.validation")
|
||||
proxies = []
|
||||
|
||||
def request(_target, proxy=None, **_kwargs):
|
||||
proxies.append(proxy)
|
||||
return response
|
||||
|
||||
monkeypatch.setattr(module, request_method, request)
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
|
||||
result = module.validate(
|
||||
{**_CHANNEL_VALUES[name], "useProxy": use_proxy},
|
||||
ChannelValidationContext(network=network),
|
||||
)
|
||||
|
||||
assert result["status"] == "connected"
|
||||
assert proxies == [network.proxy if use_proxy is True else None]
|
||||
assert network.proxy not in str(result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", _CHANNEL_VALUES)
|
||||
def test_runtime_refuses_proxy_opt_in_without_shared_address(name) -> None:
|
||||
pytest.importorskip(f"nanobot.channels.{name}.runtime", exc_type=ImportError)
|
||||
channel_cls = load_channel_plugin(name).load_channel_class()
|
||||
|
||||
with pytest.raises(ValueError, match="Advanced"):
|
||||
channel_cls({"useProxy": True}, MessageBus(), network=NetworkConfig())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", _CHANNEL_VALUES)
|
||||
@pytest.mark.parametrize("use_proxy", [True, False])
|
||||
def test_manager_constructs_proxy_capable_builtin_from_descriptor(
|
||||
name, use_proxy, monkeypatch, tmp_path,
|
||||
) -> None:
|
||||
pytest.importorskip(f"nanobot.channels.{name}.runtime", exc_type=ImportError)
|
||||
plugin = load_channel_plugin(name)
|
||||
monkeypatch.setattr("nanobot.channels.registry.discover_plugins", lambda: {name: plugin})
|
||||
monkeypatch.setattr("nanobot.optional_features.extra_installed", lambda *_args: True)
|
||||
config = Config.model_validate({
|
||||
"network": {"proxy": "http://127.0.0.1:7890"},
|
||||
"channels": {
|
||||
name: {**_CHANNEL_VALUES[name], "enabled": True, "useProxy": use_proxy},
|
||||
},
|
||||
})
|
||||
|
||||
manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
|
||||
|
||||
channel = manager.channels[name]
|
||||
assert isinstance(channel, plugin.load_channel_class())
|
||||
assert channel.uses_shared_proxy is True
|
||||
assert channel.network is config.network
|
||||
assert channel._proxy == (config.network.proxy if use_proxy else None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manager_keeps_shared_proxy_instance_scoped(monkeypatch) -> None:
|
||||
class ProxySettings:
|
||||
def __init__(self, *, proxy_address: str) -> None:
|
||||
self.proxy_address = proxy_address
|
||||
|
||||
monkeypatch.setitem(sys.modules, "neonize._binder", SimpleNamespace(ProxySettings=ProxySettings))
|
||||
channels = []
|
||||
for address in ("http://127.0.0.1:7890", "http://127.0.0.1:7891"):
|
||||
manager = object.__new__(ChannelManager)
|
||||
manager.config = Config(network=NetworkConfig(proxy=address))
|
||||
manager.bus = MessageBus()
|
||||
channel = manager._build_channel("whatsapp", WhatsAppChannel, {"useProxy": True})
|
||||
assert channel.network is manager.config.network
|
||||
channels.append(channel)
|
||||
|
||||
for channel, address in zip(channels, ("http://127.0.0.1:7890", "http://127.0.0.1:7891")):
|
||||
client = SimpleNamespace(connect=AsyncMock())
|
||||
await channel._connect_client(client)
|
||||
assert client.connect.await_args.args[0].proxy_address == address
|
||||
assert channel.config.model_dump(by_alias=True)["useProxy"] is True
|
||||
assert "proxy" not in channel.config.model_dump(by_alias=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "request_method"), [("discord", "http_get"), ("slack", "http_post")])
|
||||
def test_identity_validation_does_not_expose_shared_proxy_in_errors(name, request_method, monkeypatch) -> None:
|
||||
module = importlib.import_module(f"nanobot.channels.{name}.validation")
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
|
||||
def fail_request(*_args, **_kwargs):
|
||||
raise OSError(f"could not connect through {network.proxy}")
|
||||
|
||||
monkeypatch.setattr(module, request_method, fail_request)
|
||||
result = module.validate(
|
||||
{**_CHANNEL_VALUES[name], "useProxy": True}, ChannelValidationContext(network=network),
|
||||
)
|
||||
|
||||
assert result["status"] == "configured"
|
||||
assert result["can_enable"] is True
|
||||
assert any(check["status"] == "warn" for check in result["checks"])
|
||||
assert network.proxy not in str(result)
|
||||
assert "user:pass" not in str(result)
|
||||
@@ -74,6 +74,7 @@ def validate_channel_config(
|
||||
if setup_spec is not None and setup_spec.validator is not None:
|
||||
context = ChannelValidationContext(
|
||||
allow_local_service_access=config.tools.webui_allow_local_service_access,
|
||||
network=config.network,
|
||||
)
|
||||
custom_payload = setup_spec.validator(values, context)
|
||||
if cast(object, custom_payload) is not None:
|
||||
@@ -321,6 +322,11 @@ def _enabled(values: dict[str, Any]) -> bool:
|
||||
return _truthy(values.get("enabled"))
|
||||
|
||||
|
||||
def resolve_proxy(values: dict[str, Any], context: ChannelValidationContext) -> str | None:
|
||||
"""Resolve a channel's opt-in against the host's shared network settings."""
|
||||
return context.network.resolve_proxy(_truthy(channel_field_value(values, "useProxy")))
|
||||
|
||||
|
||||
def _label(field: str) -> str:
|
||||
words = re.sub(r"([a-z])([A-Z])", r"\1 \2", field).replace(".", " ").replace("_", " ")
|
||||
return words[:1].upper() + words[1:]
|
||||
@@ -424,6 +430,7 @@ __all__ = [
|
||||
"payload",
|
||||
"probe_tcp",
|
||||
"required_checks",
|
||||
"resolve_proxy",
|
||||
"status_from_checks",
|
||||
"string_value",
|
||||
"truthy",
|
||||
|
||||
@@ -331,14 +331,15 @@ class WhatsAppConnectStore:
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
|
||||
|
||||
section = getattr(load_config().channels, "whatsapp", None)
|
||||
root_config = load_config()
|
||||
section = getattr(root_config.channels, "whatsapp", None)
|
||||
if section is not None and hasattr(section, "model_dump"):
|
||||
config = section.model_dump(mode="json", by_alias=True)
|
||||
elif isinstance(section, dict):
|
||||
config = dict(cast(dict[str, Any], section))
|
||||
else:
|
||||
config = {}
|
||||
channel = WhatsAppChannel(config, MessageBus())
|
||||
channel = WhatsAppChannel(config, MessageBus(), network=root_config.network)
|
||||
return channel, channel.connect_database_path()
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -8,7 +8,7 @@ from nanobot.channels.whatsapp.validation import validate
|
||||
|
||||
SETUP_SPEC = ChannelSetupSpec(
|
||||
fields={
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
"allowFrom": field("list", snapshot=False),
|
||||
"groupPolicy": field(
|
||||
"enum",
|
||||
|
||||
@@ -22,6 +22,7 @@ from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir, get_runtime_subdir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -35,7 +36,7 @@ class WhatsAppConfig(Base):
|
||||
allow_from: list[str] = Field(default_factory=list)
|
||||
group_policy: Literal["open", "mention"] = "open"
|
||||
database_path: str = ""
|
||||
proxy: str = ""
|
||||
use_proxy: bool = False
|
||||
lid_mappings: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -299,19 +300,24 @@ class WhatsAppChannel(BaseChannel):
|
||||
|
||||
name = "whatsapp"
|
||||
display_name = "WhatsApp"
|
||||
uses_shared_proxy = True
|
||||
|
||||
@classmethod
|
||||
def default_config(cls) -> dict[str, Any]:
|
||||
return WhatsAppConfig().model_dump(by_alias=True)
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
legacy_bridge_fields = (
|
||||
_legacy_bridge_config_fields(cast(dict[str, Any], config))
|
||||
if isinstance(config, dict) else []
|
||||
)
|
||||
if isinstance(config, dict):
|
||||
config = WhatsAppConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: WhatsAppConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
if legacy_bridge_fields:
|
||||
self.logger.warning(
|
||||
"Ignoring deprecated WhatsApp bridge config fields: {}. "
|
||||
@@ -348,11 +354,9 @@ class WhatsAppChannel(BaseChannel):
|
||||
return api.NewAClient(str(db_path))
|
||||
|
||||
async def _connect_client(self, client: Any) -> Any:
|
||||
proxy = self.config.proxy.strip()
|
||||
proxy = self._proxy
|
||||
if not proxy:
|
||||
return await client.connect()
|
||||
if "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
from neonize._binder import ProxySettings
|
||||
|
||||
return await client.connect(ProxySettings(proxy_address=proxy))
|
||||
@@ -513,8 +517,12 @@ class WhatsAppChannel(BaseChannel):
|
||||
|
||||
async def _fetch_remote_media(self, url: str) -> bytes:
|
||||
timeout = httpx.Timeout(_REMOTE_MEDIA_TIMEOUT_SECONDS, connect=10.0)
|
||||
transport = (
|
||||
PinnedDNSAsyncTransport(inner=httpx.AsyncHTTPTransport(proxy=self._proxy))
|
||||
if self._proxy else PinnedDNSAsyncTransport()
|
||||
)
|
||||
async with httpx.AsyncClient(
|
||||
transport=PinnedDNSAsyncTransport(),
|
||||
transport=transport,
|
||||
follow_redirects=True,
|
||||
max_redirects=_REMOTE_MEDIA_MAX_REDIRECTS,
|
||||
timeout=timeout,
|
||||
|
||||
@@ -10,6 +10,7 @@ from typing import Any
|
||||
import pytest
|
||||
|
||||
from nanobot.channels.whatsapp.connect import WhatsAppConnectStore
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
@@ -359,3 +360,18 @@ async def test_cancel_during_finalize_does_not_promote_login_database(
|
||||
assert target.read_bytes() == b"working-session"
|
||||
assert not Path(channel.config.database_path).exists()
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
def test_connect_builds_channel_with_shared_network_settings(monkeypatch, tmp_path) -> None:
|
||||
database = tmp_path / "neonize.db"
|
||||
config = Config.model_validate({
|
||||
"network": {"proxy": "http://127.0.0.1:7890"},
|
||||
"channels": {"whatsapp": {"useProxy": True, "databasePath": str(database)}},
|
||||
})
|
||||
monkeypatch.setattr("nanobot.channels.whatsapp.connect.load_config", lambda: config)
|
||||
|
||||
channel, target = WhatsAppConnectStore._build_channel()
|
||||
|
||||
assert channel.network is config.network
|
||||
assert channel.config.use_proxy is True
|
||||
assert target == database
|
||||
@@ -18,6 +18,7 @@ from nanobot.channels.whatsapp.runtime import (
|
||||
_legacy_bridge_config_fields,
|
||||
_NeonizeAPI,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
class _Proto:
|
||||
@@ -139,7 +140,9 @@ async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) ->
|
||||
"neonize._binder",
|
||||
SimpleNamespace(ProxySettings=ProxySettings),
|
||||
)
|
||||
channel = _make_channel({"proxy": "127.0.0.1:23458"})
|
||||
channel = WhatsAppChannel(
|
||||
{"useProxy": True}, MessageBus(), network=NetworkConfig(proxy="127.0.0.1:23458"),
|
||||
)
|
||||
client = SimpleNamespace(connect=AsyncMock(return_value=None))
|
||||
|
||||
await channel._connect_client(client)
|
||||
@@ -150,7 +153,9 @@ async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) ->
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_client_without_proxy_uses_default_connection() -> None:
|
||||
channel = _make_channel({"proxy": ""})
|
||||
channel = WhatsAppChannel(
|
||||
{"useProxy": False}, MessageBus(), network=NetworkConfig(proxy="127.0.0.1:23458"),
|
||||
)
|
||||
client = SimpleNamespace(connect=AsyncMock(return_value=None))
|
||||
|
||||
await channel._connect_client(client)
|
||||
@@ -828,3 +833,32 @@ def test_reset_database_removes_sqlite_sidecars(tmp_path) -> None:
|
||||
assert not db.exists()
|
||||
assert not wal.exists()
|
||||
assert not shm.exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remote_media_uses_shared_proxy_without_bypassing_url_guard(monkeypatch) -> None:
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
proxies = []
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
return httpx.Response(200, content=b"remote media")
|
||||
|
||||
def proxy_transport(*, proxy):
|
||||
proxies.append(proxy)
|
||||
return httpx.MockTransport(handler)
|
||||
|
||||
monkeypatch.setattr(whatsapp_module.httpx, "AsyncHTTPTransport", proxy_transport)
|
||||
channel = WhatsAppChannel({"useProxy": True}, MessageBus(), network=network)
|
||||
|
||||
with pytest.raises(httpx.RequestError, match="private/internal"):
|
||||
await channel._fetch_remote_media("http://127.0.0.1/media.wav")
|
||||
|
||||
assert proxies == [network.proxy]
|
||||
assert requests == []
|
||||
|
||||
public_url = "https://93.184.216.34/media.wav"
|
||||
assert await channel._fetch_remote_media(public_url) == b"remote media"
|
||||
assert proxies == [network.proxy, network.proxy]
|
||||
assert [str(request.url) for request in requests] == [public_url]
|
||||
@@ -3,11 +3,23 @@
|
||||
from typing import Any
|
||||
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
from nanobot.channels.validation import check, enabled, official_action, payload, string_value
|
||||
from nanobot.channels.validation import (
|
||||
check,
|
||||
enabled,
|
||||
official_action,
|
||||
payload,
|
||||
resolve_proxy,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks: list[dict[str, Any]] = []
|
||||
try:
|
||||
resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return payload("whatsapp", "invalid", checks, can_enable=False)
|
||||
if enabled(values) or string_value(values.get("databasePath")):
|
||||
checks.append(
|
||||
check("local_state", "Local login state", "pass", "Saved local login state was detected.")
|
||||
|
||||
@@ -16,7 +16,7 @@ export default {
|
||||
mode: "connect",
|
||||
docsUrl: chatAppGuideUrl("whatsapp"),
|
||||
manualFields: [
|
||||
{ key: "channels.whatsapp.proxy", section: "connection" },
|
||||
{ key: "channels.whatsapp.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.whatsapp.allowFrom", section: "access" },
|
||||
{ key: "channels.whatsapp.groupPolicy", section: "behavior" },
|
||||
],
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Allowlist"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Lista de permitidos"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Liste d’autorisation"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Daftar izin"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "許可リスト"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "허용 목록"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Lista de permissão"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Danh sách cho phép"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "白名单"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "允許清單"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -30,7 +30,7 @@ from nanobot.cli.models import (
|
||||
get_model_catalog,
|
||||
get_model_context_limit,
|
||||
)
|
||||
from nanobot.config.loader import get_config_path, load_config, resolve_config_env_vars
|
||||
from nanobot.config.loader import get_config_path, load_config
|
||||
from nanobot.config.schema import Config, ModelPresetConfig
|
||||
from nanobot.providers.oauth_guidance import OAUTH_CLI_KIT_MISSING_MESSAGE
|
||||
|
||||
@@ -1321,7 +1321,8 @@ def _run_channel_login(
|
||||
|
||||
console.print(f"[{_UI_ACCENT}]Starting {display_name} login...[/]")
|
||||
try:
|
||||
channel = channel_cls(model, bus=None)
|
||||
kwargs = {"network": config.network} if channel_cls.uses_shared_proxy else {}
|
||||
channel = channel_cls(model, bus=None, **kwargs)
|
||||
success = asyncio.run(channel.login(force=False))
|
||||
except KeyboardInterrupt:
|
||||
console.print("\n[dim]Login cancelled.[/dim]")
|
||||
@@ -1601,9 +1602,7 @@ def _quick_start_requires_api_key(provider_name: str, info: _QuickStartProviderI
|
||||
|
||||
def _quick_start_codex_proxy(config: Config) -> str | None:
|
||||
"""Resolve only the Codex proxy without validating unrelated provider secrets."""
|
||||
proxy_config = Config()
|
||||
proxy_config.providers.openai_codex.proxy = config.providers.openai_codex.proxy
|
||||
return resolve_config_env_vars(proxy_config).providers.openai_codex.proxy or None
|
||||
return config.network.resolve_proxy(config.providers.openai_codex.use_proxy)
|
||||
|
||||
|
||||
def _quick_start_oauth_login(config: Config, provider_name: str) -> bool:
|
||||
|
||||
@@ -224,7 +224,8 @@ def _login_openai_codex() -> None:
|
||||
get_token, login_oauth_interactive = _load_openai_oauth_client()
|
||||
proxy = None
|
||||
try:
|
||||
proxy = resolve_config_env_vars(load_config()).providers.openai_codex.proxy or None
|
||||
config = resolve_config_env_vars(load_config())
|
||||
proxy = config.network.resolve_proxy(config.providers.openai_codex.use_proxy)
|
||||
except ValueError as e:
|
||||
console.print(f"[red]{e}[/red]")
|
||||
raise typer.Exit(1) from e
|
||||
@@ -267,7 +268,8 @@ def _login_xai_grok() -> None:
|
||||
from nanobot.providers.xai_oauth import get_xai_oauth_token, login_xai_oauth
|
||||
|
||||
try:
|
||||
proxy = resolve_config_env_vars(load_config()).providers.xai_grok.proxy or None
|
||||
config = resolve_config_env_vars(load_config())
|
||||
proxy = config.network.resolve_proxy(config.providers.xai_grok.use_proxy)
|
||||
except ValueError as exc:
|
||||
console.print(f"[red]{exc}[/red]")
|
||||
raise typer.Exit(1) from exc
|
||||
|
||||
@@ -11,6 +11,7 @@ from pydantic_settings import SettingsError
|
||||
|
||||
from nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issues
|
||||
from nanobot.config.home import get_home_path
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.utils.file_io import write_text_atomic
|
||||
|
||||
@@ -156,8 +157,9 @@ def save_config(config: Config, config_path: Path | None = None) -> None:
|
||||
settings = provider.model_dump(
|
||||
mode="json",
|
||||
by_alias=True,
|
||||
include={"proxy", "extra_body"},
|
||||
include={"use_proxy", "extra_body"},
|
||||
exclude_none=True,
|
||||
exclude_unset=True,
|
||||
)
|
||||
if settings:
|
||||
data.setdefault("providers", {})[alias] = settings
|
||||
@@ -234,6 +236,9 @@ def resolve_env_refs(value: object) -> object:
|
||||
|
||||
|
||||
def _resolve_in_place(obj: Any) -> Any:
|
||||
if isinstance(obj, NetworkConfig):
|
||||
proxy = obj.resolve_environment()
|
||||
return obj.model_copy(update={"proxy": proxy}) if proxy != obj.proxy else obj
|
||||
if isinstance(obj, str):
|
||||
new = _ENV_REF_PATTERN.sub(_env_replace, obj)
|
||||
return new if new != obj else obj
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Instance-scoped outbound proxy configuration."""
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Any, cast
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
from pydantic_core import PydanticCustomError
|
||||
|
||||
from nanobot.config_base import Base
|
||||
|
||||
_ENV_REF_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
||||
|
||||
|
||||
class NetworkConfig(Base):
|
||||
proxy: str | None = Field(default=None, repr=False)
|
||||
|
||||
@field_validator("proxy")
|
||||
@classmethod
|
||||
def normalize_proxy(cls, value: str | None) -> str | None:
|
||||
value = value.strip() if value else ""
|
||||
if not value:
|
||||
return None
|
||||
if "://" not in value and not _ENV_REF_PATTERN.fullmatch(value):
|
||||
value = f"http://{value}"
|
||||
if "${" in value:
|
||||
return value
|
||||
try:
|
||||
parsed = urlsplit(value)
|
||||
valid = (
|
||||
parsed.scheme in {"http", "https", "socks5", "socks5h"}
|
||||
and bool(parsed.hostname)
|
||||
and parsed.port != 0
|
||||
and not parsed.query
|
||||
and not parsed.fragment
|
||||
and parsed.path in {"", "/"}
|
||||
and not any(char.isspace() for char in value)
|
||||
)
|
||||
except ValueError:
|
||||
valid = False
|
||||
if not valid:
|
||||
raise ValueError("Enter an HTTP, HTTPS or SOCKS5 proxy URL")
|
||||
return value
|
||||
|
||||
def resolve_environment(self) -> str | None:
|
||||
value = self.proxy or ""
|
||||
userinfo_start = value.find("://") + 3
|
||||
userinfo_end = value.rfind("@")
|
||||
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
resolved = os.environ[match[1]]
|
||||
if userinfo_start <= match.start() < userinfo_end:
|
||||
if match.start() == userinfo_start and match.end() == userinfo_end:
|
||||
# Whole userinfo supplies its own delimiter and URL escapes.
|
||||
username, separator, password = resolved.partition(":")
|
||||
return f"{quote(username, safe='%')}{separator}{quote(password, safe='%')}"
|
||||
return quote(resolved, safe="")
|
||||
return resolved
|
||||
|
||||
try:
|
||||
return self.normalize_proxy(_ENV_REF_PATTERN.sub(replace, value))
|
||||
except KeyError:
|
||||
raise ValueError("The shared proxy environment variable is not set") from None
|
||||
|
||||
def resolve_proxy(self, enabled: bool) -> str | None:
|
||||
if not enabled:
|
||||
return None
|
||||
proxy = self.resolve_environment()
|
||||
if not proxy:
|
||||
raise ValueError("Configure the shared proxy in Advanced before enabling it")
|
||||
return proxy
|
||||
|
||||
|
||||
def _config_object(value: object) -> dict[str, Any] | None:
|
||||
return cast(dict[str, Any], value) if isinstance(value, dict) else None
|
||||
|
||||
|
||||
def migrate_legacy_proxy_config(value: Any) -> Any:
|
||||
"""Consolidate legacy addresses after settings sources have been merged."""
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
data = cast(dict[str, Any], value)
|
||||
sections: list[dict[str, Any]] = []
|
||||
providers = _config_object(data.get("providers")) or {}
|
||||
sections.extend(section for value in providers.values() if (section := _config_object(value)) is not None)
|
||||
tools = _config_object(data.get("tools")) or {}
|
||||
if (web := _config_object(tools.get("web"))) is not None:
|
||||
sections.append(web)
|
||||
channels = _config_object(data.get("channels")) or {}
|
||||
sections.extend(section for name in ("telegram", "discord", "slack", "matrix", "whatsapp") if (section := _config_object(channels.get(name))) is not None)
|
||||
|
||||
network = data.get("network")
|
||||
explicit_proxy = isinstance(network, NetworkConfig) or isinstance(network, dict) and "proxy" in network
|
||||
addresses: set[str] = set()
|
||||
migrated: list[dict[str, Any]] = []
|
||||
for section in sections:
|
||||
raw = section.get("proxy")
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
if not explicit_proxy:
|
||||
proxy = NetworkConfig.normalize_proxy(raw)
|
||||
assert proxy is not None
|
||||
username = section.get("proxyUsername", section.get("proxy_username"))
|
||||
password = section.get("proxyPassword", section.get("proxy_password"))
|
||||
if isinstance(username, str) and username and isinstance(password, str) and password:
|
||||
if _ENV_REF_PATTERN.fullmatch(proxy):
|
||||
raise PydanticCustomError("proxy_credential_migration", "Combine the Discord proxy URL and credentials into one full URL environment variable, or set network.proxy before upgrading.")
|
||||
scheme, host = proxy.split("://", 1)
|
||||
host = host.rsplit("@", 1)[-1]
|
||||
credentials = f"{quote(username, safe='${}')}:{quote(password, safe='${}')}"
|
||||
proxy = f"{scheme}://{credentials}@{host}"
|
||||
addresses.add(proxy)
|
||||
migrated.append(section)
|
||||
|
||||
if addresses:
|
||||
if len(addresses) > 1:
|
||||
raise PydanticCustomError("proxy_address_migration", "Multiple legacy proxy addresses are no longer supported. Set network.proxy to one address before upgrading.")
|
||||
if not isinstance(network, dict):
|
||||
network = {}
|
||||
data["network"] = network
|
||||
network["proxy"] = next(iter(addresses))
|
||||
for section in sections:
|
||||
for key in ("proxy", "proxyUsername", "proxy_username", "proxyPassword", "proxy_password"):
|
||||
section.pop(key, None)
|
||||
for section in migrated:
|
||||
if "useProxy" not in section and "use_proxy" not in section:
|
||||
section["useProxy"] = True
|
||||
return data
|
||||
@@ -21,6 +21,7 @@ from nanobot.agent.tools.web_config import (
|
||||
)
|
||||
from nanobot.agent.tools.web_config import WebToolsConfig
|
||||
from nanobot.config.home import get_default_workspace
|
||||
from nanobot.config.network import NetworkConfig, migrate_legacy_proxy_config
|
||||
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
|
||||
from nanobot.config.timezone import detect_system_timezone
|
||||
from nanobot.config_base import Base
|
||||
@@ -255,7 +256,7 @@ class ProviderConfig(Base):
|
||||
extra_headers: dict[str, str] | None = None # Custom headers (e.g. APP-Code for AiHubMix)
|
||||
extra_body: dict[str, Any] | None = None # Extra provider request fields; shape depends on provider/API surface
|
||||
extra_query: dict[str, str] | None = None # Extra query params (e.g. api-version for Azure-style gateways)
|
||||
proxy: str | None = None # Explicit HTTP proxy; image downloads trust its DNS and egress
|
||||
use_proxy: bool = False
|
||||
thinking_style: str | None = None # Thinking/reasoning style for custom providers
|
||||
|
||||
# Valid values mirror the keys of _THINKING_STYLE_MAP in
|
||||
@@ -421,6 +422,7 @@ class MCPServerConfig(Base):
|
||||
cwd: str = "" # Stdio: working directory for MCP server runtime artifacts
|
||||
url: str = "" # HTTP/SSE: endpoint URL
|
||||
headers: dict[str, str] = Field(default_factory=dict) # HTTP/SSE: custom headers
|
||||
use_proxy: bool = False
|
||||
tool_timeout: int = 30 # seconds before a tool call is cancelled
|
||||
enabled_tools: list[str] = Field(default_factory=lambda: ["*"]) # Only register these tools; accepts raw MCP names or wrapped mcp_<server>_<tool> names; ["*"] = all capabilities (tools, resources, prompts); any restriction = only listed tools, no resources/prompts
|
||||
|
||||
@@ -505,6 +507,7 @@ class Config(BaseSettings):
|
||||
channels: ChannelsConfig = Field(default_factory=ChannelsConfig)
|
||||
transcription: TranscriptionConfig = Field(default_factory=TranscriptionConfig)
|
||||
providers: ProvidersConfig = Field(default_factory=ProvidersConfig)
|
||||
network: NetworkConfig = Field(default_factory=NetworkConfig)
|
||||
api: ApiConfig = Field(default_factory=ApiConfig)
|
||||
gateway: GatewayConfig = Field(default_factory=GatewayConfig)
|
||||
tools: ToolsConfig = Field(default_factory=ToolsConfig)
|
||||
@@ -514,6 +517,11 @@ class Config(BaseSettings):
|
||||
serialization_alias="modelPresets",
|
||||
)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _migrate_proxy_config(cls, value: Any) -> Any:
|
||||
return migrate_legacy_proxy_config(value)
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
cls,
|
||||
|
||||
@@ -69,13 +69,14 @@ def _make_provider_core(
|
||||
p = setup.provider_config
|
||||
spec = setup.spec
|
||||
backend = setup.backend
|
||||
proxy = config.network.resolve_proxy(p.use_proxy) if p else None
|
||||
|
||||
if backend == "openai_codex":
|
||||
from nanobot.providers.openai_codex_provider import OpenAICodexProvider
|
||||
|
||||
provider = OpenAICodexProvider(
|
||||
default_model=model,
|
||||
proxy=getattr(p, "proxy", None) if p else None,
|
||||
proxy=proxy,
|
||||
extra_body=p.extra_body if p else None,
|
||||
provider_name=provider_name,
|
||||
)
|
||||
@@ -84,7 +85,7 @@ def _make_provider_core(
|
||||
|
||||
provider = XAIGrokProvider(
|
||||
default_model=model,
|
||||
proxy=getattr(p, "proxy", None) if p else None,
|
||||
proxy=proxy,
|
||||
extra_body=p.extra_body if p else None,
|
||||
provider_name=provider_name,
|
||||
)
|
||||
@@ -120,7 +121,7 @@ def _make_provider_core(
|
||||
extra_headers=_provider_extra_headers(spec, p),
|
||||
extra_body=p.extra_body if p else None,
|
||||
extra_query=p.extra_query if p else None,
|
||||
proxy=p.proxy if p else None,
|
||||
proxy=proxy,
|
||||
spec=custom_spec,
|
||||
provider_name=provider_name,
|
||||
)
|
||||
@@ -148,7 +149,7 @@ def _make_provider_core(
|
||||
extra_body=p.extra_body if p else None,
|
||||
model_api=setup.model_api,
|
||||
extra_query=p.extra_query if p else None,
|
||||
proxy=p.proxy if p else None,
|
||||
proxy=proxy,
|
||||
provider_name=provider_name,
|
||||
)
|
||||
|
||||
@@ -261,7 +262,7 @@ def _preset_provider_signature(
|
||||
preset.reasoning_effort,
|
||||
preset.context_window_tokens,
|
||||
preset.api.model_dump_json() if preset.api is not None else None,
|
||||
getattr(provider_config, "proxy", None) if provider_config else None,
|
||||
config.network.resolve_proxy(provider_config.use_proxy) if provider_config else None,
|
||||
provider_config.thinking_style if provider_config else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -123,14 +123,17 @@ def resolve_provider_route(
|
||||
provider_config = apply_request_overrides(provider_config, preset)
|
||||
if (
|
||||
provider_config
|
||||
and provider_config.proxy
|
||||
and provider_config.use_proxy
|
||||
and backend not in {"openai_compat", "openai_codex", "xai_grok", "anthropic"}
|
||||
):
|
||||
raise ValueError(
|
||||
f"providers.{provider_name}.proxy is only supported for "
|
||||
f"providers.{provider_name}.use_proxy is only supported for "
|
||||
"OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI Grok."
|
||||
)
|
||||
|
||||
if provider_config:
|
||||
config.network.resolve_proxy(provider_config.use_proxy)
|
||||
|
||||
if backend == "azure_openai":
|
||||
if not provider_config or not provider_config.api_base:
|
||||
raise ValueError("Azure OpenAI requires api_base in config.")
|
||||
@@ -177,7 +180,7 @@ def resolve_automatic_model_api(
|
||||
from nanobot.providers.github_copilot_provider import cached_github_copilot_model_api
|
||||
|
||||
api = cached_github_copilot_model_api(
|
||||
setup.model, provider_config.proxy if provider_config else None,
|
||||
setup.model, config.network.resolve_proxy(provider_config.use_proxy) if provider_config else None,
|
||||
)
|
||||
if api is not None:
|
||||
return setup.provider_name, api.preferred_api
|
||||
|
||||
@@ -15,6 +15,7 @@ from urllib.parse import SplitResult, parse_qs, urlsplit, urlunsplit
|
||||
from nanobot.agent.tools.mcp import MCPConnection, connect_mcp_servers
|
||||
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH, MCPOAuthHandlers
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.security.network import validate_url_target
|
||||
@@ -44,6 +45,7 @@ class _McpOAuthFlow:
|
||||
flow_id: str
|
||||
name: str
|
||||
cfg: MCPServerConfig
|
||||
network: NetworkConfig
|
||||
redirect_uri: str
|
||||
manual_callback: bool
|
||||
expires_at: float
|
||||
@@ -139,6 +141,7 @@ class McpOAuthManager:
|
||||
redirect_uri: str,
|
||||
*,
|
||||
reload_mcp: McpReload,
|
||||
network: NetworkConfig | None = None,
|
||||
reset_credentials: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
self._admission.check()
|
||||
@@ -156,7 +159,8 @@ class McpOAuthManager:
|
||||
flow = _McpOAuthFlow(
|
||||
flow_id=secrets.token_urlsafe(24),
|
||||
name=name,
|
||||
cfg=cfg,
|
||||
cfg=cfg.model_copy(deep=True),
|
||||
network=(network or NetworkConfig()).model_copy(deep=True),
|
||||
redirect_uri=redirect_uri,
|
||||
manual_callback=manual_callback,
|
||||
expires_at=now + _FLOW_TTL_S,
|
||||
@@ -348,6 +352,7 @@ class McpOAuthManager:
|
||||
{flow.name: flow.cfg},
|
||||
ToolRegistry(),
|
||||
oauth_handlers={flow.name: handlers},
|
||||
network=flow.network,
|
||||
)
|
||||
if flow.name not in connections:
|
||||
await self._close_connections(connections)
|
||||
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user