loginflow 0.1.1

Browser-driven login discovery, form drive, MFA, and session capture into authjar
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Discover HTML login forms: username/password fields, CSRF tokens, honeypot skip.

use crate::error::DiscoverError;
use scraper::{ElementRef, Html, Selector};
use std::collections::HashSet;
use url::Url;

/// HTTP method for a discovered form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormMethod {
    /// GET form submission.
    Get,
    /// POST form submission.
    Post,
}

impl FormMethod {
    /// Wire method string for scald-compatible [`crate::ScaldLoginFlow`].
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Get => "GET",
            Self::Post => "POST",
        }
    }
}

/// A login form discovered in HTML.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredForm {
    /// Resolved submission URL.
    pub action_url: String,
    /// GET or POST.
    pub method: FormMethod,
    /// `name` attribute of the username/email field.
    pub username_field: String,
    /// `name` attribute of the password field.
    pub password_field: String,
    /// Hidden CSRF fields to replay on submit.
    pub csrf_fields: Vec<(String, String)>,
    /// Other non-honeypot hidden fields to include.
    pub extra_hidden: Vec<(String, String)>,
    /// Optional CSS selector for the submit control.
    pub submit_selector: Option<String>,
    /// CSS selector identifying the form element.
    pub form_selector: String,
    /// Whether a TOTP/MFA code field was detected on this form.
    pub has_totp_field: bool,
    /// Eligible for scald-style HTTP fast-path (no browser/MFA on form).
    pub http_simple: bool,
}

/// Discover all login forms in an HTML document.
///
/// # Errors
///
/// Returns [`DiscoverError::Parse`] when HTML cannot be parsed.
pub fn discover_login_forms_in_html(
    html: &str,
    page_url: &Url,
) -> Result<Vec<DiscoveredForm>, DiscoverError> {
    let document = Html::parse_document(html);
    let form_sel = Selector::parse("form").map_err(|e| DiscoverError::Parse(e.to_string()))?;
    let mut forms = Vec::new();

    for (index, form) in document.select(&form_sel).enumerate() {
        if let Some(discovered) = analyze_form(form, page_url, index) {
            forms.push(discovered);
        }
    }

    Ok(forms)
}

/// Return the highest-scoring login form, if any.
///
/// # Errors
///
/// Propagates parse errors from [`discover_login_forms_in_html`].
pub fn discover_best_login_form(
    html: &str,
    page_url: &Url,
) -> Result<Option<DiscoveredForm>, DiscoverError> {
    let mut forms = discover_login_forms_in_html(html, page_url)?;
    forms.sort_by_key(|b| std::cmp::Reverse(score_form(b)));
    Ok(forms.into_iter().next())
}

fn score_form(form: &DiscoveredForm) -> u32 {
    let mut score = 0u32;
    if form.http_simple {
        score += 10;
    }
    if form.csrf_fields.is_empty() {
        score += 1;
    }
    score += u32::try_from(form.username_field.len()).unwrap_or(0);
    score
}

