Skip to main content

agentmux_srv/server/
signin_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sign-in link as a notice on the machine the person is using (spec
5//! `SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md` ยง4.4, D6). An agent that started a sign-in on
6//! another machine (`identity.signin.start`) asks its own srv to put the link in front of the
7//! person: here if a window of this AgentMux is focused, else on the LAN peer that reports one.
8//! The notice is a persistent toast with an Open action; the credentials stay on the machine that
9//! is signing in, and only the link travels.
10
11use 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
21/// Where a provider's sign-in page may be: an Open action opens a link a remote machine named,
22/// so only the provider's own https pages (and their subdomains) are accepted.
23fn 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
40/// A machine name fit for a toast: printable, short.
41fn clean_machine(machine: &str) -> String {
42    machine.chars().filter(|c| !c.is_control()).take(40).collect::<String>().trim().to_string()
43}
44
45/// A one-time code fit for a toast: letters, digits and dashes, short.
46fn 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
51/// Whether a window of this AgentMux is focused now.
52pub(crate) fn window_focused(state: &AppState) -> bool {
53    crate::backend::notify::router::get(&state.broker).is_some_and(|r| r.app_focused())
54}
55
56/// Show the link as a notice on this machine.
57pub(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
66/// Put the link in front of the person: on this machine when a window here is focused, else on the
67/// first LAN peer that has one focused and lets this agent ask (an approved install), else here.
68/// Returns the machine that got it.
69pub(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    /// The machine that is signing in.
98    machine: String,
99    url: String,
100    #[serde(default)]
101    code: Option<String>,
102}
103
104/// `POST /api/v1/agent/identity/signin/notice`: backs `Identity` `signin` with a `host`, once the
105/// other machine has returned the link.
106pub(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;