Skip to main content

agentmux_srv/server/
browser_signin_fill.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Filling a saved sign-in by the person's own choice
5//! (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md ยง5.3).
6//!
7//! When a frame of a pane shows a sign-in form, the host says so
8//! (`credential.Form`); srv lists the `login` entries the tab's profile holds for
9//! exactly that frame's origin in the block meta [`SIGNINS_META_KEY`] (entry id,
10//! origin, masked user name: never a password). The pane shows a key button with
11//! their number, which opens a menu marked operator-only, so no agent's `UI`
12//! click reaches its items: the person choosing "Sign in as al***" is their
13//! approval. That sends `browser.signin_fill`, which only the window may, and
14//! srv hands the host the user name and password to type into that frame.
15//!
16//! Only `https`, or `http` on this computer: a sign-in is never typed into a
17//! page anyone on the network could read or change.
18
19use std::collections::{BTreeSet, HashMap};
20use std::sync::LazyLock;
21use std::time::Duration;
22
23use parking_lot::Mutex;
24use serde_json::{json, Value};
25
26use crate::backend::vault::signins;
27
28use super::AppState;
29
30/// The block meta key the pane reads its saved sign-ins from.
31pub(crate) const SIGNINS_META_KEY: &str = "browser:signins";
32const HOST_WAIT: Duration = Duration::from_secs(20);
33
34/// The frame origins each pane's page showed a sign-in form for.
35static FORMS: LazyLock<Mutex<HashMap<String, BTreeSet<String>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
36
37/// Whether a sign-in may be typed into a page of `origin`: `https`, or `http` on this computer.
38pub(crate) fn fillable(origin: &str) -> bool {
39    if origin.starts_with("https://") {
40        return true;
41    }
42    let Some(host) = origin.strip_prefix("http://") else { return false };
43    let host = host.rsplit_once(':').map_or(host, |(h, port)| if port.chars().all(|c| c.is_ascii_digit()) { h } else { host });
44    matches!(host, "localhost" | "127.0.0.1" | "[::1]")
45}
46
47/// A frame of pane `block_id` of `origin` shows a sign-in form.
48pub(crate) fn form(state: &AppState, block_id: &str, origin: &str) {
49    if !fillable(origin) {
50        return;
51    }
52    let added = FORMS.lock().entry(block_id.to_string()).or_default().insert(origin.to_string());
53    if added {
54        publish(state, block_id);
55    }
56}
57
58/// Forget every pane's forms and clear the lists saved with them. Called when
59/// the host registers: after srv restarts the forms are gone while a list saved
60/// with a pane stays, and after the host restarts its pages are new and it no
61/// longer knows to say they navigated. The host then tells srv again of every
62/// form its pages still show (`signin_notice::resend_forms`).
63pub(crate) fn reset_lists(state: &AppState) {
64    reset_in(state, &FORMS);
65}
66
67/// [`reset_lists`] on a given table of forms, so a test can clear its own
68/// without taking down the forms of tests running beside it.
69fn reset_in(state: &AppState, forms: &Mutex<HashMap<String, BTreeSet<String>>>) {
70    forms.lock().clear();
71    super::browser_signin_offer::clear_stale(state, SIGNINS_META_KEY, &BTreeSet::new(), "[signin-fill]");
72}
73
74/// Pane `block_id`'s main frame loaded a new page: its forms went with the old one.
75pub(crate) fn navigated(state: &AppState, block_id: &str) {
76    if FORMS.lock().remove(block_id).is_some() {
77        set_meta(state, block_id, Value::Null);
78    }
79}
80
81/// The frame origins pane `block_id`'s page shows a sign-in form for now.
82pub(crate) fn form_origins(block_id: &str) -> Vec<String> {
83    FORMS.lock().get(block_id).map(|o| o.iter().cloned().collect()).unwrap_or_default()
84}
85
86/// The saved sign-ins pane `block_id`'s page can take, as the pane lists them.
87fn listed(state: &AppState, block_id: &str) -> Vec<Value> {
88    let origins = form_origins(block_id);
89    let Some(profile) = super::browser_signin_offer::profile_of(state, block_id) else { return Vec::new() };
90    match signins::offered_for(&state.identity_store, &profile, &origins) {
91        Ok(found) => found.into_iter().map(|(entry, origin, user)| json!({ "entry": entry, "origin": origin, "user": signins::mask(&user) })).collect(),
92        Err(e) => {
93            tracing::warn!(error = %e, "[signin-fill] couldn't read the saved sign-ins");
94            Vec::new()
95        }
96    }
97}
98
99/// Show pane `block_id` the saved sign-ins its page can take (none: no button).
100pub(crate) fn publish(state: &AppState, block_id: &str) {
101    if !FORMS.lock().contains_key(block_id) {
102        return;
103    }
104    let list = listed(state, block_id);
105    set_meta(state, block_id, if list.is_empty() { Value::Null } else { Value::Array(list) });
106}
107
108/// The Vault changed (an entry saved, edited, moved or deleted): refresh the list
109/// of every pane whose page shows a sign-in form, so a sign-in saved while the
110/// page is open can be used and a deleted one goes from the menu. Panes whose
111/// list didn't change aren't written.
112pub(crate) fn refresh_all(state: &AppState) {
113    let panes: Vec<String> = FORMS.lock().keys().cloned().collect();
114    for block_id in panes {
115        let list = listed(state, &block_id);
116        let value = if list.is_empty() { Value::Null } else { Value::Array(list) };
117        let current = state
118            .mstore
119            .get::<crate::backend::obj::Block>(&block_id)
120            .ok()
121            .flatten()
122            .and_then(|b| b.meta.get(SIGNINS_META_KEY).cloned())
123            .unwrap_or(Value::Null);
124        if current != value {
125            set_meta(state, &block_id, value);
126        }
127    }
128}
129
130fn set_meta(state: &AppState, block_id: &str, value: Value) {
131    let mut meta = crate::backend::obj::MetaMapType::new();
132    meta.insert(SIGNINS_META_KEY.to_string(), value);
133    if let Err(e) = super::http_shell::broadcast_meta_update(state, block_id, &meta) {
134        tracing::warn!(error = %e, "[signin-fill] couldn't show the pane's saved sign-ins");
135    }
136}
137
138/// The person chose entry `entry` from pane `block_id`'s "Sign in as" menu: type
139/// it into the page, if the page still shows a form for the site it is saved for.
140pub(crate) async fn fill(state: &AppState, block_id: &str, entry: &str) -> Result<(), String> {
141    fill_picked(state, block_id, entry, false).await
142}
143
144/// [`fill`], for a pick made with the keyboard: `keep_focus` when it was Tab, which moved focus on before the
145/// fill ran, so the host gives focus back to where it went once the fields are typed.
146pub(crate) async fn fill_picked(state: &AppState, block_id: &str, entry: &str, keep_focus: bool) -> Result<(), String> {
147    // A pick closes the pane's list, by click or by key.
148    super::browser_signin_list::close(state, block_id);
149    let profile = super::browser_signin_offer::profile_of(state, block_id).ok_or("this tab keeps no sign-ins (Incognito)")?;
150    fill_as(state, block_id, entry, &profile, crate::backend::vault::PERSON, None, "", keep_focus).await.map(|_| ())
151}
152
153/// Type sign-in `entry` of `profile` into pane `block_id`'s page, if the page
154/// still shows a form for the site it is saved for, and record it as `actor`'s.
155/// Gives the site and whether a user name field was filled; never a value.
156/// `shown`: for an agent's sign-in, the entry's `created_at`, site and `updated_at` the
157/// person approved. Nothing is typed if the entry was made again with its id, or
158/// edited (its site, or who it is shared with, included), while they were asked.
159#[allow(clippy::too_many_arguments)]
160pub(crate) async fn fill_as(state: &AppState, block_id: &str, entry: &str, profile: &str, actor: &str, shown: Option<(i64, String, i64)>, reason: &str, keep_focus: bool) -> Result<(String, bool), String> {
161    let origins = form_origins(block_id);
162    // An agent's sign-in is limited to the Vaults it may use, and in its own profile's tab to the logins shared with it.
163    let own = shown.is_some().then(|| super::browser_signin::own_uid(state, actor, profile)).flatten();
164    let agent = shown.is_some().then(|| actor.to_string());
165    let (store, id, profile) = (state.identity_store.clone(), entry.to_string(), profile.to_string());
166    let (origin, username, password, label) = tokio::task::spawn_blocking(move || {
167        let who = agent.as_deref().map(|a| (a, own.as_deref()));
168        let Some((created, site, updated)) = shown else {
169            return signins::for_fill(&store, &id, &profile, &origins, who);
170        };
171        if store.vault_get(&id).map_err(|e| e.to_string())?.map(|r| (r.created_at, r.updated_at)) != Some((created, updated)) {
172            return Err("the sign-in was deleted, replaced or changed while the person was asked, so nothing was typed".to_string());
173        }
174        let found = signins::for_fill(&store, &id, &profile, &origins, who)?;
175        if found.0 != site {
176            return Err(format!("the sign-in's site was changed from {site} while the person was asked, so nothing was typed"));
177        }
178        Ok(found)
179    })
180    .await
181    .map_err(|e| e.to_string())??;
182    if !fillable(&origin) {
183        return Err(format!("{origin} isn't https, so the sign-in wasn't typed"));
184    }
185    let body = json!({ "block_id": block_id, "origin": origin, "username": username, "password": password.as_str(), "keep_focus": keep_focus });
186    let typed = super::ui_handlers::proxy_value(state, "signin_fill", body, HOST_WAIT).await;
187    drop(password);
188    let outcome = if typed.is_ok() { "done" } else { "failed" };
189    crate::backend::vault::record_line(
190        &state.identity_store,
191        crate::backend::vault::Line { entry_id: entry, label: &label, actor, action: signins::SIGNED_IN, target: &origin, outcome, reason },
192    );
193    if typed.is_ok() {
194        if let Err(e) = state.identity_store.vault_touch(entry, agentmux_common::time::now_ms()) {
195            tracing::warn!(error = %e, "[signin-fill] couldn't note the sign-in's use");
196        }
197        super::vault_handlers::publish(state);
198    }
199    let typed = typed.map_err(|(_, e)| e)?;
200    Ok((origin, typed.get("username_filled").and_then(Value::as_bool).unwrap_or(false)))
201}
202
203/// `browser.signin_fill`, from the window only: an agent's sign-in goes through
204/// `Browser` `signin` and its approval window (B3), never this.
205pub(crate) fn register(engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>, state: &AppState) {
206    use crate::backend::rpc_types::{CommandBrowserSigninFillData, COMMAND_BROWSER_SIGNIN_FILL};
207    let st = state.clone();
208    engine.register_typed(COMMAND_BROWSER_SIGNIN_FILL, move |req: CommandBrowserSigninFillData, ctx| {
209        let state = st.clone();
210        async move {
211            ctx.operator_only("only the person chooses a saved sign-in to fill")?;
212            fill(&state, &req.block_id, &req.entry).await
213        }
214    });
215}
216
217#[cfg(test)]
218#[path = "browser_signin_fill_tests.rs"]
219mod tests;