fn analyze_form(form: ElementRef<'_>, page_url: &Url, index: usize) -> Option<DiscoveredForm> {
    let password_sel = Selector::parse("input[type=password]").ok()?;
    let password = form.select(&password_sel).next()?;
    let password_field = field_name(&password)?;

    let username = find_username_field(form)?;
    let username_field = field_name(&username)?;

    if is_search_field(username) {
        return None;
    }

    let method = form
        .value()
        .attr("method")
        .map(|m| m.eq_ignore_ascii_case("get"))
        .map(|is_get| {
            if is_get {
                FormMethod::Get
            } else {
                FormMethod::Post
            }
        })
        .unwrap_or(FormMethod::Post);

    let action = form.value().attr("action").unwrap_or("");
    let action_url = resolve_action(page_url, action);

    let input_sel = Selector::parse("input, textarea, select").ok()?;
    let mut csrf_fields = Vec::new();
    let mut extra_hidden = Vec::new();
    let mut has_totp_field = false;
    let mut seen_names = HashSet::new();

    for input in form.select(&input_sel) {
        let Some(name) = field_name(&input) else {
            continue;
        };
        if seen_names.contains(&name) {
            continue;
        }
        seen_names.insert(name.clone());

        let input_type = input
            .value()
            .attr("type")
            .unwrap_or("text")
            .to_ascii_lowercase();

        if input_type == "password" {
            continue;
        }

        if is_totp_field(&name, &input_type) {
            has_totp_field = true;
            continue;
        }

        if name == username_field {
            continue;
        }

        if input_type == "hidden" || input_type == "text" && is_honeypot(input) {
            if is_honeypot(input) {
                continue;
            }
            let value = input.value().attr("value").unwrap_or("").to_string();
            if is_csrf_name(&name) {
                csrf_fields.push((name, value));
            } else if input_type == "hidden" {
                extra_hidden.push((name, value));
            }
            continue;
        }

        if is_honeypot(input) {
            continue;
        }
    }

    let form_selector = form_selector_for(form, index);
    let submit_selector = find_submit_selector(form);

    let http_simple = !has_totp_field
        && matches!(method, FormMethod::Get | FormMethod::Post)
        && !action_url.is_empty();

    Some(DiscoveredForm {
        action_url,
        method,
        username_field,
        password_field,
        csrf_fields,
        extra_hidden,
        submit_selector,
        form_selector,
        has_totp_field,
        http_simple,
    })
}

fn find_username_field<'a>(form: ElementRef<'a>) -> Option<ElementRef<'a>> {
    let input_sel = Selector::parse("input, textarea").ok()?;
    let mut best: Option<(u32, ElementRef<'a>)> = None;

    for input in form.select(&input_sel) {
        let input_type = input
            .value()
            .attr("type")
            .unwrap_or("text")
            .to_ascii_lowercase();
        if input_type == "password" || input_type == "submit" || input_type == "button" {
            continue;
        }
        if !matches!(
            input_type.as_str(),
            "text" | "email" | "tel" | "" | "search"
        ) {
            continue;
        }
        let name = field_name(&input).unwrap_or_default();
        let score = username_field_score(&name, input);
        if score == 0 {
            continue;
        }
        match &best {
            None => best = Some((score, input)),
            Some((prev, _)) if score > *prev => best = Some((score, input)),
            _ => {}
        }
    }

    best.map(|(_, el)| el)
}

fn username_field_score(name: &str, input: ElementRef<'_>) -> u32 {
    let lower = name.to_ascii_lowercase();
    let mut score = 0u32;
    for token in ["user", "login", "email", "account", "id"] {
        if lower.contains(token) {
            score += 5;
        }
    }
    if input.value().attr("type") == Some("email") {
        score += 8;
    }
    if let Some(ph) = input.value().attr("placeholder") {
        let ph = ph.to_ascii_lowercase();
        if ph.contains("email") || ph.contains("user") {
            score += 4;
        }
        if ph.contains("search") {
            score = 0;
        }
    }
    if let Some(aria) = input.value().attr("aria-label") {
        let aria = aria.to_ascii_lowercase();
        if aria.contains("search") {
            score = 0;
        }
    }
    score
}

fn is_search_field(input: ElementRef<'_>) -> bool {
    if let Some(ph) = input.value().attr("placeholder") {
        let ph = ph.to_ascii_lowercase();
        if ph.contains("search") {
            return true;
        }
    }
    if let Some(aria) = input.value().attr("aria-label") {
        if aria.to_ascii_lowercase().contains("search") {
            return true;
        }
    }
    false
}

fn is_totp_field(name: &str, input_type: &str) -> bool {
    if is_csrf_name(name) {
        return false;
    }
    let lower = name.to_ascii_lowercase();
    if input_type == "tel" && (lower.contains("otp") || lower.contains("2fa")) {
        return true;
    }
    ["otp", "totp", "mfa", "2fa", "authenticator"]
        .iter()
        .any(|t| lower.contains(t))
        || (lower.contains("code") && !lower.contains("postal") && !lower.contains("zip"))
}

