1use 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
37pub(crate) const PENDING_META_KEY: &str = "browser:signin_pending";
39const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
41const NOTICE: Duration = Duration::from_secs(5);
43pub(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";
45pub(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)";
47pub(crate) const BUSY: &str = "another sign-in is showing its notice on this pane: nothing was typed; try again when it is done";
49
50static 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 #[serde(default)]
60 entry: Option<String>,
61 #[serde(default)]
63 reason: Option<String>,
64}
65
66pub(crate) fn grant_key(agent: &str, profile: &str, origin: &str) -> String {
71 format!("signin:{agent}|{profile}|{origin}")
72}
73
74pub(crate) fn shared_grant_key(uid: &str, profile: &str, origin: &str, saved: &str) -> String {
78 grant_key(uid, profile, &format!("{origin}|{saved}"))
79}
80
81pub(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
110struct 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
126pub(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
150pub(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#[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
164pub(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
177struct Chosen {
181 grant_agent: String,
184 shared: bool,
185 saved: String,
187 entry: String,
188 label: String,
189 origin: String,
190 user: String,
191 profile: String,
192 created: i64,
193 updated: i64,
196}
197
198struct Refusal {
201 outcome: &'static str,
202 how: How,
203 code: StatusCode,
204 why: String,
205}
206
207pub(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
217pub(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
224async 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 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
256async 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
273pub(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
311async 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 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
332pub(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
394pub(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
410pub(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;