Skip to main content

agentmux_srv/server/
browser_account.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` `generate_password`: an agent makes an account with a password the
5//! Vault makes (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §7).
6//!
7//! The agent names the new-password field of a sign-up form by a reference from
8//! its snapshot. The host finds it and says which site's frame it is in
9//! (`signup_probe`: from its own frame map, never the page). The person is
10//! asked in the Vault's own prompt, a window modal outside every pane, which no
11//! `UI` click reaches: "Allow once", "Always for <agent> on <site>" or "Deny". Always is kept
12//! as the `accounts` kind of a site permission (browser_site_permissions.rs), listed in
13//! Settings > Browser, where the person revokes it; with it the question is skipped and
14//! the countdown stays. Silence is still a no, and an Incognito tab never offers Always.
15//! Then the pane shows "<agent> is
16//! creating an account on <site> [Stop]" for 10 seconds, and only then is the
17//! password made, kept in the Vault as an unconfirmed `login` of the tab's
18//! profile, and typed into the field and its confirm field, as for the person's
19//! own "Use a strong password" (browser_signup.rs). The agent is told the entry
20//! and the site, never the value, and then fills the other fields itself and
21//! clicks the form's button, which asks as any committing click does.
22//!
23//! A form that also asks for the current password is a password change (§7.3):
24//! it goes to [`super::browser_change`], which asks the person every time and
25//! keeps the new password pending beside the saved one. In an Incognito tab,
26//! which keeps no sign-ins, a new account's password is kept in Personal,
27//! tagged (§9.2).
28
29use std::time::Duration;
30
31use axum::extract::State;
32use axum::http::StatusCode;
33use axum::response::{IntoResponse, Response};
34use axum::Json;
35use serde::Deserialize;
36use serde_json::{json, Value};
37
38use crate::backend::vault::signups;
39use crate::backend::vault::signins::PERSONAL;
40use crate::backend::vault::uses::{Ended, UseRequest};
41use agentmux_common::api_types::UiAutomationAuth;
42
43use super::browser_actions::{note, How, Kind};
44use super::browser_signup::Field;
45use super::ui_handlers::{err_response, target_block_id};
46use super::AppState;
47
48/// How long the person has to answer.
49const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
50/// How long the notice shows before the password is made and typed.
51#[cfg(not(test))]
52const NOTICE: Duration = Duration::from_secs(10);
53#[cfg(test)]
54const NOTICE: Duration = Duration::from_millis(150);
55const HOST_WAIT: Duration = Duration::from_secs(20);
56/// What the Activity line is called.
57const MADE: &str = "made a password on sign-up";
58/// What the agent is told when another notice shows on the pane.
59const BUSY: &str = "another notice is showing on this pane: no password was made; try again when it is done";
60/// The longest user name the agent may give.
61const MAX_USERNAME: usize = 200;
62
63#[derive(Debug, Deserialize)]
64pub(crate) struct AccountRequest {
65    auth: UiAutomationAuth,
66    #[serde(default)]
67    pane: Option<String>,
68    /// The new-password field, by its reference from the latest snapshot or find.
69    #[serde(default, rename = "ref")]
70    ref_: Option<String>,
71    /// The user name the agent signs up with, if it knows it yet; the one the
72    /// form is sent with is the one the entry keeps.
73    #[serde(default)]
74    username: Option<String>,
75    /// Why the agent makes the account: one line of 8 to 300 characters, required.
76    #[serde(default)]
77    reason: Option<String>,
78}
79
80/// What the host told of the field.
81struct Probed {
82    field: Field,
83    change: bool,
84}
85
86fn probed(v: &Value, username: &str) -> Result<Probed, String> {
87    let text = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
88    let number = |k: &str| v.get(k).and_then(Value::as_u64).map(|n| n as usize);
89    let origin = text("origin").filter(|o| !o.is_empty()).ok_or("the host didn't say which site the field is on, so no password was made")?;
90    let change = v.get("change").and_then(Value::as_bool).unwrap_or(false);
91    // The agent's user name wins; a password change's form may carry the account's own.
92    let username = if username.is_empty() && change { text("username").unwrap_or_default() } else { username.to_string() };
93    let field = Field {
94        origin,
95        field: text("field").unwrap_or_default(),
96        username: clip_username(Some(&username)),
97        passwordrules: text("passwordrules"),
98        minlength: number("minlength"),
99        maxlength: number("maxlength"),
100    };
101    if field.field.is_empty() {
102        return Err("the host found no field for a new password, so no password was made".to_string());
103    }
104    Ok(Probed { field, change })
105}
106
107fn clip_username(raw: Option<&str>) -> String {
108    raw.unwrap_or("").trim().chars().filter(|c| !c.is_control()).take(MAX_USERNAME).collect()
109}
110
111fn use_request(agent: &str, agent_pane: String, origin: &str, reason: &str, incognito: bool) -> UseRequest {
112    UseRequest {
113        agent_reason: reason.to_string(),
114        id: uuid::Uuid::new_v4().to_string(),
115        agent: agent.to_string(),
116        block_id: agent_pane,
117        entry_label: format!("a new account on {origin}"),
118        what: "new account".to_string(),
119        origin: origin.to_string(),
120        // An Incognito tab keeps no sign-ins, and its password goes to Personal: that is asked every time.
121        offer_always: !incognito,
122        reason: if incognito {
123            "this is an Incognito tab, which keeps no sign-ins: the password is kept in Personal".to_string()
124        } else {
125            format!("{agent} hasn't made an account on this site with you before")
126        },
127        kind: "login".to_string(),
128        account: true,
129        requested_ms: agentmux_common::time::now_ms_u64(),
130        ..Default::default()
131    }
132}
133
134/// Ask the person, unless they have said "Always" for this agent on this site (not in an Incognito tab);
135/// `Ok(true)` when nobody answered and it went ahead.
136async fn approve(state: &AppState, block_id: &str, agent: &str, agent_pane: String, origin: &str, reason: &str, incognito: bool) -> Result<bool, (Ended, StatusCode, How, String)> {
137    if !incognito && super::browser_site_permissions::may_make_accounts(agent, origin) {
138        return Ok(false);
139    }
140    let headline = format!("{agent} wants to create an account on {origin}");
141    let (ended, _) = super::vault_ask::ask(state, block_id, use_request(agent, agent_pane, origin, reason, incognito), ANSWER_WAIT, &headline).await;
142    match ended {
143        Ended::Once => Ok(false),
144        Ended::Always => {
145            // Kept only for this agent on this site, and listed in Settings, where the person revokes it.
146            if let Err(e) = super::browser_site_permissions::add_kind(state, agent, origin, super::browser_site_permissions::ACCOUNTS) {
147                tracing::warn!(agent = %agent, origin = %origin, error = %e, "[account] the person's Always could not be kept; this account goes ahead and the next one asks");
148            }
149            Ok(false)
150        }
151        Ended::WentAhead => Ok(true),
152        ended => Err(not_allowed(ended, "an agent makes an account")),
153    }
154}
155
156/// What an answer that is not a yes means: the HTTP status, how the pane's note records it, and what the
157/// agent is told. `what` is what only the person's yes allows ("an agent makes an account").
158pub(super) fn not_allowed(ended: Ended, what: &str) -> (Ended, StatusCode, How, String) {
159    let (how, code) = if ended == Ended::NoAnswer { (How::TimedOut, StatusCode::REQUEST_TIMEOUT) } else { (How::Declined, StatusCode::FORBIDDEN) };
160    let why = if ended == Ended::Expired {
161        format!("nobody said yes, and {what} only on the person's yes: no password was made; ask the person")
162    } else {
163        ended.refusal("no password was made")
164    };
165    (ended, code, how, why)
166}
167
168/// An Activity line for a use that ended before any entry was made.
169fn refused_line(state: &AppState, origin: &str, agent: &str, outcome: &str, reason: &str) {
170    let label = format!("a new account on {origin}");
171    crate::backend::vault::record_line(&state.identity_store, crate::backend::vault::Line { entry_id: "", label: &label, actor: agent, action: MADE, target: origin, outcome, reason });
172    super::vault_handlers::publish(state);
173}
174
175/// `POST /api/v1/ui/browser/generate_password`.
176pub(crate) async fn handle_generate_password(
177    State(state): State<AppState>,
178    caller: Option<axum::Extension<crate::server::caller::Caller>>,
179    Json(req): Json<AccountRequest>,
180) -> Response {
181    let reason = match crate::backend::vault::history::require_reason(req.reason.as_deref()) {
182        Ok(r) => r,
183        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
184    };
185    let Some(ref_) = req.ref_.as_deref().map(str::trim).filter(|r| !r.is_empty()) else {
186        return err_response(StatusCode::BAD_REQUEST, "give ref: the new-password field of the sign-up form, from a snapshot or a find".to_string());
187    };
188    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
189        Ok(b) => b,
190        Err((code, e)) => return err_response(code, e),
191    };
192    let agent = req.auth.agent_id.chars().take(64).collect::<String>();
193    let Some(block) = state.mstore.get::<crate::backend::obj::Block>(&block_id).ok().flatten() else {
194        return err_response(StatusCode::NOT_FOUND, format!("no pane {block_id}"));
195    };
196    let (profile, incognito) = super::browser_signin::profile_of(&block);
197    let refuse = |e: String| {
198        note(&block_id, &agent, Kind::Fill).detail("a new account's password").how(How::Refused(e.clone())).record(&state);
199        err_response(StatusCode::BAD_REQUEST, e)
200    };
201    let probe = match super::ui_handlers::proxy_value(&state, "signup_probe", json!({ "block_id": block_id, "ref": ref_ }), HOST_WAIT).await {
202        Ok(v) => v,
203        Err((code, e)) => return err_response(code, e),
204    };
205    let found = match probed(&probe, &clip_username(req.username.as_deref())) {
206        Ok(f) => f,
207        Err(e) => return refuse(e),
208    };
209    let origin = found.field.origin.clone();
210    if found.change {
211        // The password of an account that already exists: asked every time, kept pending beside the saved one (§7.3).
212        let asked = super::browser_change::Asked {
213            block_id: &block_id,
214            agent: &agent,
215            agent_id: &req.auth.agent_id,
216            pane: req.pane.as_deref(),
217            agent_pane: super::vault_ask::agent_pane(&state, caller.as_deref(), &req.auth),
218            reason: &reason,
219            profile,
220            incognito,
221            field: found.field,
222        };
223        return super::browser_change::handle(&state, asked).await;
224    }
225    if !super::browser_signin_fill::fillable(&origin) {
226        return refuse(format!("{origin} isn't https, so no password was made for it"));
227    }
228    // Checked before the person is asked: a field whose rules leave no strong password gets none.
229    if let Err(e) = super::browser_signup::new_password(&found.field) {
230        return refuse(e);
231    }
232    tracing::info!(agent = %agent, block_id = %block_id, origin = %origin, "[account] an agent asked for a password for a new account");
233    let agent_pane = super::vault_ask::agent_pane(&state, caller.as_deref(), &req.auth);
234    let went_ahead = match approve(&state, &block_id, &agent, agent_pane, &origin, &reason, incognito).await {
235        Ok(w) => w,
236        Err((ended, code, how, why)) => {
237            refused_line(&state, &origin, &agent, ended.outcome(), &reason);
238            note(&block_id, &agent, Kind::Fill).detail("a new account's password").how(how).record(&state);
239            return err_response(code, why);
240        }
241    };
242    match super::browser_signin::notice(&state, &block_id, &agent, &origin, "", "account", NOTICE).await {
243        Some(true) => {}
244        Some(false) => {
245            refused_line(&state, &origin, &agent, "stopped", &reason);
246            note(&block_id, &agent, Kind::Fill).detail("a new account's password").how(How::Declined).record(&state);
247            return err_response(StatusCode::FORBIDDEN, "the person stopped it: no password was made".to_string());
248        }
249        None => return refuse(BUSY.to_string()),
250    }
251    if let Err((code, e)) = super::browser_signin::still_allowed(&state, &req.auth.agent_id, req.pane.as_deref(), &block_id) {
252        note(&block_id, &agent, Kind::Fill).detail("a new account's password").how(How::Refused(e.clone())).record(&state);
253        return err_response(code, e);
254    }
255    let (kept_in, extra) = if incognito { (PERSONAL.to_string(), Some(signups::FROM_INCOGNITO)) } else { (profile, None) };
256    match super::browser_signup::make_for(&state, &block_id, found.field, kept_in.clone(), &agent, &reason, extra, false).await {
257        Ok((site, entry)) => {
258            note(&block_id, &agent, Kind::Fill).detail("a new account's password").how(How::Allowed).record(&state);
259            let mut out = json!({
260                "entry": entry,
261                "site": site,
262                "profile": kept_in,
263                "password": "[secret: hidden]",
264            });
265            if went_ahead {
266                out["approval"] = json!(crate::backend::vault::uses::WENT_AHEAD);
267            }
268            (StatusCode::OK, Json(json!({ "ok": true, "data": out }))).into_response()
269        }
270        Err(e) => {
271            note(&block_id, &agent, Kind::Fill).detail("a new account's password").how(How::Refused(e.clone())).record(&state);
272            err_response(StatusCode::BAD_GATEWAY, e)
273        }
274    }
275}
276
277#[cfg(test)]
278#[path = "browser_account_tests.rs"]
279mod tests;