Skip to main content

agentmux_srv/server/
browser_signin_offer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "Save to Vault?" for a sign-in a browser pane saw
5//! (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §5.1, §5.2).
6//!
7//! The host hands srv the user name and password a page sent (`credential.Offer`);
8//! srv holds them here, in memory, for 2 minutes, never logged. When the page
9//! moves on (`credential.Settled`: a navigation, or the password field left the
10//! page) the pane shows the offer from its block meta [`OFFER_META_KEY`], which
11//! holds only the exact origin and the masked user name, never page text. The
12//! person's answer (`browser.signin_offer_answer`, from the window only) saves it
13//! into the tab's profile, remembers "never for this site", or drops it. The
14//! offer goes after 2 minutes or the next navigation, and the held pair with it.
15//!
16//! Incognito never saves (§9.1). A step that asks only for the user name is held
17//! the same 2 minutes and joined to the password step that follows.
18
19use std::collections::HashMap;
20use std::sync::LazyLock;
21use std::time::{Duration, Instant};
22
23use parking_lot::Mutex;
24use serde_json::{json, Value};
25use zeroize::Zeroizing;
26
27use crate::backend::vault::signins::{self, Space};
28
29use super::AppState;
30
31/// The block meta key the pane reads the offer from.
32pub(crate) const OFFER_META_KEY: &str = "browser:signin_offer";
33/// How long a sign-in is held for the person's answer.
34const HOLD: Duration = Duration::from_secs(120);
35/// A navigation this soon after the offer showed is the same sign-in finishing
36/// (a redirect, or the field leaving and then the page moving), not the person
37/// moving on.
38const SETTLING: Duration = Duration::from_secs(5);
39/// One offer per site in this long: a page luring clicks can't stack them up.
40const PER_SITE: Duration = Duration::from_secs(15);
41
42struct Held {
43    id: String,
44    profile: String,
45    origin: String,
46    username: Zeroizing<String>,
47    password: Zeroizing<String>,
48    update: bool,
49    at: Instant,
50    shown_at: Option<Instant>,
51}
52
53struct Identifier {
54    origin: String,
55    username: Zeroizing<String>,
56    at: Instant,
57}
58
59#[derive(Default)]
60struct Offers {
61    /// The sign-in each pane holds: one at a time.
62    held: HashMap<String, Held>,
63    /// A user name sent alone, by pane, for the password step.
64    identifiers: HashMap<String, Identifier>,
65    /// When each site last showed an offer, by profile and origin.
66    shown: HashMap<(String, String), Instant>,
67}
68
69static OFFERS: LazyLock<Mutex<Offers>> = LazyLock::new(|| Mutex::new(Offers::default()));
70
71/// What the person answered.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub(crate) enum Answer {
74    Save,
75    Never,
76    NotNow,
77}
78
79impl Answer {
80    pub(crate) fn parse(s: &str) -> Option<Self> {
81        match s {
82            "save" => Some(Self::Save),
83            "never" => Some(Self::Never),
84            "not_now" => Some(Self::NotNow),
85            _ => None,
86        }
87    }
88}
89
90/// The profile a pane keeps sign-ins under; `None` for Incognito or a pane that is gone.
91pub(crate) fn profile_of(state: &AppState, block_id: &str) -> Option<String> {
92    let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
93    signins::profile_for_tab(block.meta.get(super::browser_identity::IDENTITY_META_KEY).and_then(Value::as_str))
94}
95
96/// The host saw a sign-in sent in pane `block_id`'s frame of `origin`: hold it
97/// until the page moves on. `password` is `None` for a step that asks only for
98/// the user name.
99pub(crate) fn offer(state: &AppState, block_id: &str, origin: &str, username: Zeroizing<String>, password: Option<Zeroizing<String>>) {
100    let Some(profile) = profile_of(state, block_id) else { return };
101    let mut offers = OFFERS.lock();
102    let now = Instant::now();
103    // What was held for panes that never moved on goes with time.
104    offers.held.retain(|_, h| h.at.elapsed() < HOLD);
105    offers.identifiers.retain(|_, i| i.at.elapsed() < HOLD);
106    let Some(password) = password.filter(|p| !p.is_empty()) else {
107        if !username.is_empty() {
108            offers.identifiers.insert(block_id.to_string(), Identifier { origin: origin.to_string(), username, at: now });
109            forget_identifier_later(block_id.to_string(), now);
110        }
111        return;
112    };
113    let joined = match offers.identifiers.remove(block_id) {
114        Some(i) if username.is_empty() && i.origin == origin && i.at.elapsed() < HOLD => i.username,
115        _ => username,
116    };
117    // A newer sign-in in the pane replaces what it held, offered or not: an
118    // earlier wrong password's "Update" must not outlive the right one.
119    let replaced = offers.held.remove(block_id);
120    let space = Space { profile: profile.clone(), origin: origin.to_string(), realm: String::new(), proxy: false };
121    if let Some(update) = decide(state, &space, &joined, &password) {
122        let id = uuid::Uuid::new_v4().to_string();
123        offers.held.insert(
124            block_id.to_string(),
125            Held { id: id.clone(), profile, origin: origin.to_string(), username: joined, password, update, at: now, shown_at: None },
126        );
127        // Dropped after HOLD whether or not its offer ever shows (a failed sign-in
128        // leaves the field up, a tab closes): the password isn't kept past that.
129        expire_later(state.clone(), block_id.to_string(), id, HOLD);
130    }
131    drop(offers);
132    // The pair a showing bar offered is gone: so is the bar.
133    if let Some(old) = replaced.filter(|h| h.shown_at.is_some()) {
134        clear_if_showing(state, block_id, &old.id);
135    }
136}
137
138/// Whether to offer saving `username` and `password` for `space`: `None` when
139/// the person said never for the site or the Vault already holds exactly that;
140/// `Some(true)` when it holds another password for that user (an update).
141fn decide(state: &AppState, space: &Space, username: &str, password: &str) -> Option<bool> {
142    let store = &state.identity_store;
143    match store.browser_signin_never_has(&space.profile, &space.origin) {
144        Ok(false) => {}
145        Ok(true) => return None,
146        Err(e) => {
147            tracing::warn!(error = %e, "[signin-offer] couldn't read the never-save list");
148            return None;
149        }
150    }
151    match signins::saved_as(store, space, username, password) {
152        Ok(None) => Some(false),
153        Ok(Some(same)) => (!same).then_some(true),
154        Err(e) => {
155            tracing::warn!(error = %e, "[signin-offer] couldn't read the saved sign-ins");
156            None
157        }
158    }
159}
160
161/// Pane `block_id`'s page moved on (a navigation, or the password field left the
162/// page): a held sign-in's offer shows; one already showing goes, unless the
163/// sign-in is still finishing.
164pub(crate) fn settled(state: &AppState, block_id: &str) {
165    enum Then {
166        Nothing,
167        /// Dropped before it showed (a site that just showed one).
168        Drop,
169        Clear,
170        Show(Value),
171    }
172    let then = {
173        let mut guard = OFFERS.lock();
174        let o = &mut *guard;
175        let Some(held) = o.held.get_mut(block_id) else { return };
176        let then = match held.shown_at {
177            _ if held.at.elapsed() >= HOLD => Then::Clear,
178            Some(at) if at.elapsed() < SETTLING => Then::Nothing,
179            Some(_) => Then::Clear,
180            None => {
181                let site = (held.profile.clone(), held.origin.clone());
182                o.shown.retain(|_, at| at.elapsed() < PER_SITE);
183                if o.shown.contains_key(&site) {
184                    Then::Drop
185                } else {
186                    held.shown_at = Some(Instant::now());
187                    o.shown.insert(site, Instant::now());
188                    Then::Show(banner(held))
189                }
190            }
191        };
192        if matches!(then, Then::Drop | Then::Clear) {
193            o.held.remove(block_id);
194        }
195        then
196    };
197    match then {
198        Then::Nothing | Then::Drop => {}
199        Then::Clear => clear(state, block_id),
200        Then::Show(banner) => show(state, block_id, banner),
201    }
202}
203
204/// What the pane shows: the exact origin and the masked user name, and whether
205/// it replaces a saved password. Never the password, never page text.
206fn banner(held: &Held) -> Value {
207    json!({
208        "id": held.id,
209        "origin": held.origin,
210        "user": if held.username.is_empty() { String::new() } else { signins::mask(&held.username) },
211        "update": held.update,
212    })
213}
214
215fn show(state: &AppState, block_id: &str, banner: Value) {
216    let mut meta = crate::backend::obj::MetaMapType::new();
217    meta.insert(OFFER_META_KEY.to_string(), banner);
218    if let Err(e) = super::http_shell::broadcast_meta_update(state, block_id, &meta) {
219        tracing::warn!(error = %e, "[signin-offer] couldn't show the offer");
220    }
221}
222
223fn clear(state: &AppState, block_id: &str) {
224    show(state, block_id, Value::Null);
225}
226
227/// Clear the bars saved with every pane srv holds no sign-in for. Called when
228/// the host registers: a held sign-in never outlives srv, and a bar saved with a
229/// pane must not keep offering one.
230pub(crate) fn reset_bars(state: &AppState) {
231    let live: std::collections::BTreeSet<String> = OFFERS.lock().held.keys().cloned().collect();
232    clear_stale(state, OFFER_META_KEY, &live, "[signin-offer]");
233}
234
235/// Set block meta `key` to null on every pane that has it and isn't in `live`.
236pub(crate) fn clear_stale(state: &AppState, key: &str, live: &std::collections::BTreeSet<String>, tag: &str) {
237    let blocks = match state.mstore.get_all::<crate::backend::obj::Block>() {
238        Ok(b) => b,
239        Err(e) => {
240            tracing::warn!(error = %e, "{tag} couldn't list panes to clear what they saved");
241            return;
242        }
243    };
244    for b in blocks.into_iter().filter(|b| !live.contains(&b.oid) && b.meta.get(key).is_some_and(|v| !v.is_null())) {
245        let mut meta = crate::backend::obj::MetaMapType::new();
246        meta.insert(key.to_string(), Value::Null);
247        if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, &b.oid, &meta) {
248            tracing::debug!(pane = %b.oid, error = %e, "{tag} stale meta not cleared");
249        }
250    }
251}
252
253/// Take the bar down if it shows offer `id`. The bar is block meta, kept across
254/// an srv restart, while the pair it offered is held only in memory: a bar
255/// whose pair has gone would otherwise stay up with buttons that do nothing.
256fn clear_if_showing(state: &AppState, block_id: &str, id: &str) {
257    let showing = state
258        .mstore
259        .get::<crate::backend::obj::Block>(block_id)
260        .ok()
261        .flatten()
262        .is_some_and(|b| b.meta.get(OFFER_META_KEY).and_then(|o| o.get("id")).and_then(Value::as_str) == Some(id));
263    if showing {
264        clear(state, block_id);
265    }
266}
267
268/// Drop the user name pane `block_id` sent alone at `at`, after HOLD.
269fn forget_identifier_later(block_id: String, at: Instant) {
270    tokio::spawn(async move {
271        tokio::time::sleep(HOLD).await;
272        let mut offers = OFFERS.lock();
273        if offers.identifiers.get(&block_id).is_some_and(|i| i.at == at) {
274            offers.identifiers.remove(&block_id);
275        }
276    });
277}
278
279/// Drop sign-in `id` after `after`, and take its offer down if it is up.
280fn expire_later(state: AppState, block_id: String, id: String, after: Duration) {
281    tokio::spawn(async move {
282        tokio::time::sleep(after).await;
283        {
284            let mut offers = OFFERS.lock();
285            if offers.held.get(&block_id).is_some_and(|h| h.id == id) {
286                offers.held.remove(&block_id);
287            }
288        }
289        // Even when its pair already went another way (dropped as too old by a
290        // later sign-in), the bar of this offer goes now.
291        clear_if_showing(&state, &block_id, &id);
292    });
293}
294
295/// The person answered offer `id` in pane `block_id`.
296pub(crate) fn answer(state: &AppState, block_id: &str, id: &str, answer: Answer) -> Result<(), String> {
297    let held = {
298        let mut offers = OFFERS.lock();
299        match offers.held.get(block_id) {
300            Some(h) if h.id == id => offers.held.remove(block_id),
301            _ => None,
302        }
303    };
304    // A late or repeated answer to an offer that has gone leaves a newer one up,
305    // and takes down a bar of its own that is still showing.
306    let Some(held) = held else {
307        clear_if_showing(state, block_id, id);
308        return Err("that offer has gone: the sign-in wasn't kept".to_string());
309    };
310    let store = &state.identity_store;
311    let done = match answer {
312        Answer::Save => {
313            let space = Space { profile: held.profile.clone(), origin: held.origin.clone(), realm: String::new(), proxy: false };
314            signins::save(store, &space, &held.username, &held.password).map(|_| {
315                super::vault_handlers::publish(state);
316                // The page's key button now has it.
317                super::browser_signin_fill::publish(state, block_id);
318            })
319        }
320        Answer::Never => store.browser_signin_never_add(&held.profile, &held.origin, agentmux_common::time::now_ms()).map_err(|e| e.to_string()),
321        Answer::NotNow => Ok(()),
322    };
323    match done {
324        Ok(()) => {
325            clear(state, block_id);
326            Ok(())
327        }
328        Err(e) => {
329            keep_after_failure(state, block_id, held);
330            Err(e)
331        }
332    }
333}
334
335/// An answer to `held` failed. The pair and its bar stay, so the person sees why
336/// and can try again, unless its two minutes ran out while the answer was tried:
337/// its expiry then found nothing to drop, and the password isn't kept past them.
338fn keep_after_failure(state: &AppState, block_id: &str, held: Held) {
339    let mut offers = OFFERS.lock();
340    // Checked under the lock the expiry takes: either it hasn't run yet and drops
341    // the pair restored here, or it has, and the time is up.
342    if held.at.elapsed() >= HOLD {
343        drop(offers);
344        clear_if_showing(state, block_id, &held.id);
345        return;
346    }
347    offers.held.entry(block_id.to_string()).or_insert(held);
348}
349
350/// `browser.signin_offer_answer`, from the window only: an agent can't save,
351/// refuse or drop the person's sign-in for them.
352pub(crate) fn register(engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>, state: &AppState) {
353    use crate::backend::rpc_types::{CommandBrowserSigninOfferAnswerData, COMMAND_BROWSER_SIGNIN_OFFER_ANSWER};
354    let st = state.clone();
355    engine.register_typed(COMMAND_BROWSER_SIGNIN_OFFER_ANSWER, move |req: CommandBrowserSigninOfferAnswerData, ctx| {
356        let state = st.clone();
357        async move {
358            ctx.operator_only("only the person answers an offer to save their sign-in")?;
359            let answer = Answer::parse(&req.answer).ok_or_else(|| format!("answer is save, never or not_now, not {:?}", req.answer))?;
360            let st = state.clone();
361            tokio::task::spawn_blocking(move || self::answer(&st, &req.block_id, &req.id, answer)).await.map_err(|e| e.to_string())?
362        }
363    });
364}
365
366#[cfg(test)]
367#[path = "browser_signin_offer_tests.rs"]
368mod tests;