Skip to main content

agentmux_srv/server/
browser_signin.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` `signin`: an agent signs in with a saved sign-in, and the person
5//! says yes (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §5.3).
6//!
7//! The agent names its pane and, when the page could take more than one, the
8//! entry. Only a `login` of the tab's profile saved for exactly the site of a
9//! sign-in form the page shows now can be used. The person is asked in the
10//! Vault's own prompt, a window modal outside every pane, which no `UI` click
11//! reaches: "Allow once", "Always for <agent> on <site>", or "Deny". Under an
12//! "Always" the pane shows "<agent> is signing in to <site> [Stop]" for 5 seconds
13//! first. The host types it as for the person's own choice (§5.3); the agent is
14//! told only which entry was used and on which site, never a value.
15
16use std::collections::HashMap;
17use std::sync::LazyLock;
18use std::time::Duration;
19
20use axum::extract::State;
21use axum::http::StatusCode;
22use axum::response::{IntoResponse, Response};
23use axum::Json;
24use parking_lot::Mutex;
25use serde::Deserialize;
26use serde_json::{json, Value};
27use tokio::sync::oneshot;
28
29use crate::backend::vault::signins::{self, PERSONAL};
30use crate::backend::vault::uses::{self, Ended, UseRequest};
31use agentmux_common::api_types::UiAutomationAuth;
32
33use super::browser_actions::{note, How, Kind};
34use super::ui_handlers::{err_response, target_block_id};
35use super::AppState;
36
37/// The block meta key of the "is signing in" notice.
38pub(crate) const PENDING_META_KEY: &str = "browser:signin_pending";
39/// How long the person has to answer.
40const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
41/// How long the notice shows before a sign-in under a grant is typed.
42const NOTICE: Duration = Duration::from_secs(5);
43/// What an agent is told when it names a login it may use for the page that the person hasn't shared with it.
44pub(crate) const NOT_SHARED: &str = "that sign-in isn't shared with this agent's browser profile, so nothing was typed: ask the person for it with Vault share (the entry and a reason), and they decide";
45/// What a container agent is told when its tab would use Personal's sign-ins (an Incognito tab uses them).
46pub(crate) const NO_PERSONAL: &str = "a container agent is offered none of the person's Personal sign-ins, in an Incognito tab or any other, so nothing was typed: sign in from a tab of your own browser profile (open the pane without a profile) with a login the person shared with you, which you can ask for with Vault share (the entry and a reason)";
47/// What the agent is told when another sign-in's notice shows on the pane.
48pub(crate) const BUSY: &str = "another sign-in is showing its notice on this pane: nothing was typed; try again when it is done";
49
50/// The notices showing, by id: the pane and what stops the sign-in.
51static PENDING: LazyLock<Mutex<HashMap<String, (String, oneshot::Sender<()>)>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
52
53#[derive(Debug, Deserialize)]
54pub(crate) struct SigninRequest {
55    auth: UiAutomationAuth,
56    #[serde(default)]
57    pane: Option<String>,
58    /// The saved sign-in to use; needed only when the page could take more than one.
59    #[serde(default)]
60    entry: Option<String>,
61    /// Why the agent signs in: one line of 8 to 300 characters, required.
62    #[serde(default)]
63    reason: Option<String>,
64}
65
66/// The key "Always for <agent> on this site" is kept under, in the grants table
67/// web forms use for sites: `signin:<agent>|<profile>|<origin>`, which can't be a
68/// site's origin. It names the site and profile the person approved, so an entry
69/// whose site or profile is edited afterwards is asked about again.
70pub(crate) fn grant_key(agent: &str, profile: &str, origin: &str) -> String {
71    format!("signin:{agent}|{profile}|{origin}")
72}
73
74/// [`grant_key`] for a login shared with the agent: it is used in the agent's own profile (`profile`), and the key also
75/// names the profile the login is saved for (`saved`), so a login whose profile is edited afterwards is asked about again
76/// whatever writes it (A6).
77pub(crate) fn shared_grant_key(uid: &str, profile: &str, origin: &str, saved: &str) -> String {
78    grant_key(uid, profile, &format!("{origin}|{saved}"))
79}
80
81/// Which of the sign-ins the page can take, `(entry, origin, user)`, is meant.
82pub(crate) fn choose(found: Vec<(String, String, String)>, entry: Option<&str>) -> Result<(String, String, String), String> {
83    if let Some(want) = entry {
84        return found.into_iter().find(|(e, _, _)| e == want).ok_or_else(|| {
85            "that sign-in isn't saved for a sign-in form on this page in this tab's profile, so nothing was typed (a sign-in for a site's HTTP prompt is never typed into a form: the browser answers that prompt itself when the site asks, from an entry saved for this tab's profile or one the person shared with you, which you can ask for with Vault share, and you are told what became of it)".to_string()
86        });
87    }
88    match found.len() {
89        0 => Err("no saved sign-in in this tab's profile fits a sign-in form on this page now; the person can save one when they sign in".to_string()),
90        1 => Ok(found.into_iter().next().unwrap_or_default()),
91        _ => {
92            let listed: Vec<String> = found.iter().map(|(e, o, u)| format!("{e} ({} on {o})", signins::mask(u))).collect();
93            Err(format!("{} saved sign-ins fit this page; name one with entry: {}", found.len(), listed.join(", ")))
94        }
95    }
96}
97
98fn noted(state: &AppState, block_id: &str, agent: &str, how: How) {
99    note(block_id, agent, Kind::Fill).detail("a saved sign-in from the Vault").how(how).record(state);
100}
101
102fn set_notice(state: &AppState, block_id: &str, value: Value) {
103    let mut meta = crate::backend::obj::MetaMapType::new();
104    meta.insert(PENDING_META_KEY.to_string(), value);
105    if let Err(e) = super::http_shell::broadcast_meta_update(state, block_id, &meta) {
106        tracing::warn!(error = %e, "[signin] couldn't show the pane's sign-in notice");
107    }
108}
109
110/// A notice showing: dropped when the sign-in goes ahead or is stopped, and also
111/// when the agent's call is cancelled while it shows, so no notice is left on the
112/// pane with a Stop that stops nothing.
113struct Showing<'a> {
114    state: &'a AppState,
115    block_id: &'a str,
116    id: String,
117}
118
119impl Drop for Showing<'_> {
120    fn drop(&mut self) {
121        PENDING.lock().remove(&self.id);
122        set_notice(self.state, self.block_id, Value::Null);
123    }
124}
125
126/// Show "<agent> is signing in" for [`NOTICE`] (`kind` `signin`, or `account`
127/// for an agent making a new account, for as long as `wait` says): `Some(true)`
128/// when nobody stopped it, `None` when another notice already shows on the pane.
129/// One at a time per pane, so what waits to be typed is always what the pane
130/// shows and its Stop stops.
131pub(crate) async fn notice(state: &AppState, block_id: &str, agent: &str, origin: &str, user: &str, kind: &str, wait: Duration) -> Option<bool> {
132    let id = uuid::Uuid::new_v4().to_string();
133    let (tx, rx) = oneshot::channel();
134    {
135        let mut pending = PENDING.lock();
136        if pending.values().any(|(b, _)| b == block_id) {
137            return None;
138        }
139        pending.insert(id.clone(), (block_id.to_string(), tx));
140    }
141    let _showing = Showing { state, block_id, id: id.clone() };
142    let deadline = agentmux_common::time::now_ms() + wait.as_millis() as i64;
143    set_notice(state, block_id, json!({ "id": id, "agent": agent, "origin": origin, "user": signins::mask(user), "kind": kind, "deadline_ms": deadline }));
144    Some(tokio::select! {
145        _ = tokio::time::sleep(wait) => true,
146        _ = rx => false,
147    })
148}
149
150/// Clear the notice saved with every pane that has none showing. Called when
151/// the host registers: a notice lives in memory, and one saved with a pane from
152/// before srv restarted would show a Stop that stops nothing.
153pub(crate) fn reset_notices(state: &AppState) {
154    let live: std::collections::BTreeSet<String> = PENDING.lock().values().map(|(b, _)| b.clone()).collect();
155    super::browser_signin_offer::clear_stale(state, PENDING_META_KEY, &live, "[signin]");
156}
157
158/// The id of the notice showing on pane `block_id`, for the tests' stand-in for the person's Stop.
159#[cfg(test)]
160pub(crate) fn pending_id(block_id: &str) -> Option<String> {
161    PENDING.lock().iter().find(|(_, (b, _))| b == block_id).map(|(id, _)| id.clone())
162}
163
164/// The person pressed [Stop] on notice `id` of pane `block_id`.
165pub(crate) fn stop(block_id: &str, id: &str) -> Result<(), String> {
166    let mut pending = PENDING.lock();
167    match pending.get(id) {
168        Some((b, _)) if b == block_id => {}
169        _ => return Err("that sign-in has already been typed or stopped".to_string()),
170    }
171    if let Some((_, tx)) = pending.remove(id) {
172        let _ = tx.send(());
173    }
174    Ok(())
175}
176
177/// The saved sign-in an agent means: its entry, label, site and user name, the
178/// tab's profile, and the entry's `created_at`, which tells it from one deleted
179/// and made again with the same id while the person was asked.
180struct Chosen {
181    /// Whom an "Always" for this entry names: the agent's permanent uid when the login was reached through a share
182    /// (A10), otherwise the agent.
183    grant_agent: String,
184    shared: bool,
185    /// The profile the entry is saved for (what a share's "Always" is also bound to).
186    saved: String,
187    entry: String,
188    label: String,
189    origin: String,
190    user: String,
191    profile: String,
192    created: i64,
193    /// The entry's `updated_at` as the person is shown it: a request is bound to the entry as it was then, so one edited
194    /// while it waits (a share removed and made again included) types nothing and is given no Always (A7).
195    updated: i64,
196}
197
198/// Why nothing was typed: the outcome kept in the Vault's activity, how the
199/// pane's log shows it, and what the agent is told.
200struct Refusal {
201    outcome: &'static str,
202    how: How,
203    code: StatusCode,
204    why: String,
205}
206
207/// The tab's profile, and whether it is Incognito, which keeps no sign-ins of
208/// its own: it may use Personal's, asked each time.
209pub(crate) fn profile_of(block: &crate::backend::obj::Block) -> (String, bool) {
210    let identity = block.meta.get(super::browser_identity::IDENTITY_META_KEY).and_then(Value::as_str);
211    match signins::profile_for_tab(identity) {
212        Some(p) => (p, false),
213        None => (PERSONAL.to_string(), true),
214    }
215}
216
217/// The agent's permanent uid when `profile` is its own browser profile: the one tab where a login shared with it is
218/// offered (A4). `None` for a tab of any other profile and for an agent that isn't running.
219pub(crate) fn own_uid(state: &AppState, agent: &str, profile: &str) -> Option<String> {
220    let uid = state.reactive_handler.get_agent(agent).and_then(|a| a.uid)?;
221    (profile == format!("profile:{}", crate::backend::browser_profiles_store::agent_profile_id(&uid))).then_some(uid)
222}
223
224/// The saved sign-in of `profile` the agent means, among those that fit a
225/// sign-in form the page shows now.
226async fn chosen(state: &AppState, block_id: &str, agent: &str, profile: &str, entry: Option<&str>) -> Result<Chosen, Response> {
227    let origins = super::browser_signin_fill::form_origins(block_id);
228    let own = own_uid(state, agent, profile);
229    let (store, p, who, uid, seen) = (state.identity_store.clone(), profile.to_string(), agent.to_string(), own.clone(), origins.clone());
230    let found = match tokio::task::spawn_blocking(move || signins::offered_for_agent(&store, &p, &seen, &who, uid.as_deref())).await {
231        Ok(Ok(f)) => f,
232        Ok(Err(e)) => return Err(err_response(StatusCode::INTERNAL_SERVER_ERROR, e)),
233        Err(e) => return Err(err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
234    };
235    match choose(found, entry) {
236        Ok((entry, origin, user)) => {
237            let row = state.identity_store.vault_get(&entry).ok().flatten();
238            let saved = row.as_ref().and_then(|r| crate::backend::vault::signins::fields_of(r).get(signins::PROFILE).cloned()).unwrap_or_default();
239            let shared = row.is_some() && saved != profile;
240            let (label, created, updated) = row.map(|r| (r.label, r.created_at, r.updated_at)).unwrap_or_default();
241            let grant_agent = if shared { own.clone().unwrap_or_else(|| agent.to_string()) } else { agent.to_string() };
242            Ok(Chosen { grant_agent, shared, saved, entry, label, origin, user, profile: profile.to_string(), created, updated })
243        }
244        Err(e) => {
245            // A login the agent may use for this page, which the person hasn't shared with it: say how to ask (A8).
246            let e = match (&own, entry) {
247                (Some(uid), Some(want)) if signins::unshared_for(&state.identity_store, want, &origins, agent, uid) => NOT_SHARED.to_string(),
248                _ => e,
249            };
250            noted(state, block_id, agent, How::Refused(e.clone()));
251            Err(err_response(StatusCode::BAD_REQUEST, e))
252        }
253    }
254}
255
256/// The person's yes: under an "Always" the notice shows and nobody pressed
257/// Stop; otherwise they answered the Vault's prompt, in `agent_pane`. True when
258/// nobody answered it and it went ahead.
259async fn approve(state: &AppState, block_id: &str, agent: &str, agent_pane: String, c: &Chosen, incognito: bool, reason: &str) -> Result<bool, Refusal> {
260    let key = if c.shared { shared_grant_key(&c.grant_agent, &c.profile, &c.origin, &c.saved) } else { grant_key(&c.grant_agent, &c.profile, &c.origin) };
261    let (store, e, k) = (state.identity_store.clone(), c.entry.clone(), key.clone());
262    let granted = !incognito && tokio::task::spawn_blocking(move || store.vault_grant_check(&e, &k).unwrap_or(false)).await.unwrap_or(false);
263    if !granted {
264        return ask(state, block_id, agent, agent_pane, c, incognito, key, reason).await;
265    }
266    match notice(state, block_id, agent, &c.origin, &c.user, "signin", NOTICE).await {
267        Some(true) => Ok(false),
268        Some(false) => Err(Refusal { outcome: "stopped", how: How::Declined, code: StatusCode::FORBIDDEN, why: "the person stopped the sign-in: nothing was typed".to_string() }),
269        None => Err(Refusal { outcome: "another was showing", how: How::Refused(BUSY.to_string()), code: StatusCode::CONFLICT, why: BUSY.to_string() }),
270    }
271}
272
273/// The agent may still act on the pane after the wait: the person had time to
274/// pause it or take it over, and nothing is typed then. The call's auth was
275/// checked when it came; the wait can outlast its freshness window.
276pub(crate) fn still_allowed(state: &AppState, agent_id: &str, pane: Option<&str>, block_id: &str) -> Result<(), (StatusCode, String)> {
277    match super::ui_handlers::target_for(state, block_id, agent_id, pane) {
278        Ok(b) if b == block_id => Ok(()),
279        Ok(_) => Err((StatusCode::CONFLICT, "the pane changed while the sign-in waited: nothing was typed".to_string())),
280        Err((code, e)) => Err((code, format!("{e}; nothing was typed"))),
281    }
282}
283
284fn use_request(agent: &str, agent_pane: String, c: &Chosen, incognito: bool, agent_reason: &str) -> UseRequest {
285    UseRequest {
286        agent_reason: agent_reason.to_string(),
287        id: uuid::Uuid::new_v4().to_string(),
288        agent: agent.to_string(),
289        block_id: agent_pane,
290        entry_id: c.entry.clone(),
291        entry_label: c.label.clone(),
292        what: "sign-in".to_string(),
293        origin: c.origin.clone(),
294        field: signins::mask(&c.user),
295        offer_always: !incognito,
296        reason: if incognito {
297            "this is an Incognito tab, which keeps no sign-ins: Personal's is used, and asked for each time".to_string()
298        } else if c.shared {
299            format!("the person shared this login with {agent}; it hasn't signed in with it on this site before")
300        } else {
301            format!("{agent} hasn't signed in with this before")
302        },
303        kind: "login".to_string(),
304        signin: true,
305        shared: c.shared,
306        requested_ms: agentmux_common::time::now_ms_u64(),
307        ..Default::default()
308    }
309}
310
311/// Ask the person in the Vault's prompt; an "Always" is kept under `key`. True
312/// when nobody answered and it went ahead.
313async fn ask(state: &AppState, block_id: &str, agent: &str, agent_pane: String, c: &Chosen, incognito: bool, key: String, reason: &str) -> Result<bool, Refusal> {
314    let headline = format!("{agent} wants to sign in to {}", c.origin);
315    let (ended, _) = super::vault_ask::ask(state, block_id, use_request(agent, agent_pane, c, incognito, reason), ANSWER_WAIT, &headline).await;
316    match ended {
317        Ended::Once => Ok(false),
318        Ended::WentAhead => Ok(true),
319        Ended::Always => {
320            // Only for the entry the person was shown, not one made again with its id.
321            let (store, e, created, updated) = (state.identity_store.clone(), c.entry.clone(), c.created, c.updated);
322            let _ = tokio::task::spawn_blocking(move || store.vault_grant_add_unchanged(&e, &key, agentmux_common::time::now_ms(), created, updated)).await;
323            Ok(false)
324        }
325        ended => {
326            let (how, code) = if ended == Ended::NoAnswer { (How::TimedOut, StatusCode::REQUEST_TIMEOUT) } else { (How::Declined, StatusCode::FORBIDDEN) };
327            Err(Refusal { outcome: ended.outcome(), how, code, why: ended.refusal("nothing was typed") })
328        }
329    }
330}
331
332/// `POST /api/v1/ui/browser/signin`.
333pub(crate) async fn handle_signin(
334    State(state): State<AppState>,
335    caller: Option<axum::Extension<crate::server::caller::Caller>>,
336    Json(req): Json<SigninRequest>,
337) -> Response {
338    let reason = match crate::backend::vault::history::require_reason(req.reason.as_deref()) {
339        Ok(r) => r,
340        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
341    };
342    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
343        Ok(b) => b,
344        Err((code, e)) => return err_response(code, e),
345    };
346    let agent = req.auth.agent_id.chars().take(64).collect::<String>();
347    let Some(block) = state.mstore.get::<crate::backend::obj::Block>(&block_id).ok().flatten() else {
348        return err_response(StatusCode::NOT_FOUND, format!("no pane {block_id}"));
349    };
350    let (profile, incognito) = profile_of(&block);
351    let agent_pane = super::vault_ask::agent_pane(&state, caller.as_deref(), &req.auth);
352    if profile == PERSONAL && super::browser_identity::in_container(&state, &agent_pane) {
353        noted(&state, &block_id, &agent, How::Refused(NO_PERSONAL.to_string()));
354        return err_response(StatusCode::FORBIDDEN, NO_PERSONAL.to_string());
355    }
356    let c = match chosen(&state, &block_id, &agent, &profile, req.entry.as_deref()).await {
357        Ok(c) => c,
358        Err(response) => return response,
359    };
360    tracing::info!(agent = %agent, block_id = %block_id, entry = %c.entry, "[signin] an agent asked to sign in");
361    let went_ahead = match approve(&state, &block_id, &agent, agent_pane, &c, incognito, &reason).await {
362        Ok(w) => w,
363        Err(r) => {
364            crate::backend::vault::record_line(
365                &state.identity_store,
366                crate::backend::vault::Line { entry_id: &c.entry, label: &c.label, actor: &agent, action: signins::SIGNED_IN, target: &c.origin, outcome: r.outcome, reason: &reason },
367            );
368            super::vault_handlers::publish(&state);
369            noted(&state, &block_id, &agent, r.how);
370            return err_response(r.code, r.why);
371        }
372    };
373    if let Err((code, e)) = still_allowed(&state, &req.auth.agent_id, req.pane.as_deref(), &block_id) {
374        noted(&state, &block_id, &agent, How::Refused(e.clone()));
375        return err_response(code, e);
376    }
377
378    match super::browser_signin_fill::fill_as(&state, &block_id, &c.entry, &profile, &agent, Some((c.created, c.origin.clone(), c.updated)), &reason, false).await {
379        Ok((site, username_filled)) => {
380            noted(&state, &block_id, &agent, How::Allowed);
381            let mut out = json!({ "filled": true, "entry": c.entry, "site": site, "username_filled": username_filled, "password": "[secret: hidden]" });
382            if went_ahead {
383                out["approval"] = json!(uses::WENT_AHEAD);
384            }
385            (StatusCode::OK, Json(json!({ "ok": true, "data": out }))).into_response()
386        }
387        Err(e) => {
388            noted(&state, &block_id, &agent, How::Refused(e.clone()));
389            err_response(StatusCode::BAD_GATEWAY, e)
390        }
391    }
392}
393
394/// The person removed the share of login `id` with `who` (an agent's uid, or `*`): a card still waiting on a sign-in asked
395/// through that share, from an agent the entry no longer names, is answered No, so it does not stay up for a sign-in that
396/// cannot go ahead (A7). Any other card on the entry (an ordinary sign-in, another agent's share) is left for the person.
397/// A card answered or timing out later types nothing either if the entry changed: it was bound to the entry as shown.
398pub(crate) fn share_removed(state: &AppState, id: &str, who: &str) {
399    let Ok(Some(row)) = state.identity_store.vault_get(id) else { return };
400    let fields = signins::fields_of(&row);
401    for u in uses::uses().list().into_iter().filter(|u| u.signin && u.shared && u.entry_id == id) {
402        let uid = state.reactive_handler.get_agent(&u.agent).and_then(|a| a.uid).unwrap_or_default();
403        let removed = who == crate::backend::vault::shares::EVERY_AGENT || uid == who;
404        if removed && !crate::backend::vault::shares::names(&fields, &uid) {
405            uses::uses().answer(&u.id, uses::UseAnswer::of(uses::Decision::Deny));
406        }
407    }
408}
409
410/// `browser.signin_stop`, from the window only: the person's [Stop] on the notice.
411pub(crate) fn register(engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>) {
412    use crate::backend::rpc_types::{CommandBrowserSigninStopData, COMMAND_BROWSER_SIGNIN_STOP};
413    engine.register_typed(COMMAND_BROWSER_SIGNIN_STOP, move |req: CommandBrowserSigninStopData, ctx| async move {
414        ctx.operator_only("only the person stops an agent's sign-in")?;
415        stop(&req.block_id, &req.id)
416    });
417}
418
419#[cfg(test)]
420#[path = "browser_signin_tests.rs"]
421mod tests;