Skip to main content

agentmux_srv/server/
browser_signin_list.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The list of saved sign-ins under a login field
5//! (SPEC_VAULT_AUTOFILL_IN_BROWSER_PANE_2026_11_14.md §P2.3, the pane-drawn route R4).
6//!
7//! The page's listener tells the host what the person did in a login field (a click, Up or Down,
8//! a key the list takes, a press elsewhere) and the host hands it here (`credential.FieldOpen`,
9//! `FieldKey`, `FieldClose`). srv owns the list: the rows the tab's profile holds for exactly that
10//! frame's origin, ordered most recently used first and then by user name; the filter (what a user
11//! name field holds, matched as a case-insensitive prefix of the saved user name); and which row is
12//! selected. It writes what the pane draws into the block meta [`LIST_META_KEY`]: entry ids and
13//! **masked** user names, never a password and never a full user name, so the pane's own text (which
14//! an agent can read) says no more than the key button's does. Each answer gives the host two
15//! booleans, whether a list is showing and whether a row is selected, which it sets in the listener's
16//! world so the listener swallows a key only when it belongs to the list.
17//!
18//! The person picking a row is the approval, as for the key button: a click in the pane's own UI
19//! (`browser.signin_fill`, marked operator-only) or Enter or Tab on the selected row, which the host
20//! passes on only while no agent's input is reaching the pane. A pick types the sign-in through
21//! [`super::browser_signin_fill::fill`], or makes a strong password through [`super::browser_signup::make`].
22//!
23//! Only `https`, or `http` on this computer, and never in an Incognito tab (it keeps no sign-ins).
24
25use std::collections::HashMap;
26use std::sync::LazyLock;
27
28use parking_lot::Mutex;
29use serde_json::{json, Value};
30
31use crate::backend::vault::signins;
32
33use super::AppState;
34
35/// The block meta key the pane reads the open list from.
36pub(crate) const LIST_META_KEY: &str = "browser:signin-list";
37const HOST_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
38
39/// The kind of login field the person is in.
40#[derive(Clone, Copy, PartialEq, Eq, Debug)]
41enum Role {
42    Username,
43    Password,
44    NewPassword,
45}
46
47impl Role {
48    fn parse(s: &str) -> Option<Role> {
49        match s {
50            "username" => Some(Role::Username),
51            "password" => Some(Role::Password),
52            "newpassword" => Some(Role::NewPassword),
53            _ => None,
54        }
55    }
56    fn name(self) -> &'static str {
57        match self {
58            Role::Username => "username",
59            Role::Password => "password",
60            Role::NewPassword => "newpassword",
61        }
62    }
63}
64
65/// One saved sign-in in the list: `user` is the full user name (for the filter, never published).
66#[derive(Clone, Debug, PartialEq)]
67struct Row {
68    entry: String,
69    user: String,
70}
71
72/// The list the person has open in a pane.
73#[derive(Clone, Debug)]
74struct Open {
75    origin: String,
76    role: Role,
77    rows: Vec<Row>,
78    /// A strong password is offered (a field for a new password).
79    strong: bool,
80    /// The selected item: a row, or the strong password when that is all there is.
81    cursor: Option<usize>,
82}
83
84impl Open {
85    fn items(&self) -> usize {
86        if self.strong { 1 } else { self.rows.len() }
87    }
88}
89
90static LISTS: LazyLock<Mutex<HashMap<String, Open>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
91
92/// What the host is told after each report: whether a list is showing, and whether a row is selected.
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
94pub(crate) struct Answer {
95    pub shown: bool,
96    pub cursor: bool,
97}
98
99impl Answer {
100    pub(crate) fn to_json(self) -> Value {
101        json!({ "shown": self.shown, "cursor": self.cursor })
102    }
103}
104
105fn answer_of(open: Option<&Open>) -> Answer {
106    Answer { shown: open.is_some(), cursor: open.is_some_and(|o| o.cursor.is_some()) }
107}
108
109/// The rows pane `block_id`'s profile can fill into a field of `origin`, filtered by `text` when it is a
110/// user name field: most recently used first, then by user name.
111fn rows_for(state: &AppState, block_id: &str, origin: &str, role: Role, text: &str) -> Vec<Row> {
112    if role == Role::NewPassword || !super::browser_signin_fill::fillable(origin) {
113        return Vec::new();
114    }
115    let Some(profile) = super::browser_signin_offer::profile_of(state, block_id) else { return Vec::new() };
116    let found = match signins::offered_for(&state.identity_store, &profile, &[origin.to_string()]) {
117        Ok(f) => f,
118        Err(e) => {
119            tracing::warn!(error = %e, "[signin-list] couldn't read the saved sign-ins");
120            return Vec::new();
121        }
122    };
123    let typed = text.trim().to_lowercase();
124    let mut rows: Vec<(i64, Row)> = found
125        .into_iter()
126        .filter(|(_, _, user)| role != Role::Username || typed.is_empty() || user.to_lowercase().starts_with(&typed))
127        .map(|(entry, _, user)| {
128            let used = state.identity_store.vault_get(&entry).ok().flatten().map_or(0, |r| r.last_used_at);
129            (used, Row { entry, user })
130        })
131        .collect();
132    rows.sort_by(|(a, ra), (b, rb)| b.cmp(a).then_with(|| ra.user.to_lowercase().cmp(&rb.user.to_lowercase())));
133    rows.into_iter().map(|(_, r)| r).collect()
134}
135
136/// The meta the pane draws from, or null for no list.
137fn meta_of(open: Option<&Open>) -> Value {
138    let Some(o) = open else { return Value::Null };
139    json!({
140        "origin": o.origin,
141        "role": o.role.name(),
142        "rows": o.rows.iter().map(|r| json!({ "entry": r.entry, "user": signins::mask(&r.user) })).collect::<Vec<_>>(),
143        "strong": o.strong,
144        "cursor": o.cursor,
145    })
146}
147
148fn set_meta(state: &AppState, block_id: &str, value: Value) {
149    let mut meta = crate::backend::obj::MetaMapType::new();
150    meta.insert(LIST_META_KEY.to_string(), value);
151    if let Err(e) = super::http_shell::broadcast_meta_update(state, block_id, &meta) {
152        tracing::warn!(error = %e, "[signin-list] couldn't show the pane's list");
153    }
154}
155
156/// Show `open` (or no list) in pane `block_id`, and answer the host.
157fn show(state: &AppState, block_id: &str, open: Option<Open>) -> Answer {
158    let answer = answer_of(open.as_ref());
159    set_meta(state, block_id, meta_of(open.as_ref()));
160    match open {
161        Some(o) => LISTS.lock().insert(block_id.to_string(), o),
162        None => LISTS.lock().remove(block_id),
163    };
164    answer
165}
166
167/// The person clicked, or pressed Up or Down, in a login field of `role` in pane `block_id`'s frame of
168/// `origin`; `text` is what a user name field holds.
169pub(crate) fn open(state: &AppState, block_id: &str, origin: &str, role: &str, text: &str) -> Answer {
170    let Some(role) = Role::parse(role) else { return close(state, block_id) };
171    let rows = rows_for(state, block_id, origin, role, text);
172    let strong = role == Role::NewPassword && super::browser_signin_fill::fillable(origin) && super::browser_signin_offer::profile_of(state, block_id).is_some();
173    if rows.is_empty() && !strong {
174        return close(state, block_id);
175    }
176    // A list reopened for the same field keeps its selection while the rows are the same.
177    let cursor = LISTS.lock().get(block_id).filter(|o| o.origin == origin && o.role == role && o.rows == rows).and_then(|o| o.cursor);
178    show(state, block_id, Some(Open { origin: origin.to_string(), role, rows, strong, cursor }))
179}
180
181/// The person pressed elsewhere on the page, or the page moved on: no list.
182pub(crate) fn close(state: &AppState, block_id: &str) -> Answer {
183    let was_open = LISTS.lock().contains_key(block_id);
184    if was_open {
185        return show(state, block_id, None);
186    }
187    Answer::default()
188}
189
190/// The person pressed in the app's own UI (another pane, the address bar, the tab strip) while the list
191/// showed: the page saw no press, so nothing told the listener. Close the list here and tell the host to
192/// clear the listener's state, so the next Up, Down, Escape or Enter in the page's field is the page's.
193pub(crate) async fn close_from_ui(state: &AppState, block_id: &str) {
194    close(state, block_id);
195    // Not `proxy_value`: that notes the call as an agent's input to the pane, and this is housekeeping for the
196    // person's own press, which must not be taken for the agent's (a popup the person opens next).
197    let told = match super::ui_handlers::get_host_ipc(state).await {
198        Ok(host) => super::ui_handlers::proxy_to_host_timeout(state, &host, "signin_list_clear", json!({ "block_id": block_id }), Some(HOST_WAIT)).await,
199        Err(e) => Err(e),
200    };
201    if let Err(e) = told {
202        tracing::info!(error = %e, "[signin-list] the page's listener wasn't told the list closed");
203    }
204}
205
206/// `browser.signin_list_close`, from the window.
207pub(crate) fn register(engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>, state: &AppState) {
208    use crate::backend::rpc_types::{CommandBrowserSigninListCloseData, COMMAND_BROWSER_SIGNIN_LIST_CLOSE};
209    let st = state.clone();
210    engine.register_typed(COMMAND_BROWSER_SIGNIN_LIST_CLOSE, move |req: CommandBrowserSigninListCloseData, _ctx| {
211        let state = st.clone();
212        async move {
213            close_from_ui(&state, &req.block_id).await;
214            Ok(())
215        }
216    });
217}
218
219/// Pane `block_id`'s main frame loaded a new page.
220pub(crate) fn navigated(state: &AppState, block_id: &str) {
221    close(state, block_id);
222}
223
224/// The host registered: lists left in panes by an srv that forgot them go.
225pub(crate) fn reset(state: &AppState) {
226    LISTS.lock().clear();
227    super::browser_signin_offer::clear_stale(state, LIST_META_KEY, &std::collections::BTreeSet::new(), "[signin-list]");
228}
229
230/// A key the list took: Up, Down, Enter, Tab or Escape.
231pub(crate) fn key(state: &AppState, block_id: &str, key: &str) -> Answer {
232    let Some(mut open) = LISTS.lock().get(block_id).cloned() else { return Answer::default() };
233    let n = open.items();
234    match key {
235        "ArrowDown" if n > 0 => open.cursor = Some(open.cursor.map_or(0, |c| (c + 1) % n)),
236        "ArrowUp" if n > 0 => open.cursor = Some(open.cursor.map_or(n - 1, |c| (c + n - 1) % n)),
237        "Escape" => return close(state, block_id),
238        "Enter" | "Tab" => {
239            let Some(at) = open.cursor.filter(|c| *c < n) else { return answer_of(Some(&open)) };
240            pick(state, block_id, &open, at, key == "Tab");
241            return close(state, block_id);
242        }
243        _ => {}
244    }
245    show(state, block_id, Some(open))
246}
247
248/// The person chose item `at` with the keyboard: do what a click on it does. `tabbed`: with Tab, which moved
249/// focus on before this runs, so the fill gives it back to where it went.
250fn pick(state: &AppState, block_id: &str, open: &Open, at: usize, tabbed: bool) {
251    let (state, block_id) = (state.clone(), block_id.to_string());
252    if open.strong {
253        tokio::spawn(async move {
254            if let Err(e) = super::browser_signup::make_picked(&state, &block_id, tabbed).await {
255                tracing::info!(error = %e, "[signin-list] the strong password wasn't made");
256            }
257        });
258        return;
259    }
260    let Some(row) = open.rows.get(at) else { return };
261    let entry = row.entry.clone();
262    tokio::spawn(async move {
263        if let Err(e) = super::browser_signin_fill::fill_picked(&state, &block_id, &entry, tabbed).await {
264            tracing::info!(error = %e, "[signin-list] the sign-in wasn't typed");
265        }
266    });
267}
268
269#[cfg(test)]
270#[path = "browser_signin_list_tests.rs"]
271mod tests;