Skip to main content

agentmux_srv/server/
browser_signup.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "Use a strong password" on a sign-up form
5//! (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md ยง6).
6//!
7//! When the person focuses a field for a new password in a pane's page, the
8//! host says so (`credential.Signup`, with the field's `passwordrules`,
9//! `minlength` and `maxlength` and the user name typed so far); srv offers it in
10//! the block meta [`SIGNUP_META_KEY`] (the frame's origin only), and the pane's
11//! key button gets "Use a strong password (saved to the Vault)" in its menu,
12//! marked operator-only. Choosing it sends `browser.signup_password`, which only
13//! the window may: srv generates a password under the field's rules, keeps it
14//! as a `login` entry tagged unconfirmed **before** anything is typed, so the
15//! value exists only in the Vault when the site first sees it, then has the host
16//! set it into the new-password field and its confirm field.
17//!
18//! When the form is sent with it (`credential.SignupSent`), srv records the user
19//! name sent and drops the tag. A form not sent within 30 minutes leaves the
20//! entry unconfirmed in the Vault. Choosing it again (the site refused the
21//! password) replaces the unconfirmed value, the refused one kept as a version.
22//! A sign-up sent with a password the person typed is offered "Save to Vault?"
23//! like a sign-in.
24
25use std::collections::{BTreeSet, HashMap};
26use std::sync::LazyLock;
27use std::time::{Duration, Instant};
28
29use parking_lot::Mutex;
30use serde_json::{json, Value};
31use zeroize::Zeroizing;
32
33use crate::backend::vault::generate::{self, RulesRequest};
34use crate::backend::vault::signins::Space;
35use crate::backend::vault::{signups, PERSON};
36
37use super::AppState;
38
39/// The block meta key the pane reads the offer from.
40pub(crate) const SIGNUP_META_KEY: &str = "browser:signup";
41/// How long a sent form can still confirm the password made for it.
42const CONFIRM_WITHIN: Duration = Duration::from_secs(30 * 60);
43const HOST_WAIT: Duration = Duration::from_secs(20);
44
45/// The new-password field a pane's page last had the focus in: its frame's
46/// origin, the token the listener marked it with, and what the page says a
47/// password there may be.
48#[derive(Debug, Clone, Default)]
49pub(crate) struct Field {
50    pub origin: String,
51    /// Only this field is filled: `data-agentmux-signup` holds it.
52    pub field: String,
53    pub username: String,
54    pub passwordrules: Option<String>,
55    pub minlength: Option<usize>,
56    pub maxlength: Option<usize>,
57}
58
59/// The entry last made for a pane's sign-up, until the form is sent with it.
60#[derive(Debug, Clone)]
61struct Made {
62    origin: String,
63    entry: String,
64    at: Instant,
65}
66
67static OFFERED: LazyLock<Mutex<HashMap<String, Field>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
68static MADE: LazyLock<Mutex<HashMap<String, Made>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
69
70/// The person focused a new-password field of `field.origin` in pane `block_id`.
71/// Nothing is offered in Incognito, or on a page anyone on the network could
72/// read or change.
73pub(crate) fn focused(state: &AppState, block_id: &str, field: Field) {
74    if !token(&field.field) || !super::browser_signin_fill::fillable(&field.origin) || super::browser_signin_offer::profile_of(state, block_id).is_none() {
75        return;
76    }
77    let origin = field.origin.clone();
78    let was = OFFERED.lock().insert(block_id.to_string(), field).map(|f| f.origin);
79    if was.as_deref() != Some(origin.as_str()) {
80        set_meta(state, block_id, json!({ "origin": origin }));
81    }
82}
83
84/// A field token as the listener makes one: letters, digits and `-`, at most 64.
85fn token(t: &str) -> bool {
86    !t.is_empty() && t.len() <= 64 && t.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
87}
88
89/// Pane `block_id`'s main frame loaded a new page: its fields went with the old one.
90pub(crate) fn navigated(state: &AppState, block_id: &str) {
91    if OFFERED.lock().remove(block_id).is_some() {
92        set_meta(state, block_id, Value::Null);
93    }
94}
95
96/// Forget every pane's offer and clear the ones saved with panes. Called when
97/// the host registers, as `browser_signin_fill::reset_lists` is; the page offers
98/// again the next time the person focuses the field.
99pub(crate) fn reset_offers(state: &AppState) {
100    OFFERED.lock().clear();
101    super::browser_signin_offer::clear_stale(state, SIGNUP_META_KEY, &BTreeSet::new(), "[signup]");
102}
103
104fn set_meta(state: &AppState, block_id: &str, value: Value) {
105    let mut meta = crate::backend::obj::MetaMapType::new();
106    meta.insert(SIGNUP_META_KEY.to_string(), value);
107    if let Err(e) = super::http_shell::broadcast_meta_update(state, block_id, &meta) {
108        tracing::warn!(error = %e, "[signup] couldn't show the pane's offer");
109    }
110}
111
112/// A password for `field`: under its `passwordrules`, else its `minlength` and
113/// `maxlength`, else the defaults, clipped to `maxlength`. Rules that can't be
114/// read are dropped (the length limits still hold); rules that can are the
115/// site's, so when they leave no strong password, or contradict each other,
116/// none is made rather than one the site would refuse. `minlength` is a floor,
117/// never clipped: a field whose most allowed is shorter gets no password.
118pub(crate) fn new_password(field: &Field) -> Result<Zeroizing<String>, String> {
119    let length = field.minlength.filter(|n| *n > generate::DEFAULT_LENGTH).map(|n| n.min(generate::MAX_LENGTH));
120    let passwordrules = field.passwordrules.clone().filter(|r| !r.trim().is_empty() && generate::readable(r));
121    let rules = generate::rules(&RulesRequest { passwordrules, length, words: None, maxlength: field.maxlength })
122        .map_err(|e| format!("this field's rules leave no strong password, so none was made: {e}"))?;
123    if let Some(min) = field.minlength.filter(|n| *n > rules.length) {
124        return Err(format!("this field asks for at least {min} characters but takes at most {}, so no password was made", rules.length));
125    }
126    generate::generate(&rules)
127}
128
129/// The person chose "Use a strong password" in pane `block_id`: make one, keep
130/// it in the Vault, then set it into the page. Gives the site.
131pub(crate) async fn make(state: &AppState, block_id: &str) -> Result<String, String> {
132    make_picked(state, block_id, false).await
133}
134
135/// [`make`], for a pick made with the keyboard: `keep_focus` when it was Tab, which moved focus on before the
136/// fill ran, so the host gives focus back to where it went once the fields are filled.
137pub(crate) async fn make_picked(state: &AppState, block_id: &str, keep_focus: bool) -> Result<String, String> {
138    let profile = super::browser_signin_offer::profile_of(state, block_id).ok_or("this tab keeps no sign-ins (Incognito)")?;
139    let field = OFFERED.lock().get(block_id).cloned().ok_or("the page has no field for a new password now")?;
140    make_for(state, block_id, field, profile, PERSON, "", None, keep_focus).await.map(|(origin, _)| origin)
141}
142
143/// Make a password for `field` of pane `block_id`, keep it in the Vault under
144/// `profile` (with `extra` as one more tag; `reason` is the agent's, kept with the Activity line) before anything is typed, then set
145/// it into the page, as `actor`'s doing. Gives the site and the entry; never
146/// the value. A password made earlier for this pane and site, still unconfirmed,
147/// is replaced (the site refused it), the refused one kept as a version.
148#[allow(clippy::too_many_arguments)]
149pub(crate) async fn make_for(state: &AppState, block_id: &str, field: Field, profile: String, actor: &str, reason: &str, extra: Option<&'static str>, keep_focus: bool) -> Result<(String, String), String> {
150    let earlier = MADE.lock().get(block_id).filter(|m| m.origin == field.origin && m.at.elapsed() < CONFIRM_WITHIN).map(|m| m.entry.clone());
151    let password = new_password(&field)?;
152    let (origin, field_token) = (field.origin.clone(), field.field.clone());
153    let space = Space { profile, origin: origin.clone(), realm: String::new(), proxy: false };
154    let (store, value) = (state.identity_store.clone(), password.clone());
155    let (entry, label) = tokio::task::spawn_blocking(move || {
156        if let Some(id) = earlier {
157            if let Some(label) = signups::replace(&store, &id, &value)? {
158                return Ok((id, label));
159            }
160        }
161        signups::create_tagged(&store, &space, &field.username, &value, extra)
162    })
163    .await
164    .map_err(|e| e.to_string())??;
165    MADE.lock().insert(block_id.to_string(), Made { origin: origin.clone(), entry: entry.clone(), at: Instant::now() });
166    super::vault_handlers::publish(state);
167    let body = json!({ "block_id": block_id, "origin": origin, "field": field_token, "password": password.as_str(), "keep_focus": keep_focus });
168    let filled = super::ui_handlers::proxy_value(state, "signup_fill", body, HOST_WAIT).await;
169    drop(password);
170    let outcome = if filled.is_ok() { "done" } else { "failed" };
171    let line = crate::backend::vault::Line { entry_id: &entry, label: &label, actor, action: "filled on sign-up", target: &origin, outcome, reason };
172    crate::backend::vault::record_line(&state.identity_store, line);
173    filled.map_err(|(_, e)| format!("the password is saved in the Vault as {label}, but wasn't filled: {e}"))?;
174    Ok((origin, entry))
175}
176
177/// A sign-up form of `origin` was sent in pane `block_id`. A password made for
178/// that site and profile, sent as made, confirms its entry, however long ago
179/// it was made and across an srv restart (found in the Vault, not in `MADE`);
180/// any other password is the person's own, offered "Save to Vault?" as a
181/// sign-in is.
182pub(crate) fn sent(state: &AppState, block_id: &str, origin: &str, username: Zeroizing<String>, password: Zeroizing<String>) {
183    if let Some(profile) = super::browser_signin_offer::profile_of(state, block_id) {
184        let space = Space { profile, origin: origin.to_string(), realm: String::new(), proxy: false };
185        match signups::confirm_sent(&state.identity_store, &space, &username, &password) {
186            Ok(Some(entry)) => {
187                let mut made = MADE.lock();
188                if made.get(block_id).is_some_and(|m| m.entry == entry) {
189                    made.remove(block_id);
190                }
191                drop(made);
192                super::vault_handlers::publish(state);
193                return;
194            }
195            Ok(None) => {}
196            Err(e) => tracing::warn!(error = %e, "[signup] couldn't confirm the sign-up's password"),
197        }
198    }
199    super::browser_signin_offer::offer(state, block_id, origin, username, Some(password));
200}
201
202/// `browser.signup_password`, from the window only: an agent can't make the
203/// person's password for them through the pane's menu.
204pub(crate) fn register(engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>, state: &AppState) {
205    use crate::backend::rpc_types::{CommandBrowserSignupPasswordData, COMMAND_BROWSER_SIGNUP_PASSWORD};
206    let st = state.clone();
207    engine.register_typed(COMMAND_BROWSER_SIGNUP_PASSWORD, move |req: CommandBrowserSignupPasswordData, ctx| {
208        let state = st.clone();
209        async move {
210            ctx.operator_only("only the person chooses to make a password for a sign-up")?;
211            super::browser_signin_list::close(&state, &req.block_id);
212            make(&state, &req.block_id).await.map(|_| ())
213        }
214    });
215}
216
217#[cfg(test)]
218#[path = "browser_signup_tests.rs"]
219mod tests;