mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-26 23:50:17 +00:00
* feat: Move debug log truncation from agent loop to REPL channel Full tool output now flows through StatusUpdate so the web gateway gets untruncated content. The REPL channel truncates at display time (200 chars for tool results, thinking, and status messages). Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Flatten WASM tool schemas and fix host HTTP runtime contention LLMs can't reliably follow oneOf + const discriminator patterns in JSON Schema, causing tools like Google Calendar to receive malformed params (e.g., {"operation":"list_events","data":{"calendarId":"primary"}} instead of {"action":"list_events","calendar_id":"primary"}). Replace all 9 WASM tool schemas with flat action enum + top-level properties. The serde #[serde(tag = "action")] deserialization works identically. Also fixes WASM host HTTP requests (channels and tools) stalling during startup by replacing Handle::current().block_on() with a dedicated single-threaded runtime per request, avoiding I/O driver contention. Reduces verbose LLM debug logging (full request/response payloads) and changes tower_http default from debug to warn. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: Built-in OAuth credentials and combined Google scopes Add infrastructure for shipping default OAuth credentials with the binary, similar to how gcloud/rclone bake in their client_id. Credentials are set at compile time via IRONCLAW_GOOGLE_CLIENT_ID / IRONCLAW_GOOGLE_CLIENT_SECRET env vars, or can be hardcoded in src/cli/oauth_defaults.rs. The fallback chain is: capabilities file > runtime env var > built-in defaults. Also, when authing any Google tool, scopes from ALL installed Google tools are now combined into a single OAuth request (they all share the same google_oauth_token secret). One login covers Gmail, Calendar, Drive, etc. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: Ship default Google OAuth credentials for zero-config auth Google Desktop App credentials are not secret (per Google's own docs). Hardcode them so `ironclaw tool auth <google-tool>` works out of the box without requiring users to register their own OAuth app. Credentials can still be overridden at compile time (IRONCLAW_GOOGLE_CLIENT_ID) or runtime (GOOGLE_OAUTH_CLIENT_ID). Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Consistent OAuth callback port and polished landing page - Use fixed port 9876 instead of scanning 9876-9886 (one redirect URI to register in provider OAuth apps, deterministic behavior) - Replace broken unicode checkmark with SVG icons (charset was missing, rendered as mojibake) - Dark themed landing page with proper card layout for both success and error states - Add charset=utf-8 to Content-Type headers Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: Unify OAuth callback server across all auth flows All three OAuth flows (WASM tool auth, MCP server auth, NEAR AI login) now share the same code from cli::oauth_defaults: - Fixed port 9876 (one redirect URI to register per provider) - Shared landing page HTML (dark card with SVG icons, proper charset) - Parameterized wait_for_callback(listener, path, param, display_name) Removes ~120 lines of duplicated callback/HTML code. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Support for oauth token refresh * refactor: Replace bootstrap.json with ~/.ironclaw/.env for DATABASE_URL Kill the 4-field BootstrapConfig JSON file. Only DATABASE_URL actually needs disk persistence (chicken-and-egg before DB connect). The other three fields are now derived: pool_size defaults to 10 via env var, secrets master key is auto-detected (env then keychain probe), and onboard_completed is inferred from DATABASE_URL presence. The new format is a standard .env file loaded via dotenvy early in main, so DATABASE_URL is available as a regular env var everywhere. Handles three upgrade paths: - Clean start: wizard writes .env, reload after wizard completes - Returning user: .env loaded at startup, business as usual - Legacy upgrade: bootstrap.json auto-migrated to .env on first run Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Address PR review findings - Fix UTF-8 panic in truncate_for_preview (byte-slice on char boundary) - Cap WASM guest timeout_ms at 5 minutes to prevent resource exhaustion - Fix localhost detection in requires_auth() to avoid substring matches (e.g. "notlocalhost.com" no longer matches) - Fix query param injection to insert before URL fragment - Fix extract_host_from_url for IPv6 bracket notation - Remove misleading schema defaults: Slack limit, Slides insertion_index, Docs index (per-action defaults documented in descriptions instead) Co-Authored-By: Claude Opus 4.6 <[email protected]> * style: Fix cargo fmt formatting Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: IPv6 loopback support for OAuth listener and localhost detection - bind_callback_listener: try [::1] first, fall back to 127.0.0.1, so OAuth redirects work on systems where localhost resolves to ::1 - is_localhost_url: replace manual string parsing with url::Url for correct handling of IPv6 brackets, ports, userinfo, etc. - Add url crate as direct dependency (already a transitive dep) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Address PR review feedback on runtime reuse, onboard check, and OAuth binding - Remove session file check from check_onboard_needed(); DATABASE_URL is sufficient - Detect AddrInUse on IPv6 bind and fail immediately instead of falling through to IPv4 - Reuse dedicated tokio runtime across HTTP calls in both tool and channel WASM wrappers Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: HTML-escape provider name in OAuth landing page, simplify Slack limit description - Add html_escape() to prevent XSS in landing_html() where provider_name was interpolated directly into HTML (defense-in-depth, source is trusted but escaping costs nothing) - Remove per-action default numbers from Slack limit field description to avoid confusing LLMs with conflicting defaults Addresses review feedback from zmanian on PR #42. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Save all bootstrap fields from wizard, fix config module comment - Wizard now saves secrets_master_key_source and database_pool_size to bootstrap.json (was only saving database_url and onboard_completed, which broke secrets after fresh onboard since SecretsConfig::resolve reads key source from bootstrap) - Update config.rs module doc to reflect bootstrap.json priority chain instead of the removed ~/.ironclaw/.env approach Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: Replace BootstrapConfig with .env-based bootstrap DATABASE_URL is the only setting that needs disk persistence before the database is available. Instead of a custom bootstrap.json with 4 fields, use a standard ~/.ironclaw/.env file loaded via dotenvy. - Remove BootstrapConfig struct entirely - Restore ironclaw_env_path(), load_ironclaw_env(), save_database_url() - SecretsConfig::resolve() now auto-detects (env var then keychain probe) instead of reading a saved source from bootstrap.json - DatabaseConfig::resolve() reads DATABASE_URL from env only (dotenvy loads ~/.ironclaw/.env into the environment early in startup) - check_onboard_needed() is now sync (just checks env vars) - Wizard save_and_summarize() works for both postgres and libsql backends - One-time migration from bootstrap.json to .env preserved Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Ensure load_ironclaw_env() runs in all Config paths, fix .env priority - Config::from_env() and Config::from_db() now call load_ironclaw_env() internally (after dotenvy::dotenv()), so CLI commands like `memory` and `config` correctly load DATABASE_URL from ~/.ironclaw/.env - Fix load order: standard ./.env first (higher priority), then ~/.ironclaw/.env, matching the documented priority chain - Collapse nested if/if-let into let-chains (clippy::collapsible_if) in oauth_defaults.rs, tool.rs, and secrets/store.rs - Fix rename_to_migrated to take &Path instead of &PathBuf Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Address PR review comments (quoting, SSRF, error mapping) - Quote DATABASE_URL in .env writes so `#` in passwords isn't treated as a dotenv comment (e.g., `DATABASE_URL="postgres://..."`) - Add SSRF defenses to refresh_oauth_token(): require HTTPS, reject private/loopback IPs (with DNS resolution), disable redirects. token_url comes from tool capabilities JSON, so a malicious tool could otherwise exfiltrate refresh tokens. - Fix IPv4 bind error mapping: only map AddrInUse to PortInUse, use generic Io variant for other bind failures Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
312 lines
11 KiB
Rust
312 lines
11 KiB
Rust
//! Telegram User-Mode WASM Tool for IronClaw.
|
|
//!
|
|
//! Provides Telegram integration operating from the **user's personal account**,
|
|
//! not a bot. This tool sends encrypted MTProto messages directly to Telegram's
|
|
//! data centers via HTTPS POST, using the grammers crate for the Sans-IO
|
|
//! protocol implementation.
|
|
//!
|
|
//! # Architecture
|
|
//!
|
|
//! ```text
|
|
//! WASM Tool ──MTProto/HTTPS──► Telegram DC (*.web.telegram.org/apiw)
|
|
//! ```
|
|
//!
|
|
//! No Docker container, no middleware. The tool performs the DH key exchange,
|
|
//! encrypts requests with the auth key, and POSTs raw ciphertext to Telegram's
|
|
//! web transport endpoint.
|
|
//!
|
|
//! # Session Persistence
|
|
//!
|
|
//! Session state (auth key, salt, DC, login status) is stored in the workspace
|
|
//! at `telegram/session.json`. The agent should save updated session data after
|
|
//! auth actions using `memory_write`.
|
|
//!
|
|
//! # Prerequisites
|
|
//!
|
|
//! 1. Get Telegram API credentials from https://my.telegram.org/apps
|
|
//! 2. Store them: `ironclaw secret set telegram_api_id <id>`
|
|
//! `ironclaw secret set telegram_api_hash <hash>`
|
|
//! 3. Use the `login` action with your phone number
|
|
//!
|
|
//! # Authentication Flow
|
|
//!
|
|
//! 1. Call `login` with your phone number
|
|
//! - Generates an auth key (DH exchange with Telegram DC)
|
|
//! - Sends verification code to your phone
|
|
//! - Returns session data and phone_code_hash
|
|
//! 2. Call `submit_auth_code` with the verification code
|
|
//! 3. Call `submit_2fa_password` if you have 2FA enabled
|
|
//! 4. After each auth step, save the returned `session` JSON to
|
|
//! `telegram/session.json` via `memory_write`
|
|
//!
|
|
//! # Privacy
|
|
//!
|
|
//! - `get_messages` does NOT mark messages as read
|
|
//! - Messages are read via `messages.getHistory`, not `getUpdates`
|
|
|
|
mod api;
|
|
mod auth;
|
|
mod session;
|
|
mod transport;
|
|
mod types;
|
|
|
|
use session::Session;
|
|
use types::TelegramAction;
|
|
|
|
wit_bindgen::generate!({
|
|
world: "sandboxed-tool",
|
|
path: "../../wit/tool.wit",
|
|
});
|
|
|
|
struct TelegramTool;
|
|
|
|
impl exports::near::agent::tool::Guest for TelegramTool {
|
|
fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response {
|
|
match execute_inner(&req.params) {
|
|
Ok(result) => exports::near::agent::tool::Response {
|
|
output: Some(result),
|
|
error: None,
|
|
},
|
|
Err(e) => exports::near::agent::tool::Response {
|
|
output: None,
|
|
error: Some(e),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn schema() -> String {
|
|
SCHEMA.to_string()
|
|
}
|
|
|
|
fn description() -> String {
|
|
"Telegram user-mode integration for reading and sending messages from the user's \
|
|
personal account. Supports contacts, chat history, message search, sending, \
|
|
forwarding, and deletion. Communicates directly with Telegram's servers via \
|
|
encrypted MTProto over HTTPS (no Docker/TDLight needed). Does NOT mark messages \
|
|
as read when reading history. Use the 'login' action to authenticate with your \
|
|
phone number. Session state is persisted in the workspace at telegram/session.json."
|
|
.to_string()
|
|
}
|
|
}
|
|
|
|
fn execute_inner(params: &str) -> Result<String, String> {
|
|
let action: TelegramAction =
|
|
serde_json::from_str(params).map_err(|e| format!("Invalid parameters: {e}"))?;
|
|
|
|
near::agent::host::log(
|
|
near::agent::host::LogLevel::Info,
|
|
&format!("Executing Telegram action: {action:?}"),
|
|
);
|
|
|
|
match action {
|
|
TelegramAction::Login { phone_number } => execute_login(&phone_number),
|
|
TelegramAction::SubmitAuthCode { code } => execute_submit_code(&code),
|
|
TelegramAction::Submit2faPassword { password } => execute_submit_2fa(&password),
|
|
TelegramAction::GetMe => with_session(api::get_me),
|
|
TelegramAction::GetContacts => with_session(api::get_contacts),
|
|
TelegramAction::GetChats { limit } => with_session(|s| api::get_chats(s, limit)),
|
|
TelegramAction::GetMessages {
|
|
chat_id,
|
|
limit,
|
|
from_message_id,
|
|
} => with_session(|s| api::get_messages(s, chat_id, limit, from_message_id)),
|
|
TelegramAction::SendMessage { chat_id, text } => {
|
|
with_session(|s| api::send_message(s, chat_id, &text))
|
|
}
|
|
TelegramAction::ForwardMessage {
|
|
from_chat_id,
|
|
to_chat_id,
|
|
message_ids,
|
|
} => with_session(|s| api::forward_message(s, from_chat_id, to_chat_id, message_ids)),
|
|
TelegramAction::DeleteMessage {
|
|
message_ids,
|
|
revoke,
|
|
} => with_session(|s| api::delete_messages(s, message_ids, revoke)),
|
|
TelegramAction::SearchMessages {
|
|
query,
|
|
chat_id,
|
|
limit,
|
|
} => with_session(|s| api::search_messages(s, &query, chat_id, limit)),
|
|
TelegramAction::GetUpdates => with_session(api::get_updates),
|
|
}
|
|
}
|
|
|
|
/// Load session from workspace, verify it's initialized and logged in, then run the action.
|
|
fn with_session(f: impl FnOnce(&Session) -> Result<String, String>) -> Result<String, String> {
|
|
let session = session::load_session().ok_or(
|
|
"No session found. Use the 'login' action first, then save the returned session \
|
|
to telegram/session.json via memory_write."
|
|
.to_string(),
|
|
)?;
|
|
|
|
if !session.initialized {
|
|
return Err("Session exists but auth key not generated. Run 'login' again.".into());
|
|
}
|
|
if !session.logged_in {
|
|
return Err("Session exists but not logged in. Complete the login flow \
|
|
(submit_auth_code / submit_2fa_password)."
|
|
.into());
|
|
}
|
|
|
|
f(&session)
|
|
}
|
|
|
|
/// Login flow: create session, generate auth key, send verification code.
|
|
fn execute_login(phone_number: &str) -> Result<String, String> {
|
|
let api_id = get_api_id()?;
|
|
let api_hash = get_api_hash()?;
|
|
|
|
// Default to DC2 (Venus) as it's commonly assigned to new sessions
|
|
let dc_id = 2u8;
|
|
|
|
let mut session = Session::new(api_id, api_hash, dc_id);
|
|
session.phone_number = Some(phone_number.to_string());
|
|
|
|
// Step 1: DH auth key exchange
|
|
near::agent::host::log(
|
|
near::agent::host::LogLevel::Info,
|
|
"Starting DH auth key exchange with Telegram DC...",
|
|
);
|
|
auth::generate_auth_key(&mut session)?;
|
|
|
|
// Step 2: send verification code
|
|
near::agent::host::log(
|
|
near::agent::host::LogLevel::Info,
|
|
"Auth key generated. Sending verification code...",
|
|
);
|
|
let result = api::send_code(&mut session)?;
|
|
|
|
// Return session + result so agent can persist it
|
|
let session_json = session::session_to_json(&session)?;
|
|
Ok(format!(
|
|
"{{\"result\":{result},\"session\":{session_json},\"instructions\":\
|
|
\"Save the 'session' object to telegram/session.json using memory_write.\"}}"
|
|
))
|
|
}
|
|
|
|
/// Submit auth code, return updated session.
|
|
fn execute_submit_code(code: &str) -> Result<String, String> {
|
|
let mut session =
|
|
session::load_session().ok_or("No session found. Use 'login' first.".to_string())?;
|
|
|
|
let result = api::sign_in(&mut session, code)?;
|
|
let session_json = session::session_to_json(&session)?;
|
|
|
|
Ok(format!(
|
|
"{{\"result\":{result},\"session\":{session_json},\"instructions\":\
|
|
\"Save the 'session' object to telegram/session.json using memory_write.\"}}"
|
|
))
|
|
}
|
|
|
|
/// Submit 2FA password, return updated session.
|
|
fn execute_submit_2fa(password: &str) -> Result<String, String> {
|
|
let mut session =
|
|
session::load_session().ok_or("No session found. Use 'login' first.".to_string())?;
|
|
|
|
let result = api::check_password(&mut session, password)?;
|
|
let session_json = session::session_to_json(&session)?;
|
|
|
|
Ok(format!(
|
|
"{{\"result\":{result},\"session\":{session_json},\"instructions\":\
|
|
\"Save the 'session' object to telegram/session.json using memory_write.\"}}"
|
|
))
|
|
}
|
|
|
|
/// Read api_id from params or check secret existence.
|
|
fn get_api_id() -> Result<i32, String> {
|
|
// The secret store holds the value but WASM can't read it directly.
|
|
// The api_id is injected via env or must be in capabilities.
|
|
// For now, read from workspace config if available.
|
|
if let Some(val) = near::agent::host::workspace_read("telegram/api_id") {
|
|
return val
|
|
.trim()
|
|
.parse::<i32>()
|
|
.map_err(|e| format!("invalid api_id in workspace: {e}"));
|
|
}
|
|
Err(
|
|
"Telegram API ID not found. Store it in workspace at telegram/api_id \
|
|
(just the numeric value) using memory_write."
|
|
.into(),
|
|
)
|
|
}
|
|
|
|
fn get_api_hash() -> Result<String, String> {
|
|
if let Some(val) = near::agent::host::workspace_read("telegram/api_hash") {
|
|
let trimmed = val.trim().to_string();
|
|
if trimmed.is_empty() {
|
|
return Err("telegram/api_hash is empty".into());
|
|
}
|
|
return Ok(trimmed);
|
|
}
|
|
Err(
|
|
"Telegram API hash not found. Store it in workspace at telegram/api_hash \
|
|
using memory_write."
|
|
.into(),
|
|
)
|
|
}
|
|
|
|
const SCHEMA: &str = r#"{
|
|
"type": "object",
|
|
"required": ["action"],
|
|
"properties": {
|
|
"action": {
|
|
"type": "string",
|
|
"enum": ["login", "submit_auth_code", "submit_2fa_password", "get_me", "get_contacts", "get_chats", "get_messages", "send_message", "forward_message", "delete_message", "search_messages", "get_updates"],
|
|
"description": "The Telegram operation to perform"
|
|
},
|
|
"phone_number": {
|
|
"type": "string",
|
|
"description": "Phone number in international format (e.g., '+1234567890'). Required for: login"
|
|
},
|
|
"code": {
|
|
"type": "string",
|
|
"description": "Verification code received via SMS or Telegram. Required for: submit_auth_code"
|
|
},
|
|
"password": {
|
|
"type": "string",
|
|
"description": "Two-factor authentication password. Required for: submit_2fa_password"
|
|
},
|
|
"chat_id": {
|
|
"type": "integer",
|
|
"description": "Chat ID (negative for groups/channels). Required for: get_messages, send_message. Optional for: search_messages"
|
|
},
|
|
"limit": {
|
|
"type": "integer",
|
|
"description": "Maximum number of results (default: 20). Used by: get_chats, get_messages, search_messages",
|
|
"default": 20
|
|
},
|
|
"from_message_id": {
|
|
"type": "integer",
|
|
"description": "Start from this message ID for pagination. Used by: get_messages"
|
|
},
|
|
"text": {
|
|
"type": "string",
|
|
"description": "Message text. Required for: send_message"
|
|
},
|
|
"from_chat_id": {
|
|
"type": "integer",
|
|
"description": "Source chat ID. Required for: forward_message"
|
|
},
|
|
"to_chat_id": {
|
|
"type": "integer",
|
|
"description": "Destination chat ID. Required for: forward_message"
|
|
},
|
|
"message_ids": {
|
|
"type": "array",
|
|
"items": { "type": "integer" },
|
|
"description": "Message IDs. Required for: forward_message, delete_message"
|
|
},
|
|
"revoke": {
|
|
"type": "boolean",
|
|
"description": "Also delete for other participants (default: false). Used by: delete_message",
|
|
"default": false
|
|
},
|
|
"query": {
|
|
"type": "string",
|
|
"description": "Search query. Required for: search_messages"
|
|
}
|
|
}
|
|
}"#;
|
|
|
|
export!(TelegramTool);
|