agentmux_srv/server/
signin_notice.rs1use axum::extract::{Extension, State};
12use axum::response::IntoResponse;
13use axum::Json;
14use serde::Deserialize;
15use serde_json::{json, Value};
16
17use super::*;
18
19pub use crate::backend::signin_link_event::SigninLinkEvent;
20
21fn allowed_hosts(provider: &str) -> &'static [&'static str] {
24 match provider {
25 "claude" => &["claude.com", "claude.ai", "anthropic.com"],
26 "codex" => &["openai.com", "chatgpt.com"],
27 _ => &[],
28 }
29}
30
31pub(crate) fn link_allowed(provider: &str, link: &str) -> bool {
32 let Ok(url) = url::Url::parse(link) else { return false };
33 if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() {
34 return false;
35 }
36 let Some(host) = url.host_str().map(str::to_ascii_lowercase) else { return false };
37 allowed_hosts(provider).iter().any(|h| host == *h || host.ends_with(&format!(".{h}")))
38}
39
40fn clean_machine(machine: &str) -> String {
42 machine.chars().filter(|c| !c.is_control()).take(40).collect::<String>().trim().to_string()
43}
44
45fn clean_code(code: Option<&str>) -> Option<String> {
47 let code = code?.trim();
48 (!code.is_empty() && code.len() <= 32 && code.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then(|| code.to_string())
49}
50
51pub(crate) fn window_focused(state: &AppState) -> bool {
53 crate::backend::notify::router::get(&state.broker).is_some_and(|r| r.app_focused())
54}
55
56pub(crate) fn show_local(state: &AppState, provider: &str, machine: &str, link: &str, code: Option<&str>) -> Result<(), String> {
58 if !link_allowed(provider, link) {
59 return Err(format!("not a {provider} sign-in link"));
60 }
61 let event = SigninLinkEvent { provider: provider.to_string(), machine: clean_machine(machine), url: link.to_string(), code: clean_code(code) };
62 state.broker.publish_event::<crate::backend::mps_events::SigninLink>(&event, vec![], 0);
63 Ok(())
64}
65
66pub(crate) async fn route(state: &AppState, slug: &str, provider: &str, machine: &str, link: &str, code: Option<&str>) -> Result<String, ApiError> {
70 if !link_allowed(provider, link) {
71 return Err(ApiError::bad_request(format!("not a {provider} sign-in link")));
72 }
73 if !window_focused(state) {
74 let mut peers: Vec<String> = state.lan_discovery.get_instances().iter().map(|p| p.hostname.trim().to_string()).filter(|h| !h.is_empty()).collect();
75 peers.sort();
76 peers.dedup();
77 for peer in peers {
78 let asked = super::remote_ops::send::call(state, slug, &peer, "app.activity", json!({}), "where is the person").await;
79 if asked.result["window_focused"].as_bool() != Some(true) {
80 continue;
81 }
82 let params = json!({ "provider": provider, "machine": machine, "url": link, "code": code });
83 let shown = super::remote_ops::send::call(state, slug, &peer, "identity.signin.notice", params, "show the sign-in link").await;
84 if shown.result["shown"].as_bool() == Some(true) {
85 return Ok(peer);
86 }
87 }
88 }
89 show_local(state, provider, machine, link, code)?;
90 Ok(state.hostname.clone())
91}
92
93#[derive(Deserialize)]
94pub(super) struct SigninNoticeRequest {
95 agent_id: String,
96 provider: String,
97 machine: String,
99 url: String,
100 #[serde(default)]
101 code: Option<String>,
102}
103
104pub(super) async fn handle_agent_signin_notice(
107 State(state): State<AppState>,
108 who: Option<Extension<caller::Caller>>,
109 Json(req): Json<SigninNoticeRequest>,
110) -> impl IntoResponse {
111 let (slug, _) = match actor::require_token_actor(&state, who.as_deref(), actor::ActorSite::IdentitySigninNotice, &req.agent_id).await {
112 Ok(who) => who,
113 Err(e) => return app_api_response::<Value>(Err(e)),
114 };
115 let shown_on = route(&state, &slug, &req.provider, &req.machine, &req.url, req.code.as_deref()).await;
116 app_api_response(shown_on.map(|machine| json!({ "shown_on": machine })))
117}
118
119#[cfg(test)]
120#[path = "signin_notice_tests.rs"]
121mod tests;