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
+1
-1
@@ -16,7 +16,7 @@ Shell execution (`ExecTool`, `agent/tools/shell.py`) also respects `restrict_to_
|
||||
|
||||
All outbound HTTP requests from agent tools must pass through the shared URL guards in `security/network.py` (`validate_url_target` or `resolve_url_target`). By default they block loopback, RFC1918 private addresses, CGNAT ranges, link-local ranges, and cloud metadata endpoints (including `169.254.169.254`).
|
||||
|
||||
For direct requests, the only escape hatch is `configure_ssrf_whitelist(cidrs)`, which reads from `config.tools.ssrf_whitelist` at load time. An explicitly configured `providers.<name>.proxy` is a separate user-authorized trust boundary for provider requests and provider-returned image URL downloads. Those downloads still reject malformed URLs and locally identifiable private/internal targets on every redirect, but hostnames unavailable to local DNS are delegated to the trusted proxy. The user-selected proxy owns final DNS resolution and network egress policy.
|
||||
For direct requests, the only escape hatch is `configure_ssrf_whitelist(cidrs)`, which reads from `config.tools.ssrf_whitelist` at load time. The shared `network.proxy` address enabled by `providers.<name>.useProxy` is a separate user-authorized trust boundary for provider requests and provider-returned image URL downloads. Those downloads still reject malformed URLs and locally identifiable private/internal targets on every redirect, but hostnames unavailable to local DNS are delegated to the trusted proxy. The user-selected proxy owns final DNS resolution and network egress policy.
|
||||
|
||||
HTTP/SSE MCP transports are part of this boundary: validate configured MCP URLs before probing or constructing clients, and validate each outgoing HTTP request before redirects are followed. Local/private HTTP MCP endpoints are allowed only through the explicit SSRF whitelist. Stdio MCP servers are not part of the HTTP SSRF path.
|
||||
|
||||
|
||||
@@ -339,6 +339,34 @@ A normal return from `send()` means either the visible payload was accepted by t
|
||||
|
||||
`send()` may run as soon as `is_running` becomes true. If a channel sets `_running` before its transport is ready, it must keep raising until delivery can be attempted safely. Small platform-specific retries are fine, but the final failure must still reach the manager.
|
||||
|
||||
### Optional shared proxy
|
||||
|
||||
Existing `__init__(config, bus)` constructors remain valid. `BaseChannel.uses_shared_proxy` defaults to `False`; only runtimes that explicitly set this class capability to `True` receive the instance-scoped top-level `NetworkConfig` as the keyword-only `network` argument. This capability is not a user setting.
|
||||
|
||||
To support the shared proxy, declare `use_proxy: bool = False` on your channel's config model and expose `"useProxy": ChannelFieldSpec(kind="bool", default=False)` in its setup fields. Opt in on the runtime class and forward `network` to the base constructor:
|
||||
|
||||
```python
|
||||
from typing import Any
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
class WebhookChannel(BaseChannel):
|
||||
uses_shared_proxy = True
|
||||
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = WebhookConfig(**config)
|
||||
super().__init__(config, bus, network=network)
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
```
|
||||
|
||||
Pass the resolved address to your platform clients. `useProxy: false` keeps the channel direct even when `network.proxy` is configured; `true` requires a shared proxy address and fails rather than silently connecting directly. Setup validators receive the same settings through `context.network`. Do not load global config or persist a proxy address in the channel config.
|
||||
|
||||
### Interactive Login
|
||||
|
||||
If your channel requires interactive authentication (e.g. QR code scan), override `login(force=False)`:
|
||||
|
||||
+4
-3
@@ -127,7 +127,7 @@ See the [native Linear agent guide](./guides/linear-agent.md) for the complete s
|
||||
|
||||
1. Create a bot with `@BotFather` and copy its token.
|
||||
2. Run `nanobot webui`, then open **Channels → Telegram**.
|
||||
3. Paste the token. If the gateway cannot reach Telegram directly, expand **Advanced** and add an HTTP or SOCKS proxy.
|
||||
3. Paste the token. If the gateway cannot reach Telegram directly, set the address in **Settings → Advanced → Shared proxy**, then enable **Use proxy** in Telegram's advanced options.
|
||||
4. Save and enable Telegram, then send the bot a direct message.
|
||||
|
||||
The configuration badge means nanobot found a saved token. The live connection check is separate, so a temporary Telegram or proxy outage does not make an existing configuration disappear. Saved tokens and proxy URLs remain masked.
|
||||
@@ -161,13 +161,14 @@ nanobot plugins enable telegram
|
||||
}
|
||||
```
|
||||
|
||||
If the gateway cannot reach Telegram directly, add a proxy to the same section:
|
||||
If the gateway cannot reach Telegram directly, set the shared address and enable it for Telegram:
|
||||
|
||||
```json
|
||||
{
|
||||
"network": { "proxy": "http://127.0.0.1:7890" },
|
||||
"channels": {
|
||||
"telegram": {
|
||||
"proxy": "http://127.0.0.1:7890"
|
||||
"useProxy": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+47
-13
@@ -69,6 +69,41 @@ If the WebUI does not expose the option you need, start from the task below. Mos
|
||||
| Run multiple isolated bots | separate `--home` directories, or `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Place `--home` before the subcommand; use the same instance selectors with `status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) |
|
||||
| Observe model calls | `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL` environment variables | Run one model call, then check the matching Langfuse project | [Langfuse Observability](#langfuse-observability) |
|
||||
|
||||
## Shared network proxy
|
||||
|
||||
Set one proxy address in **Settings → Advanced → Shared proxy**, then turn on **Use proxy** for each provider, Web access, channel, or remote MCP connection that needs it. The address is used by the gateway, so `127.0.0.1` refers to the machine running nanobot. Restart when Settings requests it. MCP connections can select the proxy before browser sign-in.
|
||||
|
||||
For proxies that require credentials, expand **Authentication (optional)** and enter the username and password, then choose **Save** to apply the address and credentials together. The same editor is available from **Configure proxy** without leaving the current form. Passwords are masked in the interface but remain part of the proxy URL in the local configuration; protect that file. If the address is a whole-URL `${ENV_VAR}` reference, include authentication in the referenced URL.
|
||||
|
||||
Only features with a **Use proxy** switch use this address. Turning a switch off preserves the feature's normal environment/system proxy behavior. An enabled switch without a configured address fails rather than silently connecting directly. Use a trusted proxy and keep credentials in its URL private.
|
||||
|
||||
<details>
|
||||
<summary>Manual configuration</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"network": { "proxy": "http://127.0.0.1:7890" },
|
||||
"providers": { "openai": { "useProxy": true } },
|
||||
"tools": {
|
||||
"web": { "useProxy": true },
|
||||
"mcpServers": {
|
||||
"figma-remote": {
|
||||
"type": "streamableHttp",
|
||||
"url": "https://mcp.figma.com/mcp",
|
||||
"auth": "oauth",
|
||||
"useProxy": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
HTTP, HTTPS, SOCKS5, and SOCKS5H URLs are accepted; individual integrations retain their transport limits. `${ENV_VAR}` references work in `network.proxy`.
|
||||
|
||||
</details>
|
||||
|
||||
On upgrade, one legacy proxy address moves to `network.proxy` and previously configured features receive `useProxy: true`. The migrated configuration is written on the next normal save, including `nanobot onboard --refresh`. If the old configuration contains different proxy addresses, choose one and set `network.proxy` explicitly before upgrading; multiple per-feature addresses are no longer supported. For Discord configurations that store the entire proxy URL in an environment variable and credentials separately, combine them into one full URL environment variable and set `network.proxy` to that reference before upgrading. Credential references inside a URL remain references when saved. Back up the original configuration before saving if you may need to downgrade.
|
||||
|
||||
## Environment Variables for Secrets
|
||||
|
||||
Instead of storing secrets directly in `config.json`, you can use `${VAR_NAME}` references that are resolved from environment variables at startup:
|
||||
@@ -277,7 +312,7 @@ A Base URL is the service address nanobot sends model requests to. Change it onl
|
||||
> - **Xiaomi MiMo thinking mode**: MiMo models (e.g. `mimo-v2.5-pro`) default to enabled thinking. In the preset's **Advanced options**, set reasoning effort to `none` to disable it, or `low` / `medium` / `high` to keep it on. Omitting the field preserves the provider's per-model default.
|
||||
> - **Xiaomi MiMo Token Plan**: If you're on MiMo's token plan, open the xiaomi_mimo connection in **Settings → Models** and set its base URL to `https://token-plan-sgp.xiaomimimo.com/v1`.
|
||||
> - **Custom providers**: Besides the built-in `custom` provider, any extra key under `providers` can define its own endpoint. For example, `providers.companyProxy.apiBase` plus `modelPresets.primary.provider: "companyProxy"` creates a separate custom provider. Set `apiBase`; set `apiKey` only when the endpoint requires it. Declare accepted protocols with `providers.<name>.api`; custom connections can use Chat Completions, Responses, or Anthropic Messages. See [custom connection APIs](#custom-connection-apis).
|
||||
> - **Provider-scoped proxy**: `providers.<name>.proxy` routes only that provider through an HTTP proxy. It is supported for OpenAI-compatible providers, Anthropic Messages, `openai_codex`, and `xai_grok`. Native `bedrock`, `azure_openai`, and `github_copilot` backends reject `proxy`.
|
||||
> - **Use proxy**: `providers.<name>.useProxy` opts that provider into the [shared network proxy](#shared-network-proxy). It is supported for OpenAI-compatible providers, Anthropic Messages, `openai_codex`, and `xai_grok`. Native `bedrock`, `azure_openai`, and `github_copilot` backends do not support this switch.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -754,14 +789,13 @@ The default model is `xai-grok/grok-4.6` with a 500,000-token context window. Th
|
||||
|
||||
This is xAI subscription OAuth, not X Developer OAuth. nanobot follows the public OAuth client and proxy contract used by [Grok Build](https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/02-authentication.md). The browser flow uses a random loopback callback and PKCE. The resulting token is stored in the active instance's `auth/xai.json` (normally `~/.nanobot/auth/xai.json`), separately from Grok Build so rotating refresh tokens cannot invalidate one another.
|
||||
|
||||
To use a provider-specific proxy, merge this into `config.json` before login:
|
||||
To use the shared proxy, configure its address and enable it for xAI before login:
|
||||
|
||||
```json
|
||||
{
|
||||
"network": { "proxy": "http://127.0.0.1:7890" },
|
||||
"providers": {
|
||||
"xaiGrok": {
|
||||
"proxy": "http://127.0.0.1:7890"
|
||||
}
|
||||
"xaiGrok": { "useProxy": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1744,7 +1778,7 @@ When ripgrep (`rg`) is installed, nanobot automatically uses it in place of the
|
||||
|
||||
## Web Tools
|
||||
|
||||
Open **Settings → Capabilities → Web access** to enable or disable web tools and configure search and fetch. Use **Configure → Advanced options** for the web proxy and User-Agent, and **Settings → Advanced** for the SSRF whitelist. Follow any restart prompt.
|
||||
Open **Settings → Capabilities → Web access** to enable or disable web tools and configure search and fetch. Use **Configure → Advanced options** for **Use proxy** and User-Agent, and **Settings → Advanced** for the shared proxy address and SSRF whitelist. Follow any restart prompt.
|
||||
|
||||
nanobot includes web search and web fetch tools. They are enabled by default. The collapsed examples below show the equivalent `tools.web` configuration.
|
||||
|
||||
@@ -1782,28 +1816,28 @@ nanobot uses a shared SSRF guard for built-in web fetches and HTTP/SSE MCP conne
|
||||
|
||||
Keep whitelist entries as narrow as possible, such as a single host CIDR (`192.168.1.50/32`). The whitelist is global for the shared SSRF guard; it is not limited to one tool or one MCP server. This guard does not filter network traffic from shell commands or stdio MCP processes. The shell sandboxes also allow network access; use host or container egress controls when you need to prevent outbound connections.
|
||||
|
||||
HTTP/SSE MCP connections use the same process-wide proxy environment behavior as `web_fetch`: proxied targets use the configured proxy, and URLs excluded by `NO_PROXY` remain DNS-pinned direct connections.
|
||||
Web access and HTTP/SSE MCP connections can opt into the [shared network proxy](#shared-network-proxy). With **Use proxy** off, their normal environment proxy settings and `NO_PROXY` still apply.
|
||||
|
||||
In WebUI, open **Settings → Capabilities → Web access → Configure → Advanced options** to set the web proxy. This setting applies to the agent's web search and page reading, not model providers, MCP, or your browser. `127.0.0.1` refers to the machine that runs nanobot, not the phone or computer that opens WebUI. Clear the field to use the default network settings, which can include proxy environment variables. After saving, restart nanobot when WebUI requests it. You can configure the proxy before enabling web access.
|
||||
Set the address in **Settings → Advanced → Shared proxy**, then enable **Use proxy** under **Settings → Capabilities → Web access → Configure → Advanced options**. This switch applies to web search and page reading; providers and MCP connections have their own switches. Your browser uses its own network settings. Follow any restart prompt. You can configure the proxy before enabling web access.
|
||||
|
||||
> [!TIP]
|
||||
> Use `proxy` in `tools.web` to route web requests through a proxy:
|
||||
> Set `network.proxy` once and enable `tools.web.useProxy` to route web requests through it:
|
||||
> <details>
|
||||
> <summary>Manual configuration</summary>
|
||||
>
|
||||
> ```json
|
||||
> { "tools": { "web": { "proxy": "http://127.0.0.1:7890" } } }
|
||||
> { "network": { "proxy": "http://127.0.0.1:7890" }, "tools": { "web": { "useProxy": true } } }
|
||||
> ```
|
||||
>
|
||||
> </details>
|
||||
> `web_fetch` applies DNS pinning for direct connections. When an explicit `tools.web.proxy` or a process-wide proxy environment variable applies to the target URL, nanobot still validates the requested URL locally, but DNS resolution for the outbound fetch happens at the proxy; configure only trusted proxies. URLs excluded by `NO_PROXY` keep the DNS-pinned direct path unless `tools.web.proxy` is configured.
|
||||
> Web requests still enforce URL safety checks when using a proxy. Use only trusted proxies: the proxy controls final DNS resolution and outbound access. With **Use proxy** enabled, the shared address takes precedence over environment proxy settings, including `NO_PROXY`.
|
||||
|
||||
### `tools.web`
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
|--------|------|---------|-------------|
|
||||
| `enable` | boolean | `true` | Enable or disable all built-in web tools (`web_search` + `web_fetch`) |
|
||||
| `proxy` | string or null | `null` | Proxy for web requests, for example `http://127.0.0.1:7890`. `web_fetch` DNS pinning applies only to direct connections; proxied fetches rely on the configured proxy as the trusted network exit. |
|
||||
| `useProxy` | boolean | `false` | Use the [shared network proxy](#shared-network-proxy) for web search and fetch. |
|
||||
| `userAgent` | string or null | `null` | User-Agent header for all web requests. If null, a browser one will be used |
|
||||
|
||||
### Web Search
|
||||
@@ -2098,7 +2132,7 @@ Queries are limited to 128 Unicode characters after trimming whitespace; longer
|
||||
|
||||
### Web Fetch
|
||||
|
||||
In **Settings → Capabilities → Web access**, expand the fetch options and choose whether to use Jina Reader. Save the change; use **Configure → Advanced options** in the same Web access card for network proxy settings.
|
||||
In **Settings → Capabilities → Web access**, expand the fetch options and choose whether to use Jina Reader. Save the change; use **Configure → Advanced options → Use proxy** to enable the address saved in **Settings → Advanced → Shared proxy**.
|
||||
|
||||
> [!TIP]
|
||||
> If you are having issues with JS proof-of-work or Cloudflare captchas, set a random user agent and disable Jina Reader:
|
||||
|
||||
@@ -28,12 +28,12 @@ Open **Channels → Telegram**:
|
||||
|
||||
1. If Telegram support is not installed, turn on its switch and confirm the installation.
|
||||
2. Paste the token from BotFather.
|
||||
3. If the gateway cannot reach Telegram directly, expand **Advanced** and enter an HTTP or SOCKS proxy such as `http://127.0.0.1:7890`.
|
||||
3. If the gateway cannot reach Telegram directly, set an address such as `http://127.0.0.1:7890` in **Settings → Advanced → Shared proxy**, then enable **Use proxy** in Telegram's advanced options.
|
||||
4. Save and enable Telegram. For a first private setup, leave the sender allowlist empty: new senders must pair before they can use the agent. Do not set it to `*`.
|
||||
|
||||
The configuration badge appears as soon as a bot token is saved. A connection check is separate: if Telegram is temporarily unreachable, the saved configuration remains valid and the bot can continue working in environments where the gateway has network access.
|
||||
|
||||
Saved tokens and proxy URLs are masked. A proxy entered here is used both for the connection check and for normal Telegram traffic.
|
||||
Saved tokens and proxy URLs are masked. **Use proxy** applies the shared address to both the connection check and normal Telegram traffic.
|
||||
|
||||
## Manual setup
|
||||
|
||||
@@ -50,17 +50,18 @@ Then merge this snippet into `~/.nanobot/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"network": { "proxy": "http://127.0.0.1:7890" },
|
||||
"channels": {
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "YOUR_BOT_TOKEN",
|
||||
"proxy": "http://127.0.0.1:7890"
|
||||
"useProxy": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Omit `proxy` when the gateway can reach Telegram directly.
|
||||
Leave `useProxy` off when the gateway can reach Telegram directly.
|
||||
|
||||
Omitting `allowFrom` enables pairing-only mode. The first DM from a new user gets a pairing code instead of agent access.
|
||||
|
||||
@@ -109,7 +110,7 @@ Send the message again after approval. Confirm that your private chat now receiv
|
||||
## Troubleshooting
|
||||
|
||||
- If the channel is not listed, run `nanobot plugins enable telegram` again in the same Python environment.
|
||||
- If the WebUI shows a saved configuration but the live check cannot reach Telegram, the token is still saved. Confirm the gateway can reach `api.telegram.org`, or open **Advanced → Network proxy** and enter a proxy.
|
||||
- If the WebUI shows a saved configuration but the live check cannot reach Telegram, the token is still saved. Confirm the gateway can reach `api.telegram.org`, or configure **Settings → Advanced → Shared proxy** and turn on Telegram's **Use proxy** switch.
|
||||
- If Telegram rejects the token, copy the current token from BotFather or regenerate it.
|
||||
- If messages do not arrive, check the Telegram runtime status in **Channels** and the logs of the running gateway. Confirm it is enabled and can reach Telegram; do not start a second gateway to diagnose the first.
|
||||
- If a first DM returns a pairing code, that is expected. Approve the code before testing normal agent replies.
|
||||
|
||||
@@ -85,7 +85,7 @@ Provider settings reuse normal provider config fields:
|
||||
| `providers.<name>.apiBase` | Optional custom base URL |
|
||||
| `providers.<name>.extraHeaders` | Headers merged into provider requests |
|
||||
| `providers.<name>.extraBody` | Extra JSON fields merged into provider request bodies |
|
||||
| `providers.<name>.proxy` | Explicit trusted HTTP proxy for provider requests and returned image URL downloads |
|
||||
| `providers.<name>.useProxy` | Use the shared `network.proxy` address for provider requests and returned image URL downloads |
|
||||
|
||||
For providers that return image URLs, direct downloads use DNS pinning. When an explicit provider `proxy` is configured, nanobot rejects malformed URLs and locally identifiable private/internal targets on the initial URL and every redirect. Hostnames unavailable to local DNS are delegated to that trusted proxy, which owns final DNS resolution and network egress. Process-wide proxy environment variables are not used for these downloads.
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Open **Apps → MCP** to find a service, configure its connection, and select **Connect**. Presets save MCP server configuration; the gateway discovers and runs the tools. Each service still requires its own account access and permissions. The tables below list all built-in presets.
|
||||
|
||||
For a remote HTTP/SSE service that needs a proxy, first set the shared address in **Settings → Advanced → Shared proxy**, then turn on **Use proxy** in its connection dialog before selecting **Connect**. The gateway uses that route for MCP requests and authorization. The browser's sign-in page still uses your browser's own network settings. Local stdio servers keep their own networking configuration.
|
||||
|
||||
## Hosted services
|
||||
|
||||
Browser sign-in uses the service's MCP OAuth flow. API-key presets ask for the credential listed below and add it to the required HTTP header or URL parameter. Paste the token itself into the credential field.
|
||||
@@ -123,6 +125,8 @@ Datadog uses the MCP endpoint for your Datadog site and a Personal or Service Ac
|
||||
|
||||
Figma uses the desktop app's local MCP endpoint, and Supabase starts a local server in read-only mode. Their **(remote)** variants use browser sign-in. GitHub uses Docker; **GitHub (remote)** uses a personal access token. Changes to credentials retain the connection's tool selection, timeout, and other saved settings.
|
||||
|
||||
Figma (remote) also requires [Figma's approval of the MCP client](https://developers.figma.com/docs/figma-mcp-server/remote-server-installation/). A client rejected during registration cannot connect until Figma approves it, even when its network connection works.
|
||||
|
||||
## Local servers
|
||||
|
||||
Local servers run on the gateway computer. Install the runtime or application listed for each service. Stdio servers use a managed working directory under the nanobot data directory so their runtime files stay outside the source checkout. Figma connects over HTTP to the local desktop app.
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ These fields answer different questions:
|
||||
| `model` | `modelPresets.<name>.model` | The model ID expected by that provider or gateway. |
|
||||
| `apiKey` | `providers.<provider>.apiKey` | Credential for that provider. Use `${ENV_VAR}` for secrets. |
|
||||
| `apiBase` | `providers.<provider>.apiBase` | HTTP base URL of the provider endpoint. |
|
||||
| `proxy` | `providers.<provider>.proxy` | Optional HTTP proxy for this provider only. Supported for OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI OAuth. |
|
||||
| `use_proxy` | `providers.<provider>.useProxy` | Use the shared `network.proxy` address for this provider. Supported for OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI OAuth. |
|
||||
|
||||
You usually omit `apiBase` for hosted built-in providers such as OpenRouter, Anthropic direct, OpenAI direct, Groq, or Bedrock because nanobot knows their default endpoints. Set `apiBase` for `custom`, local OpenAI-compatible servers, provider proxies, regional endpoints, or subscription endpoints. Include the API version path when the endpoint requires it, for example `https://api.example.com/v1` or `http://localhost:11434/v1`.
|
||||
|
||||
|
||||
@@ -148,12 +148,12 @@ If you need a known-good snippet instead of diagnosis, use [`provider-cookbook.m
|
||||
| Local model connection refused | Ollama, vLLM, LM Studio, or another local server is not running, or `apiBase` points to the wrong port. |
|
||||
| Bedrock validation error | Check AWS region, credentials, model access, model ID, and whether the model supports Converse. |
|
||||
| OAuth provider fails | Run the matching login command: `openai-codex`, `xai-grok`, or `github-copilot`, normally with `--set-main`. |
|
||||
| Codex OAuth needs a proxy | Set `providers.openaiCodex.proxy` before running the login command. The proxy applies to login, token refresh, and Codex API requests. |
|
||||
| Codex OAuth needs a proxy | Set the address in **Settings → Advanced → Shared proxy** and enable **Use proxy** for OpenAI Codex before login. In `config.json`, use `network.proxy` and `providers.openaiCodex.useProxy: true`. This applies to login, token refresh, and Codex API requests. |
|
||||
| Codex login runs on a remote/headless machine | In the WebUI, open ChatGPT in your local browser; when the localhost callback page cannot load, copy the full `http://localhost:1455/auth/callback?...` URL from the address bar and paste it into the WebUI dialog. From the CLI, open the printed URL locally and paste the same callback URL back into the terminal. |
|
||||
| Codex login runs in Docker | Start the container with `docker run -it` so the OAuth flow has an interactive terminal. |
|
||||
| Codex says a model is not supported with a ChatGPT account | Use provider `openai_codex` with a Codex model such as `openai-codex/gpt-5.6-sol`. Do not use the direct-API `openai/...` prefix with Codex OAuth. |
|
||||
| Config says `providers.openai_codex` conflicts with the built-in provider | Under `providers`, keep only the canonical `openaiCodex` settings key and remove a duplicate `openai_codex` key. A model preset's `provider` value remains `openai_codex`. |
|
||||
| xAI OAuth needs a proxy | Set `providers.xaiGrok.proxy` before login. It applies to OAuth discovery, token exchange/refresh, and Grok subscription requests. |
|
||||
| xAI OAuth needs a proxy | Set `network.proxy` and `providers.xaiGrok.useProxy: true` before login, or use the shared address and provider switch in Settings. This applies to OAuth discovery, token exchange/refresh, and Grok subscription requests. |
|
||||
| xAI login runs on a remote/headless machine | In the WebUI, finish sign-in in your local browser; if the loopback redirect cannot reach the server, copy the final URL from the address bar into the WebUI dialog. From the CLI, run `nanobot provider login xai-grok` interactively, open the printed URL elsewhere, and paste the final callback URL or authorization code when prompted. |
|
||||
| xAI returns 403 or subscription access denied | Confirm the signed-in account has an eligible X Premium / Grok subscription, then run `nanobot provider login xai-grok` again. This provider does not use an xAI API key or X Developer OAuth. |
|
||||
| xAI returns 400 `invalid-argument` | Read the bounded `Response body` appended to the provider error. Hosted `x_search` is sent only when xAI's model catalog advertises `supportsBackendSearch`; the model ID `grok-4.5` itself is valid. |
|
||||
|
||||
@@ -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": "使用代理"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
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