1use 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
30pub(crate) const SIGNINS_META_KEY: &str = "browser:signins";
32const HOST_WAIT: Duration = Duration::from_secs(20);
33
34static FORMS: LazyLock<Mutex<HashMap<String, BTreeSet<String>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
36
37pub(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
47pub(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
58pub(crate) fn reset_lists(state: &AppState) {
64 reset_in(state, &FORMS);
65}
66
67fn 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
74pub(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
81pub(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
86fn 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
99pub(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
108pub(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
138pub(crate) async fn fill(state: &AppState, block_id: &str, entry: &str) -> Result<(), String> {
141 fill_picked(state, block_id, entry, false).await
142}
143
144pub(crate) async fn fill_picked(state: &AppState, block_id: &str, entry: &str, keep_focus: bool) -> Result<(), String> {
147 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#[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 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
203pub(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;