Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(connect): move email config building and verification to tinychannels

Steven Enamakel6b0f16a76905
diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect.rs b/crates/openhuman-core/src/channels/controllers/ops/connect.rs
index 2bf288df79..6e488dcbca 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/connect.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/connect.rs
@@ -21,17 +21,3 @@ pub use status::{
channel_status, connected_channel_slugs, get_default_channel, set_default_channel,
};
pub use test_channel::test_channel;
-
-// `email_config_tests` below shares this module's scope via `use super::*;` —
-// the same way it did when this was one unsplit file — so bring in the
-// symbols it (and any sibling test module) reaches that way.
-#[cfg(test)]
-use crate::channels::email_channel::EmailConfig;
-#[cfg(test)]
-use email::{build_email_config, parse_email_senders, parse_port_field};
-#[cfg(test)]
-use serde_json::Value;
-
-#[cfg(test)]
-#[path = "connect_email_config_tests_tests.rs"]
-mod email_config_tests;
diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rs
index 54d25dabed..c1802bb281 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rs
@@ -11,11 +11,13 @@ use crate::security::credentials;
use super::super::super::definitions::{find_channel_definition, ChannelAuthMode};
use super::super::types::ChannelConnectionResult;
-use super::super::yuanbao::{
+use super::email::persist_email_config;
+use super::shared::{credential_provider, parse_allowed_users, parse_optional_bool};
+use tinychannels::controllers::build_email_config;
+use tinychannels::providers::verify_email_credentials;
+use tinychannels::providers::yuanbao::connect::{
build_effective_yuanbao_config, require_yuanbao_field, verify_yuanbao_credentials,
};
-use super::email::{build_email_config, persist_email_config, verify_email_credentials};
-use super::shared::{credential_provider, parse_allowed_users, parse_optional_bool};
/// Initiate a channel connection.
///
@@ -68,7 +70,7 @@ pub async fn connect_channel(
let app_secret = require_yuanbao_field(creds_map, "app_secret")?;
let base = config.channels_config.yuanbao.clone().unwrap_or_default();
let effective = build_effective_yuanbao_config(base, creds_map, app_key);
- verify_yuanbao_credentials(&effective, &app_secret).await?;
+ verify_yuanbao_credentials(reqwest::Client::new(), &effective, &app_secret).await?;
prebuilt_yuanbao_config = Some(effective);
}
diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/email.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/email.rs
index b6a58e38bd..abff24b65a 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/connect/email.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/email.rs
@@ -1,148 +1,12 @@
-//! Building, verifying, and persisting the email (IMAP/SMTP) channel config.
-
-use serde_json::Value;
-
-use crate::channels::email_channel::{EmailChannel, EmailConfig};
+//! Persisting the email (IMAP/SMTP) channel config.
+//!
+//! Building the config from the connect form and verifying the IMAP login live
+//! in `tinychannels` (`controllers::build_email_config`,
+//! `providers::verify_email_credentials`); writing it to `config.toml` without
+//! the secret is this host's policy.
+
+use crate::channels::email_channel::EmailConfig;
use crate::config::Config;
-use tinychannels_bus::traits::Channel as _;
-
-use super::shared::parse_optional_bool;
-
-/// Read a required non-empty string credential field.
-fn require_cred_str(creds: &serde_json::Map<String, Value>, key: &str) -> Result<String, String> {
- creds
- .get(key)
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .ok_or_else(|| format!("missing required field: {key}"))
-}
-
-/// Read an optional non-empty string credential field.
-fn optional_cred_str(creds: &serde_json::Map<String, Value>, key: &str) -> Option<String> {
- creds
- .get(key)
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
-}
-
-/// Parse a `u16` port from a string/number credential field, falling back to
-/// `default` when the field is absent or blank. Non-numeric values are a hard
-/// error so a typo surfaces at connect time rather than silently reverting.
-pub(crate) fn parse_port_field(
- creds: &serde_json::Map<String, Value>,
- key: &str,
- default: u16,
-) -> Result<u16, String> {
- // Port 0 is the OS "any" sentinel — never a valid mailbox port — so reject it
- // up front rather than letting it fail later with a generic connect error.
- let invalid = || format!("invalid {key}: must be a port number 1-65535");
- match creds.get(key) {
- Some(Value::Number(n)) => n
- .as_u64()
- .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
- .map(|v| v as u16)
- .ok_or_else(invalid),
- Some(Value::String(s)) => {
- let trimmed = s.trim();
- if trimmed.is_empty() {
- Ok(default)
- } else {
- match trimmed.parse::<u16>() {
- Ok(0) | Err(_) => Err(invalid()),
- Ok(port) => Ok(port),
- }
- }
- }
- None | Some(Value::Null) => Ok(default),
- _ => Err(invalid()),
- }
-}
-
-/// Parse the email `allowed_senders` allowlist from a comma/newline-separated
-/// credential field. Unlike [`parse_allowed_users`](super::shared::parse_allowed_users),
-/// this preserves a leading `@` (the domain-match syntax `@example.com` the
-/// email channel relies on) and does not force lowercase beyond what the
-/// channel already does at match time. An absent field defaults to `["*"]`
-/// (allow any) so a freshly-connected mailbox actually receives — the channel
-/// treats an *empty* list as deny-all.
-pub(crate) fn parse_email_senders(value: Option<&Value>) -> Vec<String> {
- let raw = match value {
- Some(Value::String(s)) => s.clone(),
- Some(Value::Array(items)) => items
- .iter()
- .filter_map(|v| v.as_str())
- .collect::<Vec<_>>()
- .join(","),
- _ => return vec!["*".to_string()],
- };
-
- let mut out: Vec<String> = Vec::new();
- for part in raw.split([',', '\n', '\r']) {
- let trimmed = part.trim();
- if trimmed.is_empty() {
- continue;
- }
- if !out.iter().any(|e| e.eq_ignore_ascii_case(trimmed)) {
- out.push(trimmed.to_string());
- }
- }
- if out.is_empty() {
- out.push("*".to_string());
- }
- out
-}
-
-/// Build an [`EmailConfig`] from the connect form's credential map, filling
-/// sensible defaults (ports 993/465, TLS on, folder INBOX, `from_address` =
-/// username, allowlist = `*`). Field keys map 1:1 to the `email` channel
-/// definition. Reuses `existing` only for the IDLE timeout so an advanced
-/// hand-set value survives a UI reconnect.
-pub(super) fn build_email_config(
- creds: &serde_json::Map<String, Value>,
- existing: Option<&EmailConfig>,
-) -> Result<EmailConfig, String> {
- let username = require_cred_str(creds, "username")?;
- let from_address = optional_cred_str(creds, "from_address").unwrap_or_else(|| username.clone());
- Ok(EmailConfig {
- imap_host: require_cred_str(creds, "imap_host")?,
- imap_port: parse_port_field(creds, "imap_port", 993)?,
- imap_folder: optional_cred_str(creds, "imap_folder").unwrap_or_else(|| "INBOX".to_string()),
- smtp_host: require_cred_str(creds, "smtp_host")?,
- smtp_port: parse_port_field(creds, "smtp_port", 465)?,
- smtp_tls: parse_optional_bool(creds.get("smtp_tls")).unwrap_or(true),
- username,
- password: require_cred_str(creds, "password")?,
- from_address,
- idle_timeout_secs: existing.map_or(1740, |c| c.idle_timeout_secs),
- allowed_senders: parse_email_senders(creds.get("allowed_senders")),
- })
-}
-
-/// Live-verify IMAP credentials by attempting a login. Runs before persistence
-/// so a wrong host/password fails fast in the UI instead of silently wedging
-/// the listener on the next core restart.
-pub(super) async fn verify_email_credentials(cfg: &EmailConfig) -> Result<(), String> {
- // The probe dials IMAP + logs in over the network on the connect/test RPC
- // path, so bound it: a blackholed host or stalled TLS handshake must not
- // hang the UI. `health_check` has its own inner budget; this is a hard outer
- // cap that also distinguishes a timeout from an auth failure for the user.
- let probe = EmailChannel::new(cfg.clone());
- match tokio::time::timeout(std::time::Duration::from_secs(20), probe.health_check()).await {
- Ok(true) => Ok(()),
- Ok(false) => Err(
- "IMAP connection failed — check the host, port, email address, and app password"
- .to_string(),
- ),
- Err(_) => Err(format!(
- "IMAP connection to {} timed out — check the host and port",
- cfg.imap_host
- )),
- }
-}
/// Persist an already-built + verified [`EmailConfig`] into
/// `channels_config.email` so the supervised IMAP/SMTP listener picks it up on
diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rs
index f0f833a1ad..bac44e204e 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rs
@@ -4,7 +4,7 @@ use serde_json::Value;
pub(crate) use tinychannels::controllers::{
channel_config_connected, channel_credential_provider as credential_provider,
- parse_allowed_users,
+ parse_allowed_users, parse_optional_bool,
};
/// Merge a channel's live supervised-listener health into its credential/config
@@ -34,19 +34,3 @@ pub(crate) fn merge_listener_health(
_ => (presence_connected, None),
}
}
-
-pub(super) fn parse_optional_bool(value: Option<&Value>) -> Option<bool> {
- match value {
- Some(Value::Bool(b)) => Some(*b),
- Some(Value::Number(n)) => n.as_i64().map(|v| v != 0),
- Some(Value::String(s)) => {
- let normalized = s.trim().to_ascii_lowercase();
- match normalized.as_str() {
- "1" | "true" | "yes" | "on" => Some(true),
- "0" | "false" | "no" | "off" => Some(false),
- _ => None,
- }
- }
- _ => None,
- }
-}
diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/test_channel.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/test_channel.rs
index ac422b53a8..4d8f258265 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/connect/test_channel.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/test_channel.rs
@@ -7,7 +7,8 @@ use crate::core::Outcome;
use super::super::super::definitions::{find_channel_definition, ChannelAuthMode};
use super::super::types::ChannelTestResult;
-use super::email::{build_email_config, verify_email_credentials};
+use tinychannels::controllers::build_email_config;
+use tinychannels::providers::verify_email_credentials;
/// Test a channel connection without persisting credentials.
pub async fn test_channel(
diff --git a/crates/openhuman-core/src/channels/controllers/ops/mod.rs b/crates/openhuman-core/src/channels/controllers/ops/mod.rs
index e8b603e60f..7e86c66711 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/mod.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/mod.rs
@@ -4,7 +4,6 @@ mod connect;
mod discord;
mod messaging;
mod types;
-mod yuanbao;
// Re-export types needed by tests.
#[cfg(test)]