fn is_csrf_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower.contains("csrf")
        || lower == "_token"
        || lower.contains("authenticity")
        || lower.contains("requestverification")
        || lower == "csrfmiddlewaretoken"
}

fn is_honeypot(input: ElementRef<'_>) -> bool {
    let name = field_name(&input).unwrap_or_default().to_ascii_lowercase();
    if name.contains("honeypot") || name == "url" || name.starts_with("hp_") {
        return true;
    }
    if let Some(class) = input.value().attr("class") {
        if class.to_ascii_lowercase().contains("honeypot") {
            return true;
        }
    }
    if input.value().attr("tabindex") == Some("-1") {
        return true;
    }
    if let Some(style) = input.value().attr("style") {
        let s = style.to_ascii_lowercase();
        if s.contains("display:none")
            || s.contains("display: none")
            || s.contains("visibility:hidden")
            || s.contains("left:-")
            || s.contains("opacity:0")
        {
            return true;
        }
    }
    if let Some(aria) = input.value().attr("aria-hidden") {
        if aria == "true" {
            return true;
        }
    }
    false
}

fn field_name(el: &scraper::ElementRef<'_>) -> Option<String> {
    el.value()
        .attr("name")
        .map(str::to_string)
        .or_else(|| el.value().attr("id").map(str::to_string))
}

fn resolve_action(page_url: &Url, action: &str) -> String {
    if action.is_empty() {
        return page_url.to_string();
    }
    match page_url.join(action) {
        Ok(url) => url.to_string(),
        Err(_) => action.to_string(),
    }
}

fn form_selector_for(form: ElementRef<'_>, index: usize) -> String {
    if let Some(id) = form.value().attr("id") {
        return format!("form#{id}");
    }
    if let Some(name) = form.value().attr("name") {
        return format!("form[name=\"{name}\"]");
    }
    format!("form:nth-of-type({})", index + 1)
}

fn find_submit_selector(form: ElementRef<'_>) -> Option<String> {
    let submit_sel = Selector::parse("button[type=submit], input[type=submit]").ok()?;
    let submit = form.select(&submit_sel).next()?;
    if let Some(id) = submit.value().attr("id") {
        return Some(format!("#{id}"));
    }
    if let Some(name) = submit.value().attr("name") {
        return Some(format!("[name=\"{name}\"]"));
    }
    Some("button[type=submit], input[type=submit]".to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use url::Url;

    #[test]
    fn discovers_basic_login_form() {
        let html = r#"
        <html><body>
        <form action="/login" method="post">
          <input type="hidden" name="csrf_token" value="abc" />
          <input type="text" name="username" />
          <input type="password" name="password" />
          <button type="submit">Sign in</button>
        </form>
        </body></html>
        "#;
        let page = Url::parse("https://app.example/login").expect("url");
        let form = discover_best_login_form(html, &page)
            .expect("parse")
            .expect("form");
        assert_eq!(form.username_field, "username");
        assert_eq!(form.password_field, "password");
        assert_eq!(form.csrf_fields, vec![("csrf_token".into(), "abc".into())]);
        assert!(form.http_simple);
    }

    #[test]
    fn skips_honeypot_hidden_fields() {
        let html = r#"
        <form action="/login" method="post">
          <input type="hidden" name="hp" style="display:none" value="bot" />
          <input type="text" name="email" />
          <input type="password" name="pass" />
        </form>
        "#;
        let page = Url::parse("https://x.test/").expect("url");
        let form = discover_best_login_form(html, &page)
            .expect("parse")
            .expect("form");
        assert!(form.extra_hidden.iter().all(|(n, _)| n != "hp"));
    }

    #[test]
    fn rejects_search_username_placeholder() {
        let html = r#"
        <form action="/search" method="get">
          <input type="text" name="username" placeholder="Search by username" />
          <input type="password" name="password" />
        </form>
        "#;
        let page = Url::parse("https://x.test/").expect("url");
        let forms = discover_login_forms_in_html(html, &page).expect("parse");
        assert!(forms.is_empty());
    }
}