Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmux-tui/crates/cmux-imessage/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
//! - [`Reader::threads`]: conversations (1:1 and group chats), newest activity first.
//! - [`Reader::messages`]: one conversation's messages, oldest first, paged backwards by rowid.
//! - [`Reader::since`]: messages newer than a rowid watermark, for live updates.
//! - [`send::send`]: sends a message to an existing chat through Messages.app (Automation).

mod date;
mod error;
mod model;
mod reader;
pub mod send;
mod typedstream;

pub use date::apple_to_unix_ms;
Expand Down
200 changes: 200 additions & 0 deletions cmux-tui/crates/cmux-imessage/src/send.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
//! Sending a message through Messages.app, the mirror's second step (opt-in, like the reads).
//!
//! The send runs `osascript` with a fixed AppleScript. The chat id and the text reach the script
//! only as `argv` items, never spliced into its source, so no text can change what the script
//! does. macOS asks Leo once for the Automation permission ("cmux wants to control Messages");
//! a refusal comes back as [`SendError::NotPermitted`].

use std::io::ErrorKind;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// The longest text one send takes, in bytes.
pub const MAX_TEXT_BYTES: usize = 20_000;
/// How long a send may run before the child is stopped. The first send can wait on the
/// Automation prompt, so this is generous.
pub const SEND_TIMEOUT: Duration = Duration::from_secs(120);

/// The script `osascript` runs, one `-e` per line. `item 1 of argv` is the chat guid,
/// `item 2 of argv` the text.
pub const SEND_SCRIPT: [&str; 7] = [
"on run argv",
"set chatGuid to item 1 of argv",
"set messageText to item 2 of argv",
"tell application \"Messages\"",
"send messageText to chat id chatGuid",
"end tell",
"end run",
];

/// AppleScript error: the user (or policy) refused Automation of Messages.
const ERR_NOT_AUTHORIZED: &str = "(-1743)";
/// AppleScript error: no chat with that id.
const ERR_NO_SUCH_OBJECT: &str = "(-1728)";

/// One message to send to an existing chat.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendRequest {
/// `chat.guid` of the thread (`iMessage;-;+15551234567`, `iMessage;+;chat123`, `SMS;-;...`).
pub chat_guid: String,
pub text: String,
}

/// Why a send did not go out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SendError {
EmptyText,
TextTooLong,
/// The chat guid is malformed, or Messages has no chat with it.
InvalidChat(String),
/// Automation of Messages is not allowed for cmux.
NotPermitted(String),
/// `osascript` is not available (not macOS).
Unsupported,
/// The send ran past [`SEND_TIMEOUT`] and was stopped.
TimedOut,
/// Messages or osascript reported another failure.
Failed(String),
}

impl SendError {
/// A stable, machine-readable code for the wire.
pub fn code(&self) -> &'static str {
match self {
Self::EmptyText => "empty_text",
Self::TextTooLong => "text_too_long",
Self::InvalidChat(_) => "invalid_chat",
Self::NotPermitted(_) => "not_permitted",
Self::Unsupported => "unsupported",
Self::TimedOut => "timed_out",
Self::Failed(_) => "failed",
}
}
}

impl std::fmt::Display for SendError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::EmptyText => write!(f, "messages send: the text is empty"),
Self::TextTooLong => write!(f, "messages send: the text is over {MAX_TEXT_BYTES} bytes"),
Self::InvalidChat(detail) => write!(f, "messages send: no such chat: {detail}"),
Self::NotPermitted(detail) => {
write!(f, "messages send: cmux may not control Messages (allow it under Automation): {detail}")
}
Self::Unsupported => write!(f, "messages send: osascript is not available"),
Self::TimedOut => write!(f, "messages send: timed out"),
Self::Failed(detail) => write!(f, "messages send: {detail}"),
}
}
}

impl std::error::Error for SendError {}

/// What a finished command reported.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandOutput {
pub success: bool,
pub stderr: String,
}

/// Runs a program; tests substitute a fake.
pub trait CommandRunner {
fn run(&self, program: &str, args: &[String]) -> std::io::Result<CommandOutput>;
}

/// Runs the program as a child process, stopping it after [`SEND_TIMEOUT`].
pub struct SystemRunner;

