1use 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
39pub(crate) const SIGNUP_META_KEY: &str = "browser:signup";
41const CONFIRM_WITHIN: Duration = Duration::from_secs(30 * 60);
43const HOST_WAIT: Duration = Duration::from_secs(20);
44
45#[derive(Debug, Clone, Default)]
49pub(crate) struct Field {
50 pub origin: String,
51 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#[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
70pub(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
84fn token(t: &str) -> bool {
86 !t.is_empty() && t.len() <= 64 && t.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
87}
88
89pub(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
96pub(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
112pub(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
129pub(crate) async fn make(state: &AppState, block_id: &str) -> Result<String, String> {
132 make_picked(state, block_id, false).await
133}
134
135pub(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#[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
177pub(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
202pub(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;