Skip to main content

vault_core/
session_import.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Web-session capture parsers (Phase 24.5, step 3).
4//!
5//! One implementation, in `vault-core`: the app reaches it over IPC and the CLI
6//! calls it directly, the `pools.ts` shape, so a paste that imports one way in
7//! the window cannot import another way from the terminal.
8//!
9//! Inputs: DevTools **Copy as cURL** (bash, cmd and PowerShell), **HAR**,
10//! `Set-Cookie` lines, and a **Firefox `cookies.sqlite`**. Everything parsed is
11//! attacker-controlled text (a pasted file from a site you were logged into), so
12//! nothing is executed or fetched, lengths are bounded, and cookie values are
13//! checked against RFC 6265's cookie-octet set (S10).
14//!
15//! What a capture is *not*: a place for other credentials. A cURL or HAR paste
16//! carries an `Authorization` header and cookies for CDNs and trackers; S12 says
17//! only the chosen origin's survive and the caller is told what was dropped, by
18//! name and never by value.
19
20use serde::Serialize;
21use serde_json::Value;
22
23/// Hard cap on pasted input. A HAR of a long session is megabytes; anything past
24/// this is not a login capture.
25pub const MAX_INPUT: usize = 32 * 1024 * 1024;
26
27#[derive(Debug, Clone, Default, PartialEq, Serialize)]
28pub struct Cookie {
29    pub name: String,
30    pub value: String,
31    pub domain: Option<String>,
32    pub path: Option<String>,
33    pub secure: bool,
34    pub http_only: bool,
35    /// Unix seconds. `0` is a session cookie.
36    pub expires: i64,
37    /// CHIPS. `cookies.txt` cannot express it, so that export refuses (S3).
38    pub partitioned: bool,
39}
40
41#[derive(Debug, Clone, Default, PartialEq, Serialize)]
42pub struct Capture {
43    /// `scheme://host[:port]` the capture was scoped to.
44    pub origin: Option<String>,
45    pub cookies: Vec<Cookie>,
46    /// Headers worth keeping (never `Cookie`, never `Authorization`).
47    pub headers: Vec<(String, String)>,
48    pub user_agent: Option<String>,
49    /// What was left out, by name only — see S12.
50    pub dropped: Vec<String>,
51}
52
53/// Headers that are either consumed elsewhere or are separate credentials.
54const SENSITIVE: [&str; 4] = [
55    "authorization",
56    "proxy-authorization",
57    "x-api-key",
58    "x-auth-token",
59];
60/// Transport noise that tells a replay nothing and bloats the stored recipe.
61const NOISE: [&str; 8] = [
62    "host",
63    "content-length",
64    "accept-encoding",
65    "connection",
66    "cookie",
67    "user-agent",
68    "priority",
69    "te",
70];
71
72fn origin_of(url: &str) -> Option<String> {
73    let (scheme, rest) = url.split_once("://")?;
74    if scheme != "http" && scheme != "https" {
75        return None;
76    }
77    let host = rest.split(['/', '?', '#']).next()?;
78    // userinfo never belongs in an origin
79    let host = host.rsplit('@').next()?;
80    if host.is_empty() {
81        return None;
82    }
83    Some(format!("{scheme}://{host}"))
84}
85
86fn host_of(origin: &str) -> &str {
87    let h = origin.split_once("://").map_or(origin, |(_, r)| r);
88    h.rsplit_once(':')
89        .filter(|(_, p)| p.chars().all(|c| c.is_ascii_digit()) && !h.ends_with(']'))
90        .map_or(h, |(h, _)| h)
91}
92
93/// RFC 6265 cookie-octet: no controls, space, `"`, `,`, `;` or `\`. A value
94/// wrapped in one pair of double quotes is allowed to contain the rest.
95fn valid_cookie_value(v: &str) -> bool {
96    let inner = v
97        .strip_prefix('"')
98        .and_then(|x| x.strip_suffix('"'))
99        .unwrap_or(v);
100    inner
101        .chars()
102        .all(|c| (c as u32) > 0x20 && (c as u32) < 0x7f && !matches!(c, '"' | ',' | ';' | '\\'))
103}
104
105fn cookie_pairs(header: &str, out: &mut Vec<Cookie>, dropped: &mut Vec<String>) {
106    for piece in header.split(';') {
107        let piece = piece.trim();
108        let Some((name, value)) = piece.split_once('=') else {
109            continue;
110        };
111        let (name, value) = (name.trim(), value.trim());
112        if name.is_empty() {
113            continue;
114        }
115        if !valid_cookie_value(value) {
116            dropped.push(format!("cookie {name} (illegal character in value)"));
117            continue;
118        }
119        upsert(
120            out,
121            Cookie {
122                name: name.to_string(),
123                value: value.to_string(),
124                ..Default::default()
125            },
126        );
127    }
128}
129
130/// Same name + domain + path replaces; a later capture of a cookie wins (S2).
131fn upsert(out: &mut Vec<Cookie>, c: Cookie) {
132    // An attribute-less cookie (from a request) and an attributed one of the same
133    // name (from a response) are the same cookie seen twice; two attributed ones
134    // with different domains or paths are genuinely different (S2).
135    let bare = |x: &Cookie| x.domain.is_none() && x.path.is_none();
136    if let Some(slot) = out.iter_mut().find(|x| {
137        x.name == c.name && ((x.domain == c.domain && x.path == c.path) || bare(x) || bare(&c))
138    }) {
139        *slot = c;
140    } else {
141        out.push(c);
142    }
143}
144
145fn keep_header(name: &str, value: &str, cap: &mut Capture) {
146    let lower = name.to_ascii_lowercase();
147    if lower == "user-agent" {
148        cap.user_agent = Some(value.to_string());
149    } else if SENSITIVE.contains(&lower.as_str()) {
150        let note = format!("{name} header");
151        if !cap.dropped.contains(&note) {
152            cap.dropped.push(note);
153        }
154    } else if !NOISE.contains(&lower.as_str()) && !lower.starts_with("sec-fetch-") {
155        cap.headers.push((name.to_string(), value.to_string()));
156    }
157}
158
159// ── Shell tokenising ─────────────────────────────────────────────────────────
160
161/// Splits a bash command line: `'...'`, `"..."` with backslash escapes, `$'...'`
162/// (ANSI-C), and `\`-newline continuations. `cmd` mode is un-caret-ed first.
163fn shell_split(s: &str) -> Vec<String> {
164    let c: Vec<char> = s.chars().collect();
165    let mut out = Vec::new();
166    let mut cur = String::new();
167    let mut have = false;
168    let mut i = 0;
169    while i < c.len() {
170        match c[i] {
171            '\\' if matches!(c.get(i + 1), Some('\n')) => i += 2,
172            '\\' if matches!(c.get(i + 1), Some('\r')) => i += 3,
173            '\\' => {
174                if let Some(n) = c.get(i + 1) {
175                    cur.push(*n);
176                    have = true;
177                }
178                i += 2;
179            }
180            '\'' => {
181                have = true;
182                i += 1;
183                while i < c.len() && c[i] != '\'' {
184                    cur.push(c[i]);
185                    i += 1;
186                }
187                i += 1;
188            }
189            '$' if c.get(i + 1) == Some(&'\'') => {
190                have = true;
191                i += 2;
192                while i < c.len() && c[i] != '\'' {
193                    if c[i] == '\\' && i + 1 < c.len() {
194                        i += 1;
195                        match c[i] {
196                            'n' => cur.push('\n'),
197                            'r' => cur.push('\r'),
198                            't' => cur.push('\t'),
199                            'u' | 'x' => {
200                                let width = if c[i] == 'u' { 4 } else { 2 };
201                                let hex: String = c[i + 1..].iter().take(width).collect();
202                                match u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
203                                    Some(ch) => {
204                                        cur.push(ch);
205                                        i += hex.len();
206                                    }
207                                    None => cur.push(c[i]),
208                                }
209                            }
210                            other => cur.push(other),
211                        }
212                    } else {
213                        cur.push(c[i]);
214                    }
215                    i += 1;
216                }
217                i += 1;
218            }
219            '"' => {
220                have = true;
221                i += 1;
222                while i < c.len() && c[i] != '"' {
223                    if c[i] == '\\' && matches!(c.get(i + 1), Some('"' | '\\' | '$' | '`')) {
224                        i += 1;
225                    }
226                    cur.push(c[i]);
227                    i += 1;
228                }
229                i += 1;
230            }
231            ch if ch.is_whitespace() => {
232                if have {
233                    out.push(std::mem::take(&mut cur));
234                    have = false;
235                }
236                i += 1;
237            }
238            ch => {
239                cur.push(ch);
240                have = true;
241                i += 1;
242            }
243        }
244    }
245    if have {
246        out.push(cur);
247    }
248    out
249}
250
251/// Chrome's "Copy as cURL (cmd)" caret-escapes everything and uses `^"` quotes.
252fn uncaret(s: &str) -> String {
253    let joined = s.replace("^\r\n", "").replace("^\n", "");
254    let mut out = String::new();
255    let mut it = joined.chars().peekable();
256    while let Some(ch) = it.next() {
257        if ch == '^' {
258            if let Some(n) = it.next() {
259                out.push(n);
260            }
261        } else {
262            out.push(ch);
263        }
264    }
265    // cmd quoting escapes an inner quote as \" inside "..."
266    out
267}
268
269/// DevTools **Copy as cURL**, bash or cmd flavour.
270pub fn parse_curl(text: &str) -> Result<Capture, String> {
271    if text.len() > MAX_INPUT {
272        return Err("input is too large to be a login capture".into());
273    }
274    let text = text.trim();
275    let normalized = if text.contains("^\"") || text.contains("^\n") {
276        uncaret(text)
277    } else {
278        text.to_string()
279    };
280    let toks = shell_split(&normalized);
281    let mut it = toks.into_iter();
282    match it.next().as_deref() {
283        Some("curl") | Some("curl.exe") => {}
284        _ => return Err("not a curl command".into()),
285    }
286    let mut cap = Capture::default();
287    let mut url: Option<String> = None;
288    let mut body = false;
289    let mut args = it.peekable();
290    while let Some(a) = args.next() {
291        let take = |args: &mut std::iter::Peekable<std::vec::IntoIter<String>>| args.next();
292        match a.as_str() {
293            "-H" | "--header" => {
294                if let Some(h) = take(&mut args) {
295                    if let Some((k, v)) = h.split_once(':') {
296                        let (k, v) = (k.trim(), v.trim());
297                        if k.eq_ignore_ascii_case("cookie") {
298                            cookie_pairs(v, &mut cap.cookies, &mut cap.dropped);
299                        } else {
300                            keep_header(k, v, &mut cap);
301                        }
302                    }
303                }
304            }
305            "-b" | "--cookie" => {
306                if let Some(v) = take(&mut args) {
307                    if v.contains('=') {
308                        cookie_pairs(&v, &mut cap.cookies, &mut cap.dropped);
309                    } else {
310                        cap.dropped.push("cookie file reference (-b FILE)".into());
311                    }
312                }
313            }
314            "-A" | "--user-agent" => cap.user_agent = take(&mut args),
315            "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-urlencode" | "-F"
316            | "--form" => {
317                let _ = take(&mut args);
318                body = true;
319            }
320            "-X" | "--request" | "-e" | "--referer" | "-o" | "--output" | "-m" | "--max-time"
321            | "--connect-timeout" | "-x" | "--proxy" | "-u" | "--user" => {
322                if matches!(a.as_str(), "-u" | "--user") {
323                    cap.dropped.push("basic-auth credentials (-u)".into());
324                }
325                let _ = take(&mut args);
326            }
327            "--url" => url = take(&mut args),
328            s if s.starts_with('-') => {} // --compressed, -s, -L, --insecure ...
329            s => {
330                if url.is_none() {
331                    url = Some(s.to_string());
332                }
333            }
334        }
335    }
336    if body {
337        cap.dropped.push("request body".into());
338    }
339    cap.origin = url.as_deref().and_then(origin_of);
340    if cap.origin.is_none() {
341        return Err("no http(s) URL in the curl command".into());
342    }
343    Ok(cap)
344}
345
346/// DevTools **Copy as PowerShell** (`Invoke-WebRequest`).
347pub fn parse_powershell(text: &str) -> Result<Capture, String> {
348    if !text.contains("Invoke-WebRequest") && !text.contains("Invoke-RestMethod") {
349        return Err("not a PowerShell Invoke-WebRequest".into());
350    }
351    let mut cap = Capture::default();
352    // PowerShell escapes a quote inside "..." as `" and a backtick as ``.
353    let unesc = |s: &str| s.replace("`\"", "\"").replace("``", "`").replace("`$", "$");
354    let quoted = |hay: &str, from: usize| -> Option<(String, usize)> {
355        let rest = &hay[from..];
356        let open = rest.find('"')?;
357        let bytes = rest.as_bytes();
358        let mut i = open + 1;
359        while i < bytes.len() {
360            if bytes[i] == b'`' {
361                i += 2;
362                continue;
363            }
364            if bytes[i] == b'"' {
365                return Some((unesc(&rest[open + 1..i]), from + i + 1));
366            }
367            i += 1;
368        }
369        None
370    };
371    // cookies: New-Object System.Net.Cookie("name", "value", "/", "domain")
372    let mut at = 0;
373    while let Some(p) = text[at..].find("System.Net.Cookie(") {
374        let start = at + p + "System.Net.Cookie(".len();
375        let Some((name, n1)) = quoted(text, start) else {
376            break;
377        };
378        let Some((value, n2)) = quoted(text, n1) else {
379            break;
380        };
381        let path = quoted(text, n2);
382        let (path_v, n3) = path.map_or((None, n2), |(p, n)| (Some(p), n));
383        let dom = quoted(text, n3);
384        let (dom_v, n4) = dom.map_or((None, n3), |(d, n)| (Some(d), n));
385        if valid_cookie_value(&value) {
386            upsert(
387                &mut cap.cookies,
388                Cookie {
389                    name,
390                    value,
391                    path: path_v,
392                    domain: dom_v,
393                    ..Default::default()
394                },
395            );
396        } else {
397            cap.dropped
398                .push(format!("cookie {name} (illegal character in value)"));
399        }
400        at = n4;
401    }
402    // headers: @{ "name"="value" \n "name2"="value2" }
403    if let Some(h) = text.find("-Headers @{") {
404        let mut pos = h + "-Headers @{".len();
405        while let Some((k, n)) = quoted(text, pos) {
406            // stop at the closing brace of the hashtable
407            if text[pos..n].contains('}') {
408                break;
409            }
410            let Some((v, n2)) = quoted(text, n) else {
411                break;
412            };
413            keep_header(&k, &v, &mut cap);
414            pos = n2;
415            if text[pos..].trim_start().starts_with('}') {
416                break;
417            }
418        }
419    }
420    if let Some(u) = text.find("-Uri ") {
421        if let Some((url, _)) = quoted(text, u) {
422            cap.origin = origin_of(&url);
423        }
424    }
425    if let Some(ua) = text.find("-UserAgent ") {
426        if let Some((v, _)) = quoted(text, ua) {
427            cap.user_agent = Some(v);
428        }
429    }
430    if text.contains("-Body ") {
431        cap.dropped.push("request body".into());
432    }
433    if cap.origin.is_none() {
434        return Err("no -Uri in the PowerShell command".into());
435    }
436    Ok(cap)
437}
438
439// ── HAR ──────────────────────────────────────────────────────────────────────
440
441/// Parses a HAR **in memory** and keeps only the chosen origin's request cookies
442/// and headers. The HAR itself is never stored: it holds every other site the
443/// browser talked to. With several origins and no `origin`, the error lists
444/// them so the caller can ask.
445pub fn parse_har(text: &str, origin: Option<&str>) -> Result<Capture, String> {
446    if text.len() > MAX_INPUT {
447        return Err("HAR is larger than 32 MiB; export a smaller capture".into());
448    }
449    let doc: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?;
450    let entries = doc
451        .pointer("/log/entries")
452        .and_then(Value::as_array)
453        .ok_or("not a HAR: no log.entries")?;
454
455    let origin_for = |e: &Value| {
456        e.pointer("/request/url")
457            .and_then(Value::as_str)
458            .and_then(origin_of)
459    };
460    let want = match origin {
461        Some(o) => origin_of(o).ok_or_else(|| format!("'{o}' is not an http(s) origin"))?,
462        None => {
463            let mut seen: Vec<String> = Vec::new();
464            for e in entries {
465                if let Some(o) = origin_for(e) {
466                    if !seen.contains(&o) {
467                        seen.push(o);
468                    }
469                }
470            }
471            match seen.len() {
472                0 => return Err("the HAR has no http(s) requests".into()),
473                1 => seen.remove(0),
474                _ => {
475                    return Err(format!(
476                        "the HAR touches {} origins; pass --origin one of: {}",
477                        seen.len(),
478                        seen.join(", ")
479                    ))
480                }
481            }
482        }
483    };
484
485    let mut cap = Capture {
486        origin: Some(want.clone()),
487        ..Default::default()
488    };
489    let mut other_hosts: Vec<String> = Vec::new();
490    for e in entries {
491        let Some(o) = origin_for(e) else { continue };
492        if o != want {
493            let host = host_of(&o).to_string();
494            if !other_hosts.contains(&host) {
495                other_hosts.push(host);
496            }
497            continue;
498        }
499        let req = &e["request"];
500        for c in req["cookies"].as_array().into_iter().flatten() {
501            let (Some(n), Some(v)) = (c["name"].as_str(), c["value"].as_str()) else {
502                continue;
503            };
504            if valid_cookie_value(v) {
505                upsert(
506                    &mut cap.cookies,
507                    Cookie {
508                        name: n.into(),
509                        value: v.into(),
510                        ..Default::default()
511                    },
512                );
513            } else {
514                cap.dropped
515                    .push(format!("cookie {n} (illegal character in value)"));
516            }
517        }
518        // Response cookies carry the attributes request cookies lack.
519        for c in e["response"]["cookies"].as_array().into_iter().flatten() {
520            let (Some(n), Some(v)) = (c["name"].as_str(), c["value"].as_str()) else {
521                continue;
522            };
523            if !valid_cookie_value(v) {
524                continue;
525            }
526            let expires = c["expires"]
527                .as_str()
528                .and_then(|s| {
529                    time::OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339)
530                        .ok()
531                })
532                .map_or(0, |d| d.unix_timestamp());
533            upsert(
534                &mut cap.cookies,
535                Cookie {
536                    name: n.into(),
537                    value: v.into(),
538                    domain: c["domain"].as_str().map(String::from),
539                    path: c["path"].as_str().map(String::from),
540                    secure: c["secure"].as_bool().unwrap_or(false),
541                    http_only: c["httpOnly"].as_bool().unwrap_or(false),
542                    expires,
543                    partitioned: false,
544                },
545            );
546        }
547        for h in req["headers"].as_array().into_iter().flatten() {
548            if let (Some(n), Some(v)) = (h["name"].as_str(), h["value"].as_str()) {
549                if n.starts_with(':') {
550                    continue; // HTTP/2 pseudo-headers
551                }
552                // later requests win by header name
553                cap.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(n));
554                keep_header(n, v, &mut cap);
555            }
556        }
557        if req.get("postData").is_some() && !cap.dropped.iter().any(|d| d == "request body") {
558            cap.dropped.push("request body".into());
559        }
560    }
561    if !other_hosts.is_empty() {
562        cap.dropped.push(format!(
563            "requests to {} other host(s): {}",
564            other_hosts.len(),
565            other_hosts.join(", ")
566        ));
567    }
568    Ok(cap)
569}
570
571// ── Set-Cookie ───────────────────────────────────────────────────────────────
572
573fn parse_http_date(s: &str) -> Option<i64> {
574    // RFC 2822 allows nested `(comments)`, and `time` < 0.3.47 recurses on them
575    // (RUSTSEC-2026-0009: stack exhaustion). The text is attacker-controlled — a
576    // pasted `Set-Cookie` from any site — and a real cookie date is ~30 bytes with
577    // no parentheses, so both are refused before the parser sees them.
578    if s.len() > 64 || s.contains(['(', ')']) {
579        return None;
580    }
581    time::OffsetDateTime::parse(s.trim(), &time::format_description::well_known::Rfc2822)
582        .ok()
583        .map(|d| d.unix_timestamp())
584        .or_else(|| {
585            // "Wed, 21-Oct-2015 07:28:00 GMT" (the obsolete cookie spelling)
586            let fixed = s.trim().replace('-', " ");
587            time::OffsetDateTime::parse(&fixed, &time::format_description::well_known::Rfc2822)
588                .ok()
589                .map(|d| d.unix_timestamp())
590        })
591}
592
593/// One or more `Set-Cookie:` lines (or bare `name=value; Attr` lines).
594pub fn parse_set_cookie(text: &str, now_unix: i64) -> Result<Capture, String> {
595    let mut cap = Capture::default();
596    for line in text.lines() {
597        let line = line.trim();
598        let line = line
599            .strip_prefix("Set-Cookie:")
600            .or_else(|| line.strip_prefix("set-cookie:"))
601            .unwrap_or(line)
602            .trim();
603        if line.is_empty() || line.starts_with('#') {
604            continue;
605        }
606        let mut parts = line.split(';');
607        let Some((name, value)) = parts.next().and_then(|p| p.split_once('=')) else {
608            continue;
609        };
610        let (name, value) = (name.trim(), value.trim());
611        if name.is_empty() {
612            continue;
613        }
614        if !valid_cookie_value(value) {
615            cap.dropped
616                .push(format!("cookie {name} (illegal character in value)"));
617            continue;
618        }
619        let mut c = Cookie {
620            name: name.into(),
621            value: value.into(),
622            ..Default::default()
623        };
624        let mut max_age: Option<i64> = None;
625        for attr in parts {
626            let (k, v) = attr
627                .split_once('=')
628                .map_or((attr.trim(), ""), |(k, v)| (k.trim(), v.trim()));
629            match k.to_ascii_lowercase().as_str() {
630                "domain" => {
631                    c.domain = Some(v.trim_start_matches('.').to_string())
632                        .filter(|d| !d.is_empty())
633                        .map(|d| format!(".{d}"))
634                }
635                "path" => c.path = Some(v.to_string()),
636                "secure" => c.secure = true,
637                "httponly" => c.http_only = true,
638                "partitioned" => c.partitioned = true,
639                "max-age" => max_age = v.parse().ok(),
640                "expires" => c.expires = parse_http_date(v).unwrap_or(0),
641                _ => {}
642            }
643        }
644        // Max-Age beats Expires (RFC 6265 5.3).
645        if let Some(m) = max_age {
646            c.expires = if m <= 0 { 1 } else { now_unix + m };
647        }
648        // __Host- requires Secure, Path=/ and no Domain; a violating cookie is
649        // one the browser would have rejected, so importing it would mislead.
650        if name.starts_with("__Host-")
651            && (!c.secure || c.path.as_deref() != Some("/") || c.domain.is_some())
652        {
653            cap.dropped
654                .push(format!("cookie {name} (violates the __Host- prefix rules)"));
655            continue;
656        }
657        if name.starts_with("__Secure-") && !c.secure {
658            cap.dropped.push(format!(
659                "cookie {name} (violates the __Secure- prefix rules)"
660            ));
661            continue;
662        }
663        upsert(&mut cap.cookies, c);
664    }
665    if cap.cookies.is_empty() && cap.dropped.is_empty() {
666        return Err("no Set-Cookie lines found".into());
667    }
668    Ok(cap)
669}
670
671// ── Firefox ──────────────────────────────────────────────────────────────────
672
673/// Reads a Firefox profile's `cookies.sqlite` for one host (matching `host` and
674/// its subdomains). Opened read-only from a **copy** (Firefox keeps the live file
675/// locked and its WAL separate). Firefox does not encrypt this file.
676///
677/// Chrome on Windows is deliberately not here: since Chrome 127, app-bound
678/// encryption ties cookie decryption to the Chrome process, so no external tool
679/// can read it — the same wall `yt-dlp --cookies-from-browser` hits.
680pub fn read_firefox(path: &std::path::Path, host: &str) -> Result<Capture, String> {
681    let dir = std::env::temp_dir().join(format!(
682        "unv-ff-{}-{}",
683        std::process::id(),
684        crate::new_uuid()
685    ));
686    // The copy of the browser's cookie database is a secret: private from the first instant.
687    crate::create_private_dir(&dir)?;
688    let result = (|| {
689        let copy = dir.join("cookies.sqlite");
690        std::fs::copy(path, &copy).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
691        let wal = path.with_extension("sqlite-wal");
692        if wal.exists() {
693            let _ = std::fs::copy(&wal, dir.join("cookies.sqlite-wal"));
694        }
695        let conn = rusqlite::Connection::open_with_flags(
696            &copy,
697            rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE, // WAL replay needs write on the copy
698        )
699        .map_err(|e| e.to_string())?;
700        let mut stmt = conn
701            .prepare(
702                "SELECT name, value, host, path, expiry, isSecure, isHttpOnly, originAttributes \
703                 FROM moz_cookies WHERE host = ?1 OR host = ?2 OR host LIKE ?3",
704            )
705            .map_err(|e| format!("not a Firefox cookies.sqlite: {e}"))?;
706        let host = host.trim_start_matches('.');
707        let rows = stmt
708            .query_map(
709                rusqlite::params![host, format!(".{host}"), format!("%.{host}")],
710                |r| {
711                    Ok(Cookie {
712                        name: r.get(0)?,
713                        value: r.get(1)?,
714                        domain: Some(r.get::<_, String>(2)?),
715                        path: Some(r.get::<_, String>(3)?),
716                        // Newer Firefox stores milliseconds
717                        expires: {
718                            let e: i64 = r.get(4)?;
719                            if e > 100_000_000_000 {
720                                e / 1000
721                            } else {
722                                e
723                            }
724                        },
725                        secure: r.get::<_, i64>(5)? != 0,
726                        http_only: r.get::<_, i64>(6)? != 0,
727                        partitioned: r.get::<_, String>(7)?.contains("partitionKey="),
728                    })
729                },
730            )
731            .map_err(|e| e.to_string())?;
732        let mut cap = Capture::default();
733        for row in rows {
734            let c = row.map_err(|e| e.to_string())?;
735            if valid_cookie_value(&c.value) {
736                upsert(&mut cap.cookies, c);
737            } else {
738                cap.dropped
739                    .push(format!("cookie {} (illegal character in value)", c.name));
740            }
741        }
742        Ok(cap)
743    })();
744    let _ = std::fs::remove_dir_all(&dir);
745    result
746}
747
748/// What to say when someone asks for Chrome.
749pub const CHROME_REFUSAL: &str =
750    "Chrome cookies are not read. Since Chrome 127 on Windows, app-bound encryption ties cookie \
751     decryption to the Chrome process, so no outside tool can read them (yt-dlp's \
752     --cookies-from-browser fails the same way). Export from DevTools (Copy as cURL, or Save all \
753     as HAR) or use Firefox.";
754
755/// Sniffs which dialect a paste is.
756pub fn detect(text: &str) -> &'static str {
757    let t = text.trim_start();
758    if t.starts_with("curl") {
759        "curl"
760    } else if t.contains("Invoke-WebRequest") || t.contains("Invoke-RestMethod") {
761        "powershell"
762    } else if t.starts_with('{') && t.contains("\"log\"") {
763        "har"
764    } else {
765        "set-cookie"
766    }
767}
768
769/// Parse a paste of unknown dialect.
770pub fn parse_auto(text: &str, origin: Option<&str>, now_unix: i64) -> Result<Capture, String> {
771    match detect(text) {
772        "curl" => parse_curl(text),
773        "powershell" => parse_powershell(text),
774        "har" => parse_har(text, origin),
775        _ => parse_set_cookie(text, now_unix),
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782
783    const BASH: &str = r#"curl 'https://www.example.com/api/me?x=1' \
784  -H 'accept: application/json' \
785  -H 'authorization: Bearer topsecret' \
786  -H 'cookie: sid=abc123; csrftoken=zz9; bad=a b' \
787  -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64)' \
788  -H 'sec-fetch-mode: cors' \
789  -H 'x-csrf-token: zz9' \
790  --data-raw '{"a":1}' \
791  --compressed"#;
792
793    #[test]
794    fn bash_curl_keeps_the_origins_session_and_names_what_it_dropped() {
795        let c = parse_curl(BASH).unwrap();
796        assert_eq!(c.origin.as_deref(), Some("https://www.example.com"));
797        assert_eq!(
798            c.cookies
799                .iter()
800                .map(|c| c.name.as_str())
801                .collect::<Vec<_>>(),
802            ["sid", "csrftoken"]
803        );
804        assert_eq!(
805            c.user_agent.as_deref(),
806            Some("Mozilla/5.0 (X11; Linux x86_64)")
807        );
808        let names: Vec<_> = c.headers.iter().map(|(k, _)| k.as_str()).collect();
809        assert_eq!(
810            names,
811            ["accept", "x-csrf-token"],
812            "noise and credentials are not kept"
813        );
814        // S12: reported by name, never by value.
815        assert!(c.dropped.iter().any(|d| d == "authorization header"));
816        assert!(c.dropped.iter().any(|d| d == "request body"));
817        assert!(c
818            .dropped
819            .iter()
820            .any(|d| d.contains("bad") && d.contains("illegal")));
821        assert!(!format!("{:?}", c.dropped).contains("topsecret"));
822    }
823
824    #[test]
825    fn cmd_flavoured_curl_is_uncaret_ed() {
826        let cmd = "curl ^\"https://www.example.com/^\" ^\n  -H ^\"cookie: sid=abc^\" ^\n  -H ^\"user-agent: UA/1^\"";
827        let c = parse_curl(cmd).unwrap();
828        assert_eq!(c.origin.as_deref(), Some("https://www.example.com"));
829        assert_eq!(c.cookies[0].value, "abc");
830        assert_eq!(c.user_agent.as_deref(), Some("UA/1"));
831    }
832
833    #[test]
834    fn ansi_c_quoting_is_decoded() {
835        let c = parse_curl("curl 'https://e.test/' -H $'user-agent: caf\\u00e9'").unwrap();
836        assert_eq!(c.user_agent.as_deref(), Some("café"));
837    }
838
839    #[test]
840    fn powershell_capture_yields_cookies_headers_and_origin() {
841        let ps = r#"$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
842$session.UserAgent = "x"
843$session.Cookies.Add((New-Object System.Net.Cookie("sid", "abc", "/", "www.example.com")))
844Invoke-WebRequest -UseBasicParsing -Uri "https://www.example.com/a" `
845-WebSession $session `
846-Headers @{
847"accept"="text/html"
848"authorization"="Bearer nope"
849}"#;
850        let c = parse_powershell(ps).unwrap();
851        assert_eq!(c.origin.as_deref(), Some("https://www.example.com"));
852        assert_eq!(c.cookies[0].name, "sid");
853        assert_eq!(c.cookies[0].domain.as_deref(), Some("www.example.com"));
854        assert_eq!(
855            c.headers,
856            vec![("accept".to_string(), "text/html".to_string())]
857        );
858        assert!(c.dropped.iter().any(|d| d == "authorization header"));
859    }
860
861    fn har() -> String {
862        serde_json::json!({"log":{"entries":[
863          {"request":{"url":"https://www.example.com/a","headers":[
864              {"name":":authority","value":"x"},{"name":"user-agent","value":"UA"},
865              {"name":"authorization","value":"Bearer t"},{"name":"x-csrf-token","value":"old"}],
866            "cookies":[{"name":"sid","value":"1"}]},
867           "response":{"cookies":[{"name":"sid","value":"2","domain":".example.com","path":"/","secure":true,"httpOnly":true,"expires":"2030-01-01T00:00:00Z"}]}},
868          {"request":{"url":"https://www.example.com/b","headers":[{"name":"x-csrf-token","value":"new"}],
869            "cookies":[{"name":"csrf","value":"c"}]},"response":{"cookies":[]}},
870          {"request":{"url":"https://cdn.tracker.test/p","headers":[],"cookies":[{"name":"t","value":"9"}]},"response":{"cookies":[]}}
871        ]}}).to_string()
872    }
873
874    #[test]
875    fn har_keeps_one_origin_and_lists_the_others_it_dropped() {
876        let c = parse_har(&har(), Some("https://www.example.com")).unwrap();
877        assert!(
878            c.cookies.iter().all(|c| c.name != "t"),
879            "a CDN's cookie must not be kept"
880        );
881        let sid = c.cookies.iter().find(|c| c.name == "sid").unwrap();
882        assert_eq!(
883            sid.value, "2",
884            "the response cookie's value and attributes win"
885        );
886        assert!(sid.secure && sid.http_only && sid.expires > 0);
887        assert_eq!(
888            c.headers,
889            vec![("x-csrf-token".to_string(), "new".to_string())]
890        );
891        assert!(c.dropped.iter().any(|d| d.contains("cdn.tracker.test")));
892        assert!(c.dropped.iter().any(|d| d == "authorization header"));
893    }
894
895    #[test]
896    fn har_with_several_origins_asks_instead_of_guessing() {
897        let err = parse_har(&har(), None).unwrap_err();
898        assert!(err.contains("--origin") && err.contains("cdn.tracker.test"));
899    }
900
901    #[test]
902    fn set_cookie_attributes_and_prefix_rules() {
903        let now = 1_700_000_000;
904        let c = parse_set_cookie(
905            "Set-Cookie: sid=abc; Domain=example.com; Path=/; Secure; HttpOnly; Max-Age=3600; Partitioned\n\
906             Set-Cookie: __Host-x=1; Domain=example.com; Path=/; Secure\n\
907             Set-Cookie: old=1; Expires=Wed, 21 Oct 2015 07:28:00 GMT",
908            now,
909        )
910        .unwrap();
911        let sid = &c.cookies[0];
912        assert_eq!(sid.domain.as_deref(), Some(".example.com"));
913        assert_eq!(sid.expires, now + 3600, "Max-Age beats Expires");
914        assert!(sid.secure && sid.http_only && sid.partitioned);
915        assert!(c.cookies.iter().all(|c| c.name != "__Host-x"));
916        assert!(c.dropped.iter().any(|d| d.contains("__Host-")));
917        assert_eq!(
918            c.cookies.iter().find(|c| c.name == "old").unwrap().expires,
919            1_445_412_480
920        );
921    }
922
923    #[test]
924    fn a_hostile_expires_value_cannot_exhaust_the_stack() {
925        let nested = format!(
926            "Wed, 21 Oct 2015 07:28:00 GMT {}{}",
927            "(".repeat(200_000),
928            ")".repeat(200_000)
929        );
930        let c = parse_set_cookie(&format!("Set-Cookie: a=b; Expires={nested}"), 0).unwrap();
931        assert_eq!(
932            c.cookies[0].expires, 0,
933            "an unparseable date is a session cookie, not a crash"
934        );
935    }
936
937    #[test]
938    fn detect_routes_each_dialect() {
939        assert_eq!(detect("curl 'https://a.test'"), "curl");
940        assert_eq!(
941            detect("Invoke-WebRequest -Uri \"https://a.test\""),
942            "powershell"
943        );
944        assert_eq!(detect("{\"log\":{}}"), "har");
945        assert_eq!(detect("Set-Cookie: a=b"), "set-cookie");
946    }
947
948    #[test]
949    fn firefox_sqlite_is_read_from_a_copy_and_filtered_by_host() {
950        let dir = std::env::temp_dir().join(format!("unv-ffsrc-{}", crate::new_uuid()));
951        std::fs::create_dir_all(&dir).unwrap();
952        let db = dir.join("cookies.sqlite");
953        {
954            let c = rusqlite::Connection::open(&db).unwrap();
955            c.execute_batch(
956                "CREATE TABLE moz_cookies (name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, isSecure INTEGER, isHttpOnly INTEGER, originAttributes TEXT);
957                 INSERT INTO moz_cookies VALUES ('sid','1','.example.com','/',1893456000,1,1,'');
958                 INSERT INTO moz_cookies VALUES ('p','2','www.example.com','/',1893456000000,0,0,'^partitionKey=%28https%2Cexample.com%29');
959                 INSERT INTO moz_cookies VALUES ('other','3','.evil.test','/',0,0,0,'');",
960            )
961            .unwrap();
962        }
963        let cap = read_firefox(&db, "example.com").unwrap();
964        assert_eq!(cap.cookies.len(), 2);
965        assert!(cap.cookies.iter().all(|c| c.name != "other"));
966        let p = cap.cookies.iter().find(|c| c.name == "p").unwrap();
967        assert!(p.partitioned);
968        assert_eq!(p.expires, 1_893_456_000, "millisecond expiry is normalised");
969        assert!(db.exists(), "the live file is never modified");
970        let _ = std::fs::remove_dir_all(&dir);
971    }
972}