impl CommandRunner for SystemRunner {
fn run(&self, program: &str, args: &[String]) -> std::io::Result<CommandOutput> {
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()?;
let deadline = Instant::now() + SEND_TIMEOUT;
loop {
if let Some(status) = child.try_wait()? {
let mut stderr = String::new();
if let Some(mut pipe) = child.stderr.take() {
use std::io::Read;
let _ = pipe.read_to_string(&mut stderr);
}
return Ok(CommandOutput { success: status.success(), stderr });
}
if Instant::now() >= deadline {
// Our own child: stop it and reap it so nothing is left behind.
let _ = child.kill();
let _ = child.wait();
return Err(std::io::Error::new(ErrorKind::TimedOut, "osascript timed out"));
}
std::thread::sleep(Duration::from_millis(50));
}
}
}

/// Checks a request without sending it.
pub fn validate(request: &SendRequest) -> Result<(), SendError> {
if request.text.trim().is_empty() {
return Err(SendError::EmptyText);
}
if request.text.len() > MAX_TEXT_BYTES {
return Err(SendError::TextTooLong);
}
if request.text.contains('\0') {
return Err(SendError::Failed("the text contains a NUL byte".to_string()));
}
if !is_chat_guid(&request.chat_guid) {
return Err(SendError::InvalidChat(request.chat_guid.clone()));
}
Ok(())
}

/// The `osascript` arguments for a request: the script lines as `-e` options, then the chat
/// guid and the text as plain arguments (the script's `argv`).
pub fn osascript_args(request: &SendRequest) -> Vec<String> {
let mut args = Vec::with_capacity(SEND_SCRIPT.len() * 2 + 2);
for line in SEND_SCRIPT {
args.push("-e".to_string());
args.push(line.to_string());
}
args.push(request.chat_guid.clone());
args.push(request.text.clone());
args
}

/// Validates and sends one message through Messages.app.
pub fn send(request: &SendRequest, runner: &dyn CommandRunner) -> Result<(), SendError> {
validate(request)?;
let output = match runner.run("osascript", &osascript_args(request)) {
Ok(output) => output,
Err(error) if error.kind() == ErrorKind::NotFound => return Err(SendError::Unsupported),
Err(error) if error.kind() == ErrorKind::TimedOut => return Err(SendError::TimedOut),
Err(error) => return Err(SendError::Failed(error.to_string())),
};
if output.success {
return Ok(());
}
let detail = output.stderr.trim().to_string();
Err(if detail.contains(ERR_NOT_AUTHORIZED) {
SendError::NotPermitted(detail)
} else if detail.contains(ERR_NO_SUCH_OBJECT) {
SendError::InvalidChat(detail)
} else {
SendError::Failed(detail)
})
}

/// `service;-;handle` (1:1) or `service;+;room` (group), with no control characters, and not
/// starting with `-` (so `osascript` never reads it as an option).
fn is_chat_guid(guid: &str) -> bool {
if guid.is_empty() || guid.len() > 512 || guid.starts_with('-') || guid.chars().any(char::is_control) {
return false;
}
let mut parts = guid.splitn(3, ';');
let (Some(service), Some(kind), Some(id)) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
!service.is_empty() && (kind == "-" || kind == "+") && !id.is_empty()
}
95 changes: 95 additions & 0 deletions cmux-tui/crates/cmux-imessage/tests/send.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//! Sending through Messages.app: validation, the osascript call shape and error mapping, with
//! a fake runner (no Messages.app, no osascript).

use std::cell::RefCell;

use cmux_imessage::send::{
CommandOutput, CommandRunner, MAX_TEXT_BYTES, SEND_SCRIPT, SendError, SendRequest, osascript_args, send,
validate,
};

struct FakeRunner {
result: std::io::Result<CommandOutput>,
calls: RefCell<Vec<(String, Vec<String>)>>,
}

impl FakeRunner {
fn ok() -> Self {
Self::with(Ok(CommandOutput { success: true, stderr: String::new() }))
}
fn failing(stderr: &str) -> Self {
Self::with(Ok(CommandOutput { success: false, stderr: stderr.to_string() }))
}
fn with(result: std::io::Result<CommandOutput>) -> Self {
Self { result, calls: RefCell::new(Vec::new()) }
}
}

