Skip to main content

agentmux_srv/server/remote_ops/
signin_ops.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `identity.signin.*` (spec ยง4.4, D6): signing in an account on this machine for an agent
5//! somewhere else. The provider's own login runs here, under an account directory srv mints; the
6//! caller gets the link and the session, and later the account's id and email, and never a token
7//! or a path. The caller shows the link where the person is reading, and the credentials stay on
8//! this machine. A session belongs to the caller that started it, as the transport proved it
9//! (`slug@machine`): another caller can't read it or finish it.
10
11use std::collections::HashMap;
12use std::sync::Mutex;
13use std::time::{Duration, Instant};
14
15use serde::Deserialize;
16use serde_json::{json, Value};
17
18use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
19use crate::identity::auth_session::AuthSessionStatus;
20use crate::server::identity_handlers::{start_provider_auth, StartProviderAuthReq};
21
22/// How long `start` waits for the CLI to print its link, and `finish` for the sign-in to end.
23const LINK_WAIT: Duration = Duration::from_secs(15);
24const FINISH_WAIT: Duration = Duration::from_secs(20);
25const POLL_EVERY: Duration = Duration::from_millis(400);
26/// Sessions this machine remembers a caller for; the oldest go first.
27const MAX_OWNED: usize = 64;
28
29/// Who started each session (and in which session manager), so only that caller reads or finishes it.
30static OWNERS: Mutex<Vec<(usize, String, String)>> = Mutex::new(Vec::new());
31
32/// Identifies the session manager that holds a session: one per srv.
33fn manager_key(state: &AppState) -> usize {
34    std::sync::Arc::as_ptr(&state.auth_session_manager) as usize
35}
36
37/// A provider this op can sign in. Its login command is a frontend catalog entry, so the ones
38/// whose command is known here are listed. A person who signs in on another machine can't be sent
39/// back to a callback on this one, so a provider whose browser flow ends in one (codex) uses the
40/// device code flow instead: a link and a one-time code, nothing to hand back.
41struct Login {
42    id: &'static str,
43    login: &'static [&'static str],
44    check: &'static [&'static str],
45    requires_tty: bool,
46    /// The sign-in is waiting for the person once a one-time code is shown, not just a link.
47    device_code: bool,
48}
49
50const LOGINS: &[Login] = &[
51    Login { id: "claude", login: &["auth", "login"], check: &["auth", "status", "--json"], requires_tty: true, device_code: false },
52    Login { id: "codex", login: &["login", "--device-auth"], check: &["login", "status"], requires_tty: false, device_code: true },
53];
54
55fn login_for(provider: &str) -> Option<&'static Login> {
56    LOGINS.iter().find(|l| l.id == provider)
57}
58
59const DEFAULT_PROVIDER: &str = "claude";
60
61#[derive(Debug, Deserialize)]
62struct StartParams {
63    #[serde(default)]
64    provider: Option<String>,
65    /// Sign an account in again (refresh its tokens in place) instead of adding a new one.
66    #[serde(default)]
67    account: Option<String>,
68}
69
70#[derive(Debug, Deserialize)]
71struct SessionParams {
72    session: String,
73    #[serde(default)]
74    code: Option<String>,
75}
76
77fn bad(message: impl Into<String>) -> RemoteRefusal {
78    RemoteRefusal::new("bad_params", message)
79}
80
81fn failed(message: impl Into<String>) -> RemoteRefusal {
82    RemoteRefusal::failed(message.into())
83}
84
85fn remember(state: &AppState, session: &str, actor: &str) {
86    let mut owners = OWNERS.lock().unwrap_or_else(|e| e.into_inner());
87    // Sessions srv has dropped (ended and swept) go first; only a full list of live ones evicts the oldest.
88    let key = manager_key(state);
89    owners.retain(|(k, s, _)| *k != key || state.auth_session_manager.poll_session(s).is_some());
90    if owners.iter().filter(|(k, ..)| *k == key).count() >= MAX_OWNED {
91        if let Some(oldest) = owners.iter().position(|(k, ..)| *k == key) {
92            owners.remove(oldest);
93        }
94    }
95    owners.push((key, session.to_string(), actor.to_string()));
96}
97
98fn owned_by(state: &AppState, session: &str, actor: &str) -> bool {
99    let key = manager_key(state);
100    let owners = OWNERS.lock().unwrap_or_else(|e| e.into_inner());
101    owners.iter().any(|(k, s, a)| *k == key && s == session && a == actor)
102}
103
104/// The session's state as the caller sees it. An account's id and email appear once it is signed in.
105fn view(session: &str, status: &AuthSessionStatus) -> Value {
106    match status {
107        AuthSessionStatus::Pending => json!({ "session": session, "state": "starting" }),
108        AuthSessionStatus::UrlAvailable { auth_url } => json!({ "session": session, "state": "waiting_for_person", "url": auth_url }),
109        AuthSessionStatus::CodeEmitted { device_code, verification_url } => {
110            json!({ "session": session, "state": "waiting_for_person", "url": verification_url, "device_code": device_code })
111        }
112        AuthSessionStatus::Success { email, account_id, .. } => json!({ "session": session, "state": "signed_in", "account_id": account_id, "email": email }),
113        AuthSessionStatus::Failed { error } => json!({ "session": session, "state": "failed", "error": error }),
114    }
115}
116
117/// Poll until `done` says stop or `wait` passes; the last status seen.
118async fn poll_until(state: &AppState, session: &str, wait: Duration, done: impl Fn(&AuthSessionStatus) -> bool) -> Result<AuthSessionStatus, RemoteRefusal> {
119    let deadline = Instant::now() + wait;
120    loop {
121        let snap = state.auth_session_manager.poll_session(session).ok_or_else(|| failed("that sign-in is gone (it ended or timed out); start another"))?;
122        if done(&snap.status) || Instant::now() >= deadline {
123            return Ok(snap.status);
124        }
125        tokio::time::sleep(POLL_EVERY).await;
126    }
127}
128
129/// Start signing in an account on this machine, and give back the link for the person.
130pub(super) async fn start(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
131    let p: StartParams = serde_json::from_value(params).map_err(|e| bad(format!("identity.signin.start: {e}")))?;
132    let provider = p.provider.as_deref().map(str::trim).filter(|s| !s.is_empty()).unwrap_or(DEFAULT_PROVIDER);
133    let Some(login) = login_for(provider) else {
134        let known: Vec<&str> = LOGINS.iter().map(|l| l.id).collect();
135        return Err(bad(format!("identity.signin.start: only {} can be signed in from another machine so far, not {provider}", known.join(" and "))));
136    };
137    let existing = p.account.unwrap_or_default().trim().to_string();
138    if !existing.is_empty() {
139        match state.id_store.identity_get(&existing) {
140            Ok(Some(a)) if a.provider == provider => {}
141            _ => return Err(bad(format!("identity.signin.start: {existing} isn't a {provider} account on this machine; leave account out to add a new one"))),
142        }
143    }
144    let cli = crate::server::cli_handlers::locate_provider_cli(provider)
145        .await
146        .ok_or_else(|| failed(format!("{provider} isn't installed on this machine; open a {provider} agent here once so AgentMux installs it")))?;
147    let req = StartProviderAuthReq {
148        provider_id: provider.to_string(),
149        into_bundle_id: None,
150        direct_account: true,
151        existing_account_id: existing,
152        cli_path: cli.path,
153        auth_login_args: login.login.iter().map(|a| a.to_string()).collect(),
154        auth_check_args: login.check.iter().map(|a| a.to_string()).collect(),
155        auth_env: HashMap::new(),
156        requires_tty: login.requires_tty,
157    };
158    let started = start_provider_auth(state, req);
159    let actor = caller.actor();
160    remember(state, &started.session_id, &actor);
161    tracing::info!(actor = %actor, provider, "remote identity.signin.start: started a sign-in");
162    let ready = |s: &AuthSessionStatus| match s {
163        AuthSessionStatus::Pending => false,
164        AuthSessionStatus::UrlAvailable { .. } => !login.device_code,
165        _ => true,
166    };
167    let status = poll_until(state, &started.session_id, LINK_WAIT, ready).await?;
168    Ok(view(&started.session_id, &status))
169}
170
171/// Show a sign-in link as a notice here, because the person is on this machine: `route` on the
172/// machine of the agent that asked sends it to the one that has a window focused.
173pub(super) async fn notice(state: &AppState, _caller: &RemoteCaller, params: Value) -> RemoteResult {
174    #[derive(Deserialize)]
175    struct Notice {
176        provider: String,
177        machine: String,
178        url: String,
179        #[serde(default)]
180        code: Option<String>,
181    }
182    let p: Notice = serde_json::from_value(params).map_err(|e| bad(format!("identity.signin.notice: {e}")))?;
183    crate::server::signin_notice::show_local(state, &p.provider, &p.machine, &p.url, p.code.as_deref()).map_err(bad)?;
184    Ok(json!({ "shown": true }))
185}
186
187/// Wait for the sign-in to end: the login finishes on its own once the person has authorized in a
188/// browser, or takes the code they were shown (`code`) when the browser can't finish it.
189pub(super) async fn finish(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
190    let p: SessionParams = serde_json::from_value(params).map_err(|e| bad(format!("identity.signin.finish: {e}")))?;
191    if !owned_by(state, &p.session, &caller.actor()) {
192        return Err(failed("no sign-in of yours with that session"));
193    }
194    if let Some(code) = p.code.as_deref().map(str::trim).filter(|c| !c.is_empty()) {
195        let provider = state.auth_session_manager.poll_session(&p.session).map(|s| s.provider_id);
196        if provider.as_deref().and_then(login_for).is_some_and(|l| l.device_code) {
197            return Err(bad("this sign-in shows the person a code to enter on the page; there is nothing to hand back, just wait for it to end"));
198        }
199        if !state.auth_session_manager.send_to_stdin(&p.session, code.to_string()).await {
200            return Err(failed("that sign-in isn't waiting for a code any more"));
201        }
202    }
203    let status = poll_until(state, &p.session, FINISH_WAIT, AuthSessionStatus::is_terminal).await?;
204    Ok(view(&p.session, &status))
205}
206
207#[cfg(test)]
208#[path = "signin_ops_tests.rs"]
209mod tests;