1use std::io::IsTerminal;
18use std::time::Duration;
19
20use crate::config::{CliArgs, SrvCommand};
21use crate::server::local_proof;
22
23const STEP_LIMIT: Duration = Duration::from_secs(60);
25const POLL: Duration = Duration::from_millis(500);
26
27pub(crate) async fn exit_if_requested() {
29 let Ok(cli) = <CliArgs as clap::Parser>::try_parse_from(std::env::args_os()) else { return };
30 if matches!(cli.command, Some(SrvCommand::ProbeKeychain)) {
31 use crate::identity::secret_store::KeychainProbe;
32 let line = match crate::identity::secret_store::probe_keychain(Duration::from_secs(8)) {
33 KeychainProbe::Works => "works".to_string(),
34 KeychainProbe::Absent(why) => format!("absent: {why}"),
35 KeychainProbe::NoAnswer => "no-answer".to_string(),
36 KeychainProbe::RoundTripFailed(why) => format!("failed: {why}"),
37 };
38 println!("{line}");
39 std::process::exit(if line == "works" { 0 } else { 1 });
40 }
41 let (name, port, key_file, print, origin) = match cli.command {
42 Some(SrvCommand::Open { port, key_file, print, origin }) => ("open", port, key_file, print, origin),
43 Some(SrvCommand::Logout { port, key_file }) => ("logout", port, key_file, false, None),
44 Some(SrvCommand::Sessions { port, key_file }) => ("sessions", port, key_file, false, None),
45 Some(SrvCommand::Shutdown { port, key_file }) => ("shutdown", port, key_file, false, None),
46 _ => return,
47 };
48 let code = match prepare(cli.wavedata.as_deref(), port, key_file, origin) {
49 Ok(target) => match HttpServer::connect(&target).await {
50 Ok(server) if name == "logout" => logout(&server).await,
51 Ok(server) if name == "sessions" => sessions(&server).await,
52 Ok(server) if name == "shutdown" => shutdown(&server).await,
53 Ok(server) => run(&server, &target.origin, print, &mut Stdio).await,
54 Err(e) => {
55 eprintln!("agentmux-srv {name}: {e}");
56 3
57 }
58 },
59 Err(e) => {
60 eprintln!("agentmux-srv {name}: {e}");
61 3
62 }
63 };
64 std::process::exit(code);
65}
66
67async fn logout(server: &HttpServer) -> i32 {
69 match server.post("/auth/logout", serde_json::json!({})).await {
70 Ok(v) => {
71 let n = v["revoked"].as_u64().unwrap_or(0);
72 println!("Disconnected {n} browser{}.", if n == 1 { "" } else { "s" });
73 0
74 }
75 Err(e) => {
76 eprintln!("agentmux-srv logout: {e}");
77 3
78 }
79 }
80}
81
82async fn sessions(server: &HttpServer) -> i32 {
85 match server.post("/auth/sessions", serde_json::json!({})).await {
86 Ok(v) => match v["sessions"].as_u64() {
87 Some(n) => {
88 println!("{n}");
89 for c in v["confirms"].as_array().into_iter().flatten() {
90 println!("confirm {} {} {}", c["at_unix_ms"].as_u64().unwrap_or(0), c["session"].as_str().unwrap_or("?"), c["how"].as_str().unwrap_or("?"));
91 }
92 0
93 }
94 None => {
95 eprintln!("agentmux-srv sessions: the server's answer had no count");
96 3
97 }
98 },
99 Err(e) => {
100 eprintln!("agentmux-srv sessions: {e}");
101 3
102 }
103 }
104}
105
106async fn shutdown(server: &HttpServer) -> i32 {
108 match server.post("/auth/shutdown", serde_json::json!({})).await {
109 Ok(v) if v["stopping"].as_bool() == Some(true) => 0,
110 Ok(_) => {
111 eprintln!("agentmux-srv shutdown: the server did not say it is stopping");
112 3
113 }
114 Err(e) => {
115 eprintln!("agentmux-srv shutdown: {e}");
116 3
117 }
118 }
119}
120
121pub(crate) struct Target {
122 port: u16,
123 key: String,
124 origin: String,
126}
127
128pub(crate) fn prepare(wavedata: Option<&std::path::Path>, port: Option<u16>, key_file: Option<std::path::PathBuf>, origin: Option<String>) -> Result<Target, String> {
129 let declared = origin
131 .map(|o| crate::headless::normalize_public_origin(&o).map_err(|e| format!("--origin {o:?}: {e}")))
132 .transpose()?;
133 let path = match key_file {
134 Some(p) => p,
135 None => crate::headless::key_file_path(wavedata)?,
136 };
137 let key = crate::headless::read_key_file(&path).map_err(|e| format!("{e} (is the server started here, with this data folder?)"))?;
138 let port = match port {
139 Some(p) => p,
140 None => crate::headless::read_port_file(&path)?,
141 };
142 let origin = declared.unwrap_or_else(|| format!("http://127.0.0.1:{port}"));
143 Ok(Target { port, key, origin })
144}
145
146pub(crate) fn sign_in_url(origin: &str, code: &str) -> String {
148 format!("{}/auth/enter#{code}", origin.trim_end_matches('/'))
149}
150
151fn say_short_form<T: Terminal>(terminal: &mut T, origin: &str, code: &str) {
154 terminal.say(&format!("If the line wraps and will not copy, open {}/auth/enter in your own browser and paste this code there:", origin.trim_end_matches('/')));
155 terminal.say(code);
156}
157
158pub(crate) fn linux_has_screen(set: impl Fn(&str) -> bool) -> bool {
160 set("DISPLAY") || set("WAYLAND_DISPLAY") || set("BROWSER")
161}
162
163pub(crate) fn is_yes(answer: &str) -> bool {
165 matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
166}
167
168#[derive(Debug, PartialEq, Eq)]
170pub(crate) enum Entry {
171 Unused,
172 Entered(String),
173 Gone,
174}
175
176pub(crate) trait Server {
178 async fn mint_code(&self) -> Result<String, String>;
179 async fn entry(&self, code: &str) -> Result<Entry, String>;
180 async fn answer(&self, code: &str, accept: bool) -> Result<bool, String>;
182}
183
184pub(crate) trait Terminal {
186 fn is_terminal(&self) -> bool;
187 fn say(&mut self, line: &str);
188 async fn ask(&mut self, prompt: &str, limit: Duration) -> Option<String>;
190 async fn open_browser(&mut self, url: &str) -> bool;
193}
194
195pub(crate) async fn run<S: Server, T: Terminal>(server: &S, origin: &str, print: bool, terminal: &mut T) -> i32 {
196 if !terminal.is_terminal() {
197 terminal.say("agentmux-srv open: it needs a terminal, because you confirm the page there.");
198 return 3;
199 }
200 let code = match server.mint_code().await {
201 Ok(code) => code,
202 Err(e) => {
203 terminal.say(&format!("agentmux-srv open: {e}"));
204 return 3;
205 }
206 };
207 let url = sign_in_url(origin, &code);
208 if print {
209 terminal.say("Open this line in your own browser within a minute (it works once):");
210 terminal.say(&url);
211 say_short_form(terminal, origin, &code);
212 } else if terminal.open_browser(&url).await {
213 terminal.say("Opened your browser. Its page shows a short phrase of words. If no window appears, run `agentmux open --print` and open the line it prints in your own browser.");
214 } else {
215 terminal.say("Could not open a browser. Open this line in your own browser within a minute (it works once):");
216 terminal.say(&url);
217 say_short_form(terminal, origin, &code);
218 }
219
220 let started = tokio::time::Instant::now();
222 let phrase = loop {
223 match server.entry(&code).await {
224 Ok(Entry::Entered(phrase)) => break phrase,
225 Ok(Entry::Unused) if started.elapsed() < STEP_LIMIT => tokio::time::sleep(POLL).await,
226 Ok(Entry::Unused | Entry::Gone) => {
227 terminal.say("No browser reached the page in time. Run `agentmux open` again, or `agentmux open --print` to get a line to open in your own browser.");
228 return 1;
229 }
230 Err(e) => {
231 terminal.say(&format!("agentmux-srv open: {e}"));
232 return 3;
233 }
234 }
235 };
236
237 terminal.say("A browser has reached the page. Compare its phrase with the one below, and answer y only if they match: that keeps another user of this computer from opening your AgentMux.");
238 let prompt = format!("Phrase: \"{phrase}\". Does your browser page show the same? [y/N] ");
239 let answer = terminal.ask(&prompt, STEP_LIMIT).await;
240 let accept = answer.as_deref().is_some_and(is_yes);
241 if answer.is_none() {
242 let _ = server.answer(&code, false).await;
244 terminal.say("No answer came in time, so the page was not let in. Run `agentmux open` again.");
245 return 1;
246 }
247 match server.answer(&code, accept).await {
248 Ok(true) if accept => {
249 terminal.say("Done. The browser is open to AgentMux.");
250 0
251 }
252 Ok(true) => {
253 terminal.say("Discarded. If your browser did not show that phrase, someone else used the code. Run it again with --print and paste the line into your own browser.");
254 1
255 }
256 Ok(false) => {
257 terminal.say("That page was no longer waiting. Run it again.");
258 1
259 }
260 Err(e) => {
261 terminal.say(&format!("agentmux-srv open: {e}"));
262 3
263 }
264 }
265}
266
267pub(crate) struct HttpServer {
271 client: reqwest::Client,
272 base: String,
273 bound: String,
274 key: String,
275 origin: String,
276 channel: std::sync::Mutex<local_proof::Client>,
277}
278
279impl HttpServer {
280 pub(crate) async fn connect(target: &Target) -> Result<HttpServer, String> {
284 let client = crate::http_client::builder().no_proxy().timeout(Duration::from_secs(10)).build().map_err(|e| format!("could not build an http client: {e}"))?;
286 let bound = format!("127.0.0.1:{}", target.port);
287 let base = format!("http://{bound}");
288 let channel = Self::hello(&client, &base, &bound, &target.key, &target.origin).await?;
289 Ok(HttpServer { client, base, bound, key: target.key.clone(), origin: target.origin.clone(), channel: std::sync::Mutex::new(channel) })
290 }
291
292 async fn hello(client: &reqwest::Client, base: &str, bound: &str, key: &str, origin: &str) -> Result<local_proof::Client, String> {
294 let nonce = local_proof::new_nonce();
295 let resp = client
296 .post(format!("{base}/auth/hello"))
297 .json(&serde_json::json!({ "nonce": nonce }))
298 .send()
299 .await
300 .map_err(|_| format!("could not reach srv at {base} (is it running, and is that its web port?)"))?;
301 let not_this_server = || format!("the listener at {bound} did not prove it holds this key file's key, so nothing was sent to it: it is not the server this key file belongs to (check the port, or whether the server restarted)");
302 if !resp.status().is_success() {
303 return Err(not_this_server());
304 }
305 let v: serde_json::Value = resp.json().await.map_err(|_| not_this_server())?;
306 let text = |name: &str| v[name].as_str().map(str::to_string);
307 let (Some(channel), Some(srv_nonce), Some(declared), Some(proof)) = (text("channel"), text("nonce"), text("declared"), text("proof")) else {
308 return Err(not_this_server());
309 };
310 let channel = local_proof::Client::accept(key.as_bytes(), &nonce, bound, local_proof::HelloReply { channel, nonce: srv_nonce, declared, proof })
311 .map_err(|_| not_this_server())?;
312 if origin != base && channel.declared() != Some(origin) {
314 return Err(format!("--origin {origin} is not an address this server accepts (it accepts {base}{})", channel.declared().map(|d| format!(" and {d}")).unwrap_or_default()));
315 }
316 Ok(channel)
317 }
318
319 async fn send(&self, path: &str, bytes: &[u8]) -> Result<(reqwest::StatusCode, Option<String>, Vec<u8>, u64), String> {
321 let signed = self.channel.lock().unwrap_or_else(|e| e.into_inner()).sign("POST", path, bytes);
322 let resp = self
323 .client
324 .post(format!("{}{path}", self.base))
325 .header("content-type", "application/json")
326 .header(local_proof::CHANNEL_HEADER, &signed.channel)
327 .header(local_proof::SEQ_HEADER, signed.seq.to_string())
328 .header(local_proof::PROOF_HEADER, &signed.proof)
329 .body(bytes.to_vec())
330 .send()
331 .await
332 .map_err(|_| format!("could not reach srv at {} (is it running, and is that its web port?)", self.base))?;
333 let status = resp.status();
334 let proof = resp.headers().get(local_proof::PROOF_HEADER).and_then(|v| v.to_str().ok()).map(str::to_string);
335 let answer = resp.bytes().await.map_err(|_| "srv answered something unexpected".to_string())?;
336 Ok((status, proof, answer.to_vec(), signed.seq))
337 }
338
339 async fn post(&self, path: &str, body: serde_json::Value) -> Result<serde_json::Value, String> {
340 let bytes = serde_json::to_vec(&body).map_err(|e| e.to_string())?;
341 let mut begun_again = false;
342 loop {
343 let (status, proof, answer, seq) = self.send(path, &bytes).await?;
344 if !status.is_success() {
345 if seq == 1 && !begun_again {
348 begun_again = true;
349 let fresh = Self::hello(&self.client, &self.base, &self.bound, &self.key, &self.origin).await?;
350 *self.channel.lock().unwrap_or_else(|e| e.into_inner()) = fresh;
351 continue;
352 }
353 return Err("srv did not accept this (it may have restarted: run `agentmux-srv open` again)".into());
354 }
355 let proved = proof.is_some_and(|p| self.channel.lock().unwrap_or_else(|e| e.into_inner()).answer_ok(seq, status.as_u16(), &answer, &p));
356 if !proved {
357 return Err("srv's answer did not carry the proof of the key, so it was not used".into());
358 }
359 return serde_json::from_slice(&answer).map_err(|_| "srv answered something unexpected".to_string());
360 }
361 }
362}
363
364impl Server for HttpServer {
365 async fn mint_code(&self) -> Result<String, String> {
366 let v = self.post("/auth/code", serde_json::json!({})).await?;
367 v["code"].as_str().map(str::to_string).ok_or_else(|| "srv answered no code".to_string())
368 }
369
370 async fn entry(&self, code: &str) -> Result<Entry, String> {
371 let v = self.post("/auth/pending", serde_json::json!({ "code": code })).await?;
372 Ok(match (v["state"].as_str(), v["phrase"].as_str()) {
373 (Some("unused"), _) => Entry::Unused,
374 (Some("entered"), Some(phrase)) => Entry::Entered(phrase.to_string()),
375 _ => Entry::Gone,
376 })
377 }
378
379 async fn answer(&self, code: &str, accept: bool) -> Result<bool, String> {
380 let v = self.post("/auth/confirm", serde_json::json!({ "code": code, "accept": accept })).await?;
381 if let Some(refused) = v["refused"].as_str() {
382 return Err(refused.to_string());
383 }
384 Ok(v["found"].as_bool().unwrap_or(false))
385 }
386}
387
388struct Stdio;
389
390impl Terminal for Stdio {
391 fn is_terminal(&self) -> bool {
392 std::io::stdin().is_terminal() && std::io::stdout().is_terminal()
393 }
394
395 fn say(&mut self, line: &str) {
396 println!("{line}");
397 }
398
399 async fn ask(&mut self, prompt: &str, limit: Duration) -> Option<String> {
400 use std::io::Write;
401 print!("{prompt}");
402 let _ = std::io::stdout().flush();
403 let read = tokio::task::spawn_blocking(|| {
404 let mut line = String::new();
405 match std::io::stdin().read_line(&mut line) {
406 Ok(n) if n > 0 => Some(line),
407 _ => None,
408 }
409 });
410 tokio::select! {
411 line = read => line.ok().flatten(),
412 _ = tokio::time::sleep(limit) => None,
413 _ = tokio::signal::ctrl_c() => None,
414 }
415 }
416
417 async fn open_browser(&mut self, url: &str) -> bool {
418 use agentmux_common::win32::NoWindow;
419 use std::process::{Command, Stdio};
420 let mut cmd = if cfg!(target_os = "macos") {
421 let mut c = Command::new("open");
422 c.arg(url);
423 c
424 } else if cfg!(windows) {
425 let mut c = Command::new("rundll32");
426 c.args(["url.dll,FileProtocolHandler", url]);
427 c
428 } else {
429 if !linux_has_screen(|name| std::env::var_os(name).is_some_and(|v| !v.is_empty())) {
431 return false;
432 }
433 let mut c = Command::new("xdg-open");
434 c.arg(url);
435 c
436 };
437 crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
439 let Ok(mut child) = cmd.no_window().stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else { return false };
440 for _ in 0..8 {
443 match child.try_wait() {
444 Ok(Some(status)) => return status.success(),
445 Ok(None) => tokio::time::sleep(Duration::from_millis(250)).await,
446 Err(_) => return false,
447 }
448 }
449 true
450 }
451}
452
453#[cfg(test)]
454#[path = "open_cli_tests.rs"]
455mod tests;