impl CommandRunner for FakeRunner {
fn run(&self, program: &str, args: &[String]) -> std::io::Result<CommandOutput> {
self.calls.borrow_mut().push((program.to_string(), args.to_vec()));
match &self.result {
Ok(output) => Ok(output.clone()),
Err(error) => Err(std::io::Error::new(error.kind(), error.to_string())),
}
}
}

fn request(guid: &str, text: &str) -> SendRequest {
SendRequest { chat_guid: guid.to_string(), text: text.to_string() }
}

#[test]
fn text_reaches_osascript_only_as_an_argument() {
let hostile = "\" & (do shell script \"touch /tmp/pwned\") & \"\nend tell";
let args = osascript_args(&request("iMessage;-;+15550001111", hostile));
let script: Vec<&str> = args.iter().skip(1).step_by(2).take(SEND_SCRIPT.len()).map(String::as_str).collect();
assert_eq!(script, SEND_SCRIPT.to_vec(), "the script is fixed");
assert!(args.iter().take(SEND_SCRIPT.len() * 2).step_by(2).all(|flag| flag == "-e"));
assert_eq!(args[args.len() - 2], "iMessage;-;+15550001111");
assert_eq!(args[args.len() - 1], hostile, "the text is passed verbatim as argv");
assert!(SEND_SCRIPT.iter().all(|line| !line.contains("shell")));
}

#[test]
fn validation_refuses_empty_long_and_malformed_requests() {
assert_eq!(validate(&request("iMessage;-;+15550001111", " \n")), Err(SendError::EmptyText));
let long = "x".repeat(MAX_TEXT_BYTES + 1);
assert_eq!(validate(&request("iMessage;-;+15550001111", &long)), Err(SendError::TextTooLong));
for bad in ["", "-e;-;x", "iMessage", "iMessage;x;id", "iMessage;-;", ";-;id", "iMessage;-;a\nb"] {
assert_eq!(validate(&request(bad, "hi")).map_err(|e| e.code()), Err("invalid_chat"), "{bad:?}");
}
assert_eq!(validate(&request("iMessage;-;+15550001111", "hi")), Ok(()));
assert_eq!(validate(&request("iMessage;+;chat123456", "hi")), Ok(()));
assert_eq!(validate(&request("SMS;-;+15550001111", "hi")), Ok(()));
}

#[test]
fn a_successful_send_runs_osascript_once() {
let runner = FakeRunner::ok();
assert_eq!(send(&request("iMessage;+;chat1", "hello"), &runner), Ok(()));
let calls = runner.calls.borrow();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].0, "osascript");
assert_eq!(calls[0].1.last().map(String::as_str), Some("hello"));
}

#[test]
fn an_invalid_request_never_runs_osascript() {
let runner = FakeRunner::ok();
assert_eq!(send(&request("iMessage;-;+1", ""), &runner), Err(SendError::EmptyText));
assert!(runner.calls.borrow().is_empty());
}

#[test]
fn osascript_failures_map_to_codes() {
let denied = "execution error: Not authorized to send Apple events to Messages. (-1743)";
assert_eq!(send(&request("iMessage;-;+1", "hi"), &FakeRunner::failing(denied)).map_err(|e| e.code()), Err("not_permitted"));
let missing = "execution error: Messages got an error: Can’t get chat id \"x\". (-1728)";
assert_eq!(send(&request("iMessage;-;+1", "hi"), &FakeRunner::failing(missing)).map_err(|e| e.code()), Err("invalid_chat"));
assert_eq!(send(&request("iMessage;-;+1", "hi"), &FakeRunner::failing("boom")).map_err(|e| e.code()), Err("failed"));
let absent = FakeRunner::with(Err(std::io::Error::new(std::io::ErrorKind::NotFound, "no osascript")));
assert_eq!(send(&request("iMessage;-;+1", "hi"), &absent), Err(SendError::Unsupported));
let slow = FakeRunner::with(Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "slow")));
assert_eq!(send(&request("iMessage;-;+1", "hi"), &slow), Err(SendError::TimedOut));
}