1use 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
48const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
50#[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);
56const MADE: &str = "made a password on sign-up";
58const BUSY: &str = "another notice is showing on this pane: no password was made; try again when it is done";
60const MAX_USERNAME: usize = 200;
62
63#[derive(Debug, Deserialize)]
64pub(crate) struct AccountRequest {
65 auth: UiAutomationAuth,
66 #[serde(default)]
67 pane: Option<String>,
68 #[serde(default, rename = "ref")]
70 ref_: Option<String>,
71 #[serde(default)]
74 username: Option<String>,
75 #[serde(default)]
77 reason: Option<String>,
78}
79
80struct 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 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 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
134async 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 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
156pub(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
168fn 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
175pub(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 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 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;