Skip to main content

agentmux_srv/server/
browser_change.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` `generate_password` on a form that changes a password
5//! (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md ยง7.3).
6//!
7//! A form with a `current-password` field changes an account that already exists, and a wrong change
8//! locks the person out of it. So, unlike a new account:
9//! - the person is asked **every time**, in the Vault's own prompt. There is no "Always", the standing
10//!   `accounts` permission does not apply, and silence is a no;
11//! - the new password is a **pending version** of the saved sign-in for that site and user
12//!   (`backend::vault::changes`), not an entry of its own and not its value: the saved password stays
13//!   the one that works until the site was sent the form with the new one, when the page's listener
14//!   reports it (`credential.ChangeSent`, [`sent`]) and the old one is kept 7 days for the person to put back;
15//! - an Incognito tab keeps no sign-ins, so there is nothing saved to change there.
16//!
17//! The agent fills the current password with `signin` (a saved sign-in, as it asks today), fills the
18//! rest itself and clicks the form's button, which asks as any committing click does.
19
20use std::time::Duration;
21
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Response};
24use axum::Json;
25use serde_json::json;
26use zeroize::Zeroizing;
27
28use crate::backend::vault::signins::Space;
29use crate::backend::vault::uses::{Ended, UseRequest};
30use crate::backend::vault::{changes, Line};
31
32use super::browser_actions::{note, How, Kind};
33use super::browser_signup::Field;
34use super::ui_handlers::err_response;
35use super::AppState;
36
37const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
38#[cfg(not(test))]
39const NOTICE: Duration = Duration::from_secs(10);
40#[cfg(test)]
41const NOTICE: Duration = Duration::from_millis(150);
42const HOST_WAIT: Duration = Duration::from_secs(20);
43/// What the Activity line is called when the person was asked, and when the password was typed.
44const ASKED: &str = "asked to change the password";
45const FILLED: &str = "filled on password change";
46/// The detail of the pane's action note.
47const DETAIL: &str = "a changed password";
48const BUSY: &str = "another notice is showing on this pane: no password was made; try again when it is done";
49
50/// What the handler knows of the request and the pane when the host says the form is a password change.
51pub(crate) struct Asked<'a> {
52    pub block_id: &'a str,
53    pub agent: &'a str,
54    pub agent_id: &'a str,
55    pub pane: Option<&'a str>,
56    pub agent_pane: String,
57    pub reason: &'a str,
58    pub profile: String,
59    pub incognito: bool,
60    /// The form's field for the new password, as the host marked it, and the user name.
61    pub field: Field,
62}
63
64fn use_request(a: &Asked<'_>, origin: &str) -> UseRequest {
65    UseRequest {
66        agent_reason: a.reason.to_string(),
67        id: uuid::Uuid::new_v4().to_string(),
68        agent: a.agent.to_string(),
69        block_id: a.agent_pane.clone(),
70        entry_label: format!("your password on {origin}"),
71        what: "password change".to_string(),
72        origin: origin.to_string(),
73        // Asked every time, with no Always: a changed password locks the person out of the account if it is wrong.
74        offer_always: false,
75        reason: "a changed password stops the old one working on the site; the Vault keeps the old one for 7 days".to_string(),
76        kind: "login".to_string(),
77        // Silence is a no for an account, and no standing permission or grant answers for the person.
78        account: true,
79        change: true,
80        requested_ms: agentmux_common::time::now_ms_u64(),
81        ..Default::default()
82    }
83}
84
85/// An Activity line for the saved sign-in `entry` that this change is about.
86fn line(state: &AppState, entry: &str, label: &str, a: &Asked<'_>, action: &str, outcome: &str) {
87    let l = Line { entry_id: entry, label, actor: a.agent, action, target: &a.field.origin, outcome, reason: a.reason };
88    crate::backend::vault::record_line(&state.identity_store, l);
89    super::vault_handlers::publish(state);
90}
91
92fn refuse(state: &AppState, a: &Asked<'_>, why: String) -> Response {
93    note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Refused(why.clone())).record(state);
94    err_response(StatusCode::BAD_REQUEST, why)
95}
96
97/// `generate_password` on a password-change form: ask, count down, make the pending password, type it.
98pub(crate) async fn handle(state: &AppState, a: Asked<'_>) -> Response {
99    let origin = a.field.origin.clone();
100    if a.incognito {
101        return refuse(state, &a, format!("this is an Incognito tab, which keeps no sign-ins, so there is no saved password for {origin} to change: ask the person"));
102    }
103    if !super::browser_signin_fill::fillable(&origin) {
104        return refuse(state, &a, format!("{origin} isn't https, so no password was made for it"));
105    }
106    // Before the person is asked: a field whose rules leave no strong password gets none.
107    if let Err(e) = super::browser_signup::new_password(&a.field) {
108        return refuse(state, &a, e);
109    }
110    let space = Space { profile: a.profile.clone(), origin: origin.clone(), realm: String::new(), proxy: false };
111    let (store, who, user) = (state.identity_store.clone(), a.agent.to_string(), a.field.username.clone());
112    let sp = space.clone();
113    let saved = match tokio::task::spawn_blocking(move || changes::saved_login(&store, &sp, &user, &who)).await {
114        Ok(Ok(row)) => row,
115        Ok(Err(e)) => return refuse(state, &a, e),
116        Err(e) => return refuse(state, &a, e.to_string()),
117    };
118    tracing::info!(agent = %a.agent, block_id = %a.block_id, origin = %origin, "[change] an agent asked to change a saved password");
119    if let Err((ended, code, how, why)) = approve(state, &a, &origin).await {
120        line(state, &saved.id, &saved.label, &a, ASKED, ended.outcome());
121        note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(how).record(state);
122        return err_response(code, why);
123    }
124    match super::browser_signin::notice(state, a.block_id, a.agent, &origin, &a.field.username, "change", NOTICE).await {
125        Some(true) => {}
126        Some(false) => {
127            line(state, &saved.id, &saved.label, &a, ASKED, "stopped");
128            note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Declined).record(state);
129            return err_response(StatusCode::FORBIDDEN, "the person stopped it: no password was made".to_string());
130        }
131        None => return refuse(state, &a, BUSY.to_string()),
132    }
133    if let Err((code, e)) = super::browser_signin::still_allowed(state, a.agent_id, a.pane, a.block_id) {
134        note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Refused(e.clone())).record(state);
135        return err_response(code, e);
136    }
137    match make(state, &a, &saved).await {
138        Ok(()) => {
139            note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Allowed).record(state);
140            let out = json!({
141                "entry": saved.id,
142                "site": origin,
143                "profile": a.profile,
144                "password": "[secret: hidden]",
145                "kept": "the saved password stays the one that works until the form is sent with the new one; the old one is then kept 7 days",
146            });
147            (StatusCode::OK, Json(json!({ "ok": true, "data": out }))).into_response()
148        }
149        Err(e) => {
150            note(a.block_id, a.agent, Kind::Fill).detail(DETAIL).how(How::Refused(e.clone())).record(state);
151            err_response(StatusCode::BAD_GATEWAY, e)
152        }
153    }
154}
155
156/// Ask the person; only "Allow once" goes on.
157async fn approve(state: &AppState, a: &Asked<'_>, origin: &str) -> Result<(), (Ended, StatusCode, How, String)> {
158    let headline = format!("{} wants to change your password on {origin}", a.agent);
159    let (ended, _) = super::vault_ask::ask(state, a.block_id, use_request(a, origin), ANSWER_WAIT, &headline).await;
160    match ended {
161        Ended::Once => Ok(()),
162        other => Err(super::browser_account::not_allowed(other, "an agent changes a password")),
163    }
164}
165
166/// Make the password, keep it as the saved sign-in's pending change, then type it into the page.
167async fn make(state: &AppState, a: &Asked<'_>, saved: &crate::backend::storage::vault::VaultRow) -> Result<(), String> {
168    let password = super::browser_signup::new_password(&a.field)?;
169    let (store, row, value, who) = (state.identity_store.clone(), saved.clone(), password.clone(), a.agent.to_string());
170    let change = tokio::task::spawn_blocking(move || changes::start(&store, &row, &value, &who)).await.map_err(|e| e.to_string())??;
171    let body = json!({ "block_id": a.block_id, "origin": a.field.origin, "field": a.field.field, "password": password.as_str() });
172    let filled = super::ui_handlers::proxy_value(state, "signup_fill", body, HOST_WAIT).await;
173    drop(password);
174    match filled {
175        Ok(_) => {
176            line(state, &saved.id, &saved.label, a, FILLED, "done");
177            Ok(())
178        }
179        Err((_, e)) => {
180            // No page saw it: nothing to keep.
181            let store = state.identity_store.clone();
182            if let Err(e) = tokio::task::spawn_blocking(move || changes::abandon(&store, &change)).await.map_err(|e| e.to_string()).and_then(|r| r) {
183                tracing::warn!(error = %e, "[change] couldn't drop a password change that was never typed");
184            }
185            line(state, &saved.id, &saved.label, a, FILLED, "failed");
186            Err(format!("the password wasn't typed, so none was kept: {e}"))
187        }
188    }
189}
190
191/// A password-change form of `origin` was sent in pane `block_id` with `password`. The password an agent
192/// made for it becomes the saved sign-in's, the old one kept 7 days; any other is the person's own, offered
193/// "Update password?" as a sign-in is. Never logged.
194pub(crate) fn sent(state: &AppState, block_id: &str, origin: &str, username: Zeroizing<String>, password: Zeroizing<String>) {
195    if let Some(profile) = super::browser_signin_offer::profile_of(state, block_id) {
196        let space = Space { profile, origin: origin.to_string(), realm: String::new(), proxy: false };
197        match changes::confirm_sent(&state.identity_store, &space, &password) {
198            Ok(Some(_)) => {
199                super::vault_handlers::publish(state);
200                return;
201            }
202            Ok(None) => {}
203            Err(e) => tracing::warn!(error = %e, "[change] couldn't confirm the changed password"),
204        }
205    }
206    super::browser_signin_offer::offer(state, block_id, origin, username, Some(password));
207}