Skip to main content

fats/
setup.rs

1//! `fats setup` past the piped check rows (`stats::setup`): way 1, a person at a terminal, walks the provider list,
2//! a key page per provider and the agent connection (a menu that exits); way 2, an agent, starts a one-shot local
3//! key form for its user (`fats setup oxy`); way 3, a pipe (`printf %s "$KEY" | fats setup oxy`). Also every rule
4//! about a key on its way in or out: its shape on a command line (refused there, masked in `?` rows), the status
5//! line's tails and the environment's rows, the Bright Data zone pick. Screen words are data (`src/data/screens/`,
6//! `lang::screen`), the form is `src/data/setup-form.html`.
7
8use crate::cache::{Cache, jload, jsave, now};
9use crate::clean::esc;
10use crate::lang::{At, Cmd, NO_HOLES, Out, bang, bin, draw, paint};
11use crate::provider::{KEYS, Links, PROVIDERS, links};
12use crate::settings::{self, SWITCHES};
13use crate::telemetry::Level;
14use std::io::{BufRead, IsTerminal, Read, Write};
15use std::net::{TcpListener, TcpStream};
16use std::path::{Path, PathBuf};
17use std::process::{Command, Stdio};
18use std::time::Duration;
19
20/// A key form's life, s: Oxylabs' key in hand is a signup and four screens, 4–8 min and a verification mail; 10 min
21/// ran out first.
22const LIFE: f64 = 1800.0;
23const FORM: &str = include_str!("data/setup-form.html");
24
25/// The telemetry levels as the screens name them: (the stored level, its option, its word on a row). The stored
26/// word (`full`) stays what `config`, the piped rows and `fats setup telemetry <level>` print.
27const LEVELS: [(Level, &str, &str); 3] = [
28    (Level::Full, "On (anonymous usage stats)", "On (anonymous)"),
29    (Level::Minimal, "Minimal (update check only)", "Minimal"),
30    (Level::Off, "Off", "Off"),
31];
32
33/// The Settings list (`fats setup` → Settings): rows that open a screen, the read-only ones, then Back.
34const SETTINGS: [&str; 5] = ["mcp", "cache", "stats", "telemetry", "back"];
35
36/// THE menu rule, on one read of terminal bytes (one key: ESC `[A` or `OA` is ↑): ↑↓ (k j Tab) move round, a
37/// number jumps and picks, Enter or → picks, Esc ← ⌫ = back, q (or the terminal gone, no bytes) quits. (row marked,
38/// how the menu ends: `\r` pick, ESC back, `q`; None = it goes on).
39pub fn step(at: usize, n: usize, k: &[u8]) -> (usize, Option<char>) {
40    let digit = std::str::from_utf8(k).ok().and_then(|d| d.parse::<usize>().ok()?.checked_sub(1)).filter(|d| *d < n);
41    match k {
42        b"\x1b[A" | b"\x1bOA" | b"k" => ((at + n - 1) % n, None),
43        b"\x1b[B" | b"\x1bOB" | b"j" | b"\t" => ((at + 1) % n, None),
44        b"\x1b" | b"\x1b[D" | b"\x1bOD" | b"\x7f" | b"\x08" => (at, Some('\x1b')),
45        b"q" | b"\x03" | b"\x04" | b"" => (at, Some('q')),
46        b"\r" | b"\n" | b"\x1b[C" | b"\x1bOC" => (at, Some('\r')),
47        _ => (digit.unwrap_or(at), digit.map(|_| '\r')),
48    }
49}
50
51/// The terminal in raw mode by `stty` (std only: termios through `libc` needs `unsafe`, which this crate forbids),
52/// restored on drop; no `stty` (Windows) = no menu, the key form instead (way 2). `.1` = scripted keys (tests).
53struct Term(Option<String>, std::collections::VecDeque<&'static [u8]>);
54
55/// A menu's screen lines for its marked row.
56type Text<'a> = &'a dyn Fn(usize) -> Vec<String>;
57
58fn stty(args: &[&str]) -> Option<String> {
59    let o = Command::new("stty").args(args).stdin(Stdio::inherit()).stderr(Stdio::null()).output().ok()?;
60    o.status.success().then(|| String::from_utf8_lossy(&o.stdout).trim().to_string())
61}
62
63impl Term {
64    fn key(&mut self) -> Vec<u8> {
65        self.1.pop_front().map(<[u8]>::to_vec).unwrap_or_else(|| {
66            let mut buf = [0u8; 16];
67            let n = std::io::stdin().read(&mut buf).unwrap_or(0); // raw `min 1`: 0 = the terminal is gone
68            buf.get(..n).unwrap_or_default().to_vec()
69        })
70    }
71
72    /// Every screen whole, same frame: head, rule, the 4-row card, one message line, the screen's rows, keys; one
73    /// empty line between blocks, so an empty message or block leaves no gap of its own. In colour (`hue`, `paint`).
74    fn draw(&self, text: &[String], msg: &str, rows: &[String], keys: &str) {
75        let (rule, head) = (format!(" {}", "─".repeat(76)), page("done").lines().nth(7).unwrap_or_default());
76        let (card, own) = text.split_at(7.min(text.len()));
77        let top = format!("\n {{bold}}fats setup{{/}}    {}\n{rule}\n{head}\n", marks());
78        let end = [&[String::new()][..], rows, &[format!("\n{rule}\n {{dim}}{keys}{{/}}")]].concat();
79        let l = [&[top][..], card.get(1..).unwrap_or_default(), &[format!("\n   {msg}\n")], own, &end].concat();
80        let mut lines: Vec<&str> = l.iter().flat_map(|s| s.split('\n')).collect();
81        lines.dedup_by(|a, b| a.trim().is_empty() && b.trim().is_empty());
82        let frame = paint(&lines.iter().map(|l| hue(l)).collect::<Vec<_>>().join("\r\n"), &NO_HOLES);
83        #[cfg(test)]
84        tests::FRAMES.with_borrow_mut(|f| f.push(frame.clone()));
85        print!("\x1b[H\x1b[2J{frame}");
86        std::io::stdout().flush().ok();
87    }
88
89    /// A numbered menu of `items` under the screen's own lines; `text(i)` follows the marked row; an item led by
90    /// `\n` has an empty line above it (a spacer the cursor never stops on); `out` names what ← and q do. (row, end
91    /// key).
92    fn menu<S: AsRef<str>>(&mut self, text: Text, msg: &str, items: &[S], out: &str) -> (usize, char) {
93        let mut at = 0;
94        loop {
95            let row = |(j, l): (usize, &S)| {
96                let (gap, l) = l.as_ref().strip_prefix('\n').map_or(("", l.as_ref()), |l| ("\n", l));
97                format!("{gap}   {} {}. {l}", [" ", "▸"][usize::from(j == at)], j + 1)
98            };
99            let rows: Vec<String> = items.iter().enumerate().map(row).collect();
100            self.draw(&text(at), msg, &rows, &format!("↑↓ move · Enter choose (or its number) · {out}"));
101            match step(at, items.len(), &self.key()) {
102                (i, Some(k)) => return (i, k),
103                (i, None) => at = i,
104            }
105        }
106    }
107
108    /// The key, pasted or typed in raw mode, a byte a step: each redraws a mask and the count (`••••  36 chars`, at
109    /// most 60 glyphs, never a key byte), ⌫ takes one back, Enter ends it; the rest of that read and of the terminal's
110    /// input is then dropped (reads that wait 0.1 s, until one is empty), so a pasted `\r\n` never presses the next
111    /// screen's Enter. None = back: Esc, ^C, the terminal gone, Enter alone.
112    fn secret(&mut self, text: &[String], msg: &str) -> Option<String> {
113        let (mut key, mut read) = (Vec::new(), std::collections::VecDeque::new());
114        let foot = "paste the key (it stays hidden) · Enter check it · Enter alone or Esc = back";
115        let key = loop {
116            let mask = format!("   {}  {} chars", "•".repeat(key.len().min(60)), key.len());
117            self.draw(text, msg, &[mask], foot);
118            if read.is_empty() {
119                read = self.key().into();
120            }
121            match read.pop_front() {
122                Some(b'\r' | b'\n') => break key,
123                Some(0x7f | 0x08) => _ = key.pop(),
124                Some(b) if b.is_ascii_graphic() => key.push(b),
125                Some(0x1b | 0x03 | 0x04) | None => break Vec::new(),
126                Some(_) => {}
127            }
128        };
129        if self.0.is_some() && stty(&["min", "0", "time", "1"]).is_some() {
130            while !self.key().is_empty() {}
131            stty(&["min", "1", "time", "0"]);
132        }
133        Some(String::from_utf8_lossy(&key).into_owned()).filter(|k| !k.is_empty())
134    }
135}
136
137/// A frame line's colours (`lang::paint` styles, none under `NO_COLOR`): the marks ✓ green, ○ and – dim, ✗ red (a
138/// mark = the glyph and a space), the marked row (▸) bold.
139fn hue(line: &str) -> String {
140    let marks = [("✓ ", "{green}✓{/} "), ("○ ", "{dim}○{/} "), ("– ", "{dim}–{/} "), ("✗ ", "{red}✗{/} ")];
141    let l = marks.iter().fold(line.to_string(), |l, (m, c)| l.replace(m, c));
142    if line.contains('▸') { format!("{{bold}}{}{{/}}", l.replace("{/}", "{/}{bold}")) } else { l }
143}
144
145impl Drop for Term {
146    fn drop(&mut self) {
147        self.0.as_ref().map(|s| stty(&[s]));
148        print!("\x1b[?25h\x1b[?1049l");
149        std::io::stdout().flush().ok();
150    }
151}
152
153/// Part `name` of the setup screens (`src/data/screens/setup.txt`, each after its `§ name` line).
154fn page(name: &str) -> &'static str {
155    crate::lang::screen("setup").split("§ ").find_map(|s| s.strip_prefix(name)?.strip_prefix('\n')).unwrap_or_default()
156}
157
158/// A row's screen text, filled: title, the card (its top, 4 rows, its bottom), then the screen's own lines.
159fn text(p: &str) -> Vec<String> {
160    let file = if page(p).is_empty() { "provider" } else { p }; // a provider has no screen of its own
161    let status = if p == "cache" { cache_words(&settings::get().cache.value).1 } else { state(p).1 };
162    let status = if links(p).is_some() && settings::key(p).is_none() { "no key".into() } else { status }; // list: rank
163    fill(page(file), links(p), &[("status", &status)]).lines().map(String::from).collect()
164}
165
166/// The holes of setup's screens, the agent's block and the form page: `vars` first, then the provider's `{name}`
167/// `{mint}` … and `{b}` (`lang::draw`).
168fn fill(t: &str, l: Option<&Links>, vars: &[(&str, &str)]) -> String {
169    let own = l.map(|l| [("name", l.name), ("short", l.short), ("mint", l.mint), ("signup", l.signup)]);
170    let more = l.map(|l| [("step", l.step), ("rank", l.rank), ("free", l.free), ("cost", l.cost)]);
171    let all: Vec<_> = vars.iter().copied().chain(own.into_iter().chain(more).flatten()).chain([("b", bin())]).collect();
172    draw(t, &all)
173}
174
175/// Every switch with its mark: the head of every screen and the done line.
176fn marks() -> String {
177    SWITCHES.iter().map(|p| format!("{} {p}", state(p).0)).collect::<Vec<_>>().join("  ")
178}
179
180/// A row's mark (✓ used, – off, ○ not set) and its status words.
181fn state(p: &str) -> (&'static str, String) {
182    let zone = settings::zone().filter(|_| p == "bd").map(|z| format!(" · zone {z}")).unwrap_or_default();
183    match (p, settings::on(p), settings::key(p)) {
184        ("mcp", ..) => ("✓", "ready · built in · nothing to install".into()),
185        ("done", ..) => (" ", "close setup".into()),
186        ("back", ..) => (" ", String::new()),
187        ("settings", ..) => (" ", "agent connection · cache · stats · telemetry".into()),
188        ("cache", ..) => (" ", cache_words(&settings::get().cache.value).0),
189        ("stats", ..) => {
190            let (pages, spent) = crate::stats::session(&Cache::open());
191            (" ", format!("this session: {pages} pages · {spent} → {} stats", bin()))
192        }
193        ("telemetry", ..) => {
194            let (t, what) = (crate::telemetry::level(), "anonymous usage stats, to fix and improve fats");
195            let word = LEVELS.iter().find(|l| l.0 == t).map_or("", |l| l.2);
196            (["–", "✓"][usize::from(t != Level::Off)], format!("{word} · {what}"))
197        }
198        ("free", true, _) => ("✓", "ready · no account · no key · $0 · uses your home IP".into()),
199        ("free", ..) => ("–", "off · every page goes through a paid provider".into()),
200        (_, false, Some(_)) => ("–", "off · not used · key kept".into()),
201        (_, _, Some(k)) => ("✓", format!("ready · key {} saved{zone}", crate::stats::tail(&k))),
202        _ => ("○", links(p).map_or("", |l| l.rank).into()),
203    }
204}
205
206/// The Cache words: what is stored now and a page's life (`cache::expired`'s limits). (the menu row, under the
207/// dir shortened by `row_path`; the card's Status: the whole dir and the unread life too).
208fn cache_words(root: &Path) -> (String, String) {
209    let span = |s: u64| if s.is_multiple_of(3600) { format!("{} h", s / 3600) } else { format!("{} min", s / 60) };
210    let (ttl, idle) = (span(settings::limit("cache_ttl_s")), span(settings::limit("cache_idle_s")));
211    let (bytes, _, metas) = crate::cache::usage(root);
212    let pages = metas.iter().filter(|m| !crate::stats::is_serp(m)).count();
213    let size = crate::lang::ksize(usize::try_from(bytes).unwrap_or(usize::MAX));
214    let row = format!("{} · {pages} pages, {size}B · live ≤ {ttl}", row_path(root, std::env::home_dir().as_deref()));
215    (row, format!("{} · pages live ≤ {ttl} ({idle} unread) · {pages} pages, {size}B", root.display()))
216}
217
218/// A dir as a menu row shows it: `~` for the home dir; past 32 chars its first two and last two parts around `…`
219/// (`/var/folders/…/Caches/fatsearch`).
220fn row_path(dir: &Path, home: Option<&Path>) -> String {
221    let path = home.and_then(|h| dir.strip_prefix(h).ok()).map_or_else(|| dir.into(), |r| Path::new("~").join(r));
222    let parts: Vec<&Path> = path.iter().map(Path::new).collect();
223    let short: PathBuf =
224        parts.iter().take(3).chain([&Path::new("…")]).chain(parts.iter().rev().take(2).rev()).collect();
225    if path.as_os_str().len() > 32 && parts.len() > 5 { short } else { path }.display().to_string()
226}
227
228/// THE key check: the free read `fats setup` makes for the provider (`provider::check_key`, $0; gh: none, saved
229/// unchecked), for the menu, the form and the pipe (`cli::piped`). Ok = what it shows and Bright Data's zones;
230/// Err = (code, why not).
231pub fn check(l: &Links, key: &str) -> Result<(String, Vec<String>), (&'static str, String)> {
232    if key.len() < 8 {
233        return Err(("bad_key", "too short for a key: copy the whole key".into()));
234    }
235    let Some(t) = KEYS.into_iter().find(|t| t.spec().short == l.short) else { return Ok(("unchecked".into(), vec![])) };
236    let read = crate::provider::check_key(t, key.to_string());
237    let got = crate::provider::all_within(vec![read], Duration::from_secs(20)).pop().flatten();
238    let got = got.ok_or(("provider_timeout", "no answer in 20 s".to_string()))?;
239    let said =
240        |f: crate::provider::Fail| (f.code, format!("{} said no: {} {}", l.name, f.code, f.why).trim_end().into());
241    let (what, zones) = got.map_err(said)?;
242    if l.short == "bd" && zones.is_empty() {
243        return Err(("no_zone", format!("no_zone · no Web Unlocker zone yet: make one at {}", l.mint)));
244    }
245    Ok((if zones.is_empty() { what } else { format!("zones {}", zones.join(", ")) }, zones))
246}
247
248/// The gh CLI's token (`gh auth token`) for `fats setup gh` while no gh key is set: copied into `auth.json` at
249/// setup, never read at fetch time; never in a unit test (no developer credential, as `settings::env`).
250fn gh(l: &Links) -> Option<String> {
251    (l.short == "gh" && settings::key("gh").is_none() && !cfg!(test)).then_some(())?;
252    let o = Command::new("gh").args(["auth", "token"]).stdin(Stdio::null()).stderr(Stdio::null()).output().ok()?;
253    Some(String::from_utf8_lossy(&o.stdout).trim().to_string()).filter(|t| o.status.success() && !t.is_empty())
254}
255
256/// The main list: the free fetch, the providers in rank order, Settings (`SETTINGS`), Done.
257fn rows() -> Vec<&'static str> {
258    ["free"].into_iter().chain(PROVIDERS.links.iter().map(|l| l.short)).chain(["settings", "done"]).collect()
259}
260
261/// The main list until q or Done: the done line.
262fn walk(t: &mut Term, only: Option<&'static str>) -> String {
263    // `only`'s screen first: q there (None) quits; the marks are read after the walk (what it changed)
264    if only.is_none_or(|p| open(t, p).is_some()) {
265        list_loop(t, &rows(), page("intro").trim_end());
266    }
267    format!("= setup done · {} · try: {} example.com", marks(), bin())
268}
269
270/// A list's loop, the marked row's card above it, `intro` its message: Enter opens a row (`open`) and comes back;
271/// the last row (Done, ← Back), Esc or ← leave the list (Some: back to the list above), q quits (None).
272fn list_loop(t: &mut Term, list: &[&'static str], intro: &str) -> Option<()> {
273    let gap = |p: &str| if matches!(p, "settings" | "done" | "back") { "\n" } else { "" };
274    loop {
275        // one `state` a row, the title from its page or provider (`text` works the card's Status out again)
276        let row = |p: &&str| {
277            let ((mark, words), title) =
278                (state(p), links(p).map_or(page(p).lines().next().unwrap_or_default(), |l| l.name));
279            format!("{}{mark} {title:18} {words}", gap(p)).trim_end().into()
280        };
281        let items: Vec<String> = list.iter().map(row).collect();
282        let card = |i: usize| text(list.get(i).copied().unwrap_or("done")).into_iter().take(7).collect();
283        // the main list has no list above it: ← quits, as q
284        let out = if list.last() == Some(&"done") { "← or q quit" } else { "← back · q quit" };
285        match t.menu(&card, intro, &items, out) {
286            (i, '\r') if i + 1 < list.len() => open(t, list.get(i).copied().unwrap_or_default())?,
287            (_, 'q') => return None,
288            _ => return Some(()),
289        }
290    }
291}
292
293/// A row picked: Settings its list, Cache and Stats nothing (they only show), the others their screen.
294fn open(t: &mut Term, p: &'static str) -> Option<()> {
295    match p {
296        "settings" => list_loop(t, &SETTINGS, ""),
297        "cache" | "stats" => Some(()),
298        _ => screen(t, p),
299    }
300}
301
302/// A row's screen buttons that work now: a switch (Turn on/off, Remove this key = off) that THE switch rule
303/// (`settings::switched`) refuses is not shown, nor Stop the waiting form while no form waits (`waiting_at`), so no
304/// button answers "can't"; the agent connection's one per host first (`added ✓` once it holds fats); ← Back last.
305fn buttons(p: &str) -> Vec<String> {
306    let turn = ["Turn on", "Turn off"][usize::from(settings::on(p))];
307    let stop = waiting_at(&Cache::open(), p).map(|_| "Stop the waiting form");
308    let all: Vec<&str> = match (p, settings::key(p).is_some()) {
309        ("free", _) => vec![turn],
310        ("mcp", _) => vec![],
311        ("telemetry", _) => LEVELS.iter().map(|l| l.1).collect(),
312        (_, true) => vec!["Paste a new key", turn, "Remove this key"],
313        _ => vec!["Add a key"],
314    };
315    let switch = |b: &&str| matches!(*b, "Turn on" | "Turn off" | "Remove this key");
316    let shown = all.into_iter().filter(|b| !switch(b) || settings::switched(p, *b == "Turn on").is_ok());
317    crate::mcp::buttons(p).chain(shown.chain(stop).chain(["← Back"]).map(String::from)).collect()
318}
319
320/// One row's screen until Back (Some) or q (None); every button's answer is its message.
321fn screen(t: &mut Term, p: &'static str) -> Option<()> {
322    let mut msg = String::new();
323    loop {
324        let (text, on, items) = (text(p), settings::on(p), buttons(p));
325        let (at, end) = t.menu(&|_| text.clone(), &msg, &items, "← back · q quit");
326        let done = match (end, items.get(at).map_or("", String::as_str), links(p)) {
327            ('q', ..) => return None,
328            // a test (`in_process`) only names the add: no host config edited
329            ('\r', ..) if let Some(said) = crate::mcp::pressed(p, at, crate::provider::in_process()) => Ok(said),
330            // saved or not, the screen stays: its rows and Status show the key at once
331            ('\r', "Add a key" | "Paste a new key", Some(l)) => Ok(paste(t, l).unwrap_or_else(|m| m)),
332            // removed = off, so THE switch rule refuses removing the last key that fetches
333            ('\r', "Remove this key", _) => (settings::set_on(p, false).and_then(|()| settings::remove_key(p)))
334                .and_then(|()| settings::set_on(p, true))
335                .map(|()| bak_row().map_or("○ key removed".into(), |b| format!("○ key removed · {b}"))),
336            ('\r', l, _) if let Some((level, _, word)) = LEVELS.iter().find(|o| o.1 == l) => {
337                settings::set("telemetry", level.name()).map(|()| format!("✓ telemetry {word} · from the next command"))
338            }
339            ('\r', "Turn on" | "Turn off", _) => settings::set_on(p, !on).map(|()| format!("✓ {}", state(p).1)),
340            ('\r', "Stop the waiting form", _) => stop(p, false).map(|said| format!("✓ {said}")),
341            _ => return Some(()),
342        };
343        msg = done.unwrap_or_else(|e| format!("✗ Can't: {e}"));
344    }
345}
346
347/// Paste the key (gh: the gh CLI's first, `gh`), check it ($0), pick Bright Data's zone when it has more than one
348/// (saved: fats never switches it), save. Ok = the screen's message for the saved key; Err = why none was saved.
349fn paste(t: &mut Term, l: &'static Links) -> Result<String, String> {
350    let open = format!("Open {} (no account yet: {})", l.mint, l.signup);
351    let key = gh(l).map_or_else(|| t.secret(&text(l.short), &open).ok_or_else(String::new), Ok)?;
352    t.draw(&text(l.short), &format!("… checking the key with {} ($0)", l.name), &[], "checking…");
353    let (what, zones) = check(l, &key).map_err(|(_, why)| format!("✗ {why} · not saved"))?;
354    let pick = "✓ The key works. Pick the Web Unlocker zone fats should use:";
355    let zone = match (zones.len() > 1).then(|| t.menu(&|_| text(l.short), pick, &zones, "← back · q quit")) {
356        Some((i, '\r')) => zones.get(i),
357        Some(_) => return Err(String::new()),
358        None => zones.first(),
359    };
360    settings::save_key(l.short, &key, zone.map(String::as_str)).map_err(|e| format!("✗ not saved: {e}"))?;
361    Ok(format!("✓ {} works · {} saved", l.name, key_row(what, zone, &key)))
362}
363
364/// A saved key as both setups print it: Bright Data's zone (else what the check said), then the key's tail.
365fn key_row(what: String, zone: Option<&String>, key: &str) -> String {
366    format!("{} · key {}", zone.map_or(what, |z| format!("zone {z}")), crate::stats::tail(key))
367}
368
369/// Way 1 (`main`): `fats setup [provider]` with a terminal on both ends and `stty`, `provider`'s screen first; None
370/// = piped, an agent, no `stty`, or another command.
371pub fn tty(argv: &[String]) -> Option<i32> {
372    let cmd = crate::lang::parse(argv);
373    let own = cmd.sub.first().and_then(|w| ["telemetry", "mcp"].into_iter().find(|p| p == w));
374    let only = cmd.sub.first().and_then(|p| links(p)).map(|l| l.short).or(own);
375    let term = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
376    (term && cmd.has("setup") && cmd.sub.len() < 2 && cmd.words.is_empty() && cmd.mods.is_empty()).then_some(())?;
377    let saved = stty(&["-g"]).filter(|_| stty(&["raw", "-echo", "min", "1", "time", "0"]).is_some())?;
378    // a menu that exits (q, Done): the done line printed after the terminal is restored (`Term` dropped)
379    print!("\x1b[?1049h\x1b[?25l");
380    println!("{}", walk(&mut Term(Some(saved), Default::default()), only));
381    Some(0)
382}
383
384/// Way 2 (`stats::change`): `fats setup <free|oxy|bd|decodo|gh>` without a terminal. gh: the gh CLI's token
385/// copied when it has one, else the form; `dry` starts nothing.
386pub fn agent(p: &str, dry: bool) -> Out {
387    let said = match links(p) {
388        None if !settings::on("free") => format!("= setup free · {}", free_off().1),
389        None => format!("= setup free · built in, no key to set · $0 · off: {} setup free off", bin()),
390        // offline: the form's check could not run, so none starts (as a plain `fats setup` is dry)
391        Some(_) if dry || settings::get().offline.value => {
392            format!("= dry setup {p} · would start a one-shot key form on 127.0.0.1 · $0")
393        }
394        Some(l) if gh(l).is_some_and(|k| settings::save_key(p, &k, None).is_ok()) => {
395            "= setup gh · copied the token of gh auth token into auth.json · $0".into()
396        }
397        Some(l) => return form(l),
398    };
399    Out::new(vec![said])
400}
401
402/// The free fetch switched off (`settings.json` `off`): its state (a summary's head) and its `setup` row, the state
403/// and the move back.
404pub fn free_off() -> (&'static str, String) {
405    let state = "free off (turned off)";
406    (state, format!("{state} → {} setup free on", bin()))
407}
408
409/// THE key shape on a command line: `line` with each key-shaped run of a word (`provider:<key>`, `"<key>"`) as its
410/// tail, `…6XBR`. A run is key-shaped at `key_chars` (limits.json) chars or more of `[A-Za-z0-9_+/=-]` (Decodo's
411/// token is base64) holding a letter and a digit; a word with `://` or a dot, or led by a `words.json`
412/// `path_lead` (`/`, `./`, `~`): a URL, a host, a path, a file, is left whole, and so is the binary's name (a test
413/// build's is long). A line holds a key when its masked copy differs (`key_in_argv`).
414pub fn masked(line: &str) -> String {
415    let key_char = |c: char| c.is_ascii_alphanumeric() || "_+/=-".contains(c);
416    let shaped = |r: &&str| {
417        let mixed = r.bytes().any(|c| c.is_ascii_digit()) && r.bytes().any(|c| c.is_ascii_alphabetic());
418        mixed && r.len() >= settings::limit::<usize>("key_chars") && *r != bin()
419    };
420    let word = |w: &str| {
421        let lead = crate::lang::WORDS.path_lead.iter().any(|l| w.starts_with(l));
422        if lead || w.contains("://") || w.contains('.') {
423            return w.to_string();
424        }
425        w.split(|c: char| !key_char(c)).filter(shaped).fold(w.to_string(), |w, r| w.replace(r, &crate::stats::tail(r)))
426    };
427    line.split(' ').map(word).collect::<Vec<_>>().join(" ")
428}
429
430/// The status line's keys, each by its tail, Bright Data's zone and the one file (≤ 100 cols): `keys oxy …6XBR · bd
431/// …k2Qf zone fatsrc · decodo none · gh none · auth.json`, then ` · network off` under `FATS_OFFLINE`; no key at all
432/// = what search needs and the key to add first (`keys none · search needs oxy or bd (…) → fats setup oxy`); ` · bak`
433/// last while `auth.json.bak` holds an old key (`bak_row`).
434pub fn keys_line() -> String {
435    let off = if settings::get().offline.value { " · network off" } else { "" };
436    let net = format!("{off}{}", if bak().is_some() { " · bak" } else { "" });
437    if no_keys() {
438        let all = crate::fetch::searchers();
439        let one = all.first().copied().unwrap_or_default();
440        let why = format!("search needs {} (one is enough; {one} costs least per search)", all.join(" or "));
441        return format!("keys none · {why} → {}{net}", crate::fetch::search_key());
442    }
443    let named = |p: &str| match (p, crate::stats::key(p)) {
444        ("bd", k) if k.starts_with('…') => format!("bd {k} zone {}", settings::zone().unwrap_or("none")),
445        (p, k) => format!("{p} {k}"),
446    };
447    let keys = SWITCHES.into_iter().filter(|p| *p != "free").map(named).collect::<Vec<_>>().join(" · ");
448    format!("keys {keys} · {}{net}", settings::AUTH)
449}
450
451/// No provider key saved, any switch (`gh` too).
452pub fn no_keys() -> bool {
453    settings::SWITCHES.into_iter().filter(|p| *p != "free").all(|p| settings::key(p).is_none())
454}
455
456/// The old `auth.json` a replaced or removed key leaves (`settings::save_to`), while it is there.
457pub fn bak() -> Option<PathBuf> {
458    let f = settings::key_file(&format!("{}.bak", settings::AUTH));
459    f.is_file().then_some(f)
460}
461
462/// Where a removed or switched-off key's old copy still is, and the move that deletes it (`rm`, the path quoted for
463/// a shell): `old key kept in auth.json.bak (0600) · delete it: rm '<path>'`. None = no backup.
464pub fn bak_row() -> Option<String> {
465    let path = bak()?.display().to_string().replace('\'', r"'\''");
466    Some(format!("old key kept in {}.bak (0600) · delete it: rm '{path}'", settings::AUTH))
467}
468
469/// The key the environment holds for `p` that fats does not use (`settings::env_key`, never sent), by tail (`fats`,
470/// `fats setup`): beside a different saved key, replaced only by a person; where none is saved it IS that
471/// provider's `no_key` row (`fats setup` drops its plain one), what `import-env` copies in.
472pub fn env_row(p: &str) -> Option<String> {
473    let ((var, env), b) = (settings::env_key(p)?, bin());
474    let env = crate::stats::tail(&env);
475    Some(match settings::key(p) {
476        Some(k) => format!("env {var} {env} ≠ saved {} · not used · replace: {b} setup {p}", crate::stats::tail(&k)),
477        None => bang("", "no_key", &format!("{p} · env {var} {env} not imported"), &At { arg: p, ..At::default() }),
478    })
479}
480
481/// `env_row` for every provider, and the proxy env plain ignores (`provider::proxy_note`): the status rows.
482pub fn env_rows() -> Vec<String> {
483    SWITCHES.into_iter().filter_map(env_row).chain(crate::provider::proxy_note().map(String::from)).collect()
484}
485
486/// THE argv key rule: a key-shaped word on a command line led by `setup` or a word people type for it (`login`,
487/// `keys`, `auth`: `words.json` `aliases`) is refused, never read, saved, echoed or searched (argv lands in shell
488/// history and `ps`; `fats login <key>` would be a search sending it to a provider); the key's ways in are the
489/// paste and the pipe. On any other command such a word is a word as typed (a sha, a part number).
490pub fn key_in_argv(cmd: &Cmd, argv: &[String]) -> Option<Out> {
491    // the first word, mods aside: read off `raw`, since a `?` for a later word, or a key making `login <key>` a
492    // search, leaves `reserved` empty
493    let lead = cmd.raw.split(' ').find(|t| !t.contains(':')).unwrap_or_default();
494    let alias = crate::lang::WORDS.aliases.iter().any(|a| a.1 == "setup" && a.0.eq_ignore_ascii_case(lead));
495    if !(alias || lead.eq_ignore_ascii_case("setup")) || argv.iter().all(|a| masked(a) == *a) {
496        return None;
497    }
498    let (b, p) = (bin(), cmd.raw.split(' ').find_map(links).map_or("oxy", |l| l.short));
499    let ways = format!("paste: {b} setup {p} · pipe: printf %s \"$KEY\" | {b} setup {p}");
500    let row = format!("! key_in_argv · never on the command line (shell history, ps) · {ways}");
501    Some(Out::fail("key_in_argv", "= ! key_in_argv setup · nothing read, nothing saved · $0".into(), row))
502}
503
504/// `fats setup <p>` fed a key on stdin (`printf %s "$KEY" | fats setup oxy`: SSH, CI, no browser): ONE line, its
505/// trailing CR/LF stripped, the menu's check ($0, `setup::check`), saved when it passes (a replaced key →
506/// `auth.json.bak`; the same key again replaces none); one line, rc 1 when nothing was saved (`FATS_OFFLINE`: no
507/// check). None = no provider named, stdin a terminal or `fats mcp`'s protocol, or no byte within 2 s (an agent's
508/// shell: `/dev/null`, a pipe never written): the key form.
509pub fn piped(cmd: &Cmd) -> Option<Out> {
510    let l = cmd.sub.first().and_then(|p| links(p)).filter(|_| cmd.has("setup") && cmd.sub.len() == 1)?;
511    if cmd.flag("dry") || std::io::IsTerminal::is_terminal(&std::io::stdin()) || crate::cli::FENCE.get().is_some() {
512        return None;
513    }
514    let (tx, rx) = std::sync::mpsc::channel();
515    std::thread::spawn(move || {
516        let mut line = Vec::new();
517        std::io::BufRead::read_until(&mut std::io::stdin().lock().take(16 << 10), b'\n', &mut line).ok();
518        tx.send(line).ok();
519    });
520    let line = rx.recv_timeout(Duration::from_secs(2)).ok().filter(|l| !l.is_empty())?;
521    let key = String::from_utf8_lossy(&line).trim_end_matches(['\r', '\n']).to_string();
522    let (p, b) = (l.short, bin());
523    let not_saved = |code: &'static str, why: &str| {
524        let row = format!("= ! {code} setup {p} · {why} · not saved → printf %s \"$KEY\" | {b} setup {p}");
525        Some(Out { rc: 1, ..Out::new(vec![row]).with("error", code) })
526    };
527    if settings::get().offline.value {
528        return not_saved("offline", "FATS_OFFLINE is on: no check (unset FATS_OFFLINE)");
529    }
530    // the old key goes to `auth.json.bak` only when the new one differs (`settings::save_to`)
531    let replaced = settings::key(p).is_some_and(|k| k != key.trim());
532    let kept = if replaced { " · the old key in auth.json.bak" } else { "" };
533    let (what, zones) = match check(l, &key) {
534        Ok(got) => got,
535        Err((code, why)) => return not_saved(code, &why),
536    };
537    let zone = if p == "bd" { pick_zone(&zones, None).ok() } else { None };
538    if let Err(e) = settings::save_key(p, &key, zone.as_deref()) {
539        return not_saved("cache_write", &e);
540    }
541    let pick = (p == "bd" && zone.is_none()).then(|| format!(" · no zone yet → {b} setup bd zone:<name>"));
542    let pick = pick.unwrap_or_default();
543    let what = key_row(what, zone.as_ref(), &key);
544    Some(Out::new(vec![format!("= setup {p} ok {what} saved auth.json (600){kept} · $0{pick}")]))
545}
546
547/// Bright Data's Web Unlocker zone from its zone names: `zone:`, else the configured one, else the only one.
548/// Err = the `! no_zone` row naming the account's unblocker zones.
549pub fn pick_zone(names: &[String], arg: Option<&str>) -> Result<String, String> {
550    let want = arg.or(settings::zone()).map(String::from);
551    match (want, names) {
552        (Some(w), _) if names.contains(&w) => Ok(w),
553        (None, [one]) => Ok(one.clone()),
554        (want, _) => {
555            let what = want.map_or("pick one".into(), |w| format!("{w} is not a Web Unlocker zone here"));
556            let list = if names.is_empty() { "none (add one in the control panel)".into() } else { names.join(", ") };
557            let arg = names.first().map_or("<name>", String::as_str);
558            let at = crate::lang::At { id: "setup", arg, ..Default::default() };
559            Err(crate::lang::bang("bd", "no_zone", &format!("{what} · unblocker zones: {list}"), &at))
560        }
561    }
562}
563
564/// A key form's run file `<session>/run/setup-<p>.<ext>`: `json` = token, port, deadline (the cache root is its
565/// owner's only, `cache::private_root`), there while the run serves (its port written once it listens) and after its
566/// deadline (`form_row`: dead), gone once a key is saved or the form is stopped; `log` = the run's output. The run
567/// serves only while this file holds its token (`serve`): removed or replaced by a new form's, the run exits.
568fn run_file(c: &Cache, p: &str, ext: &str) -> PathBuf {
569    c.root.join(&c.session).join("run").join(format!("setup-{p}.{ext}"))
570}
571
572#[derive(serde::Serialize, serde::Deserialize)]
573struct Form {
574    token: String,
575    until: f64,
576    port: u16,
577}
578
579/// Provider `p`'s key form that still waits: its URL. Its run must still answer on its port (within 200 ms): one
580/// killed before its deadline (a reboot, a killed process group) left a dead link behind.
581fn waiting_at(c: &Cache, p: &str) -> Option<String> {
582    let f: Form = jload(&run_file(c, p, "json")).filter(|f: &Form| f.port > 0 && f.until > now())?;
583    TcpStream::connect_timeout(&([127, 0, 0, 1], f.port).into(), Duration::from_millis(200)).ok()?;
584    Some(format!("http://127.0.0.1:{}/k/{}/{p}", f.port, f.token))
585}
586
587/// Provider `p`'s key form as `fats setup` reports it: one still waiting (its time left, its URL), or one whose time
588/// ran out with no key saved: the link the user got is dead.
589pub fn form_row(p: &str) -> Option<String> {
590    let c = Cache::open();
591    let f: Form = jload(&run_file(&c, p, "json")).filter(|f: &Form| f.port > 0)?;
592    let left = ((f.until - now()) / 60.0).ceil();
593    let dead =
594        || format!("! form_expired {p} · the link the user got is dead → {} setup {p} · new link, same 3 steps", bin());
595    Some(waiting_at(&c, p).map_or_else(dead, |url| format!("{p} form waiting · {left} min left · {url}")))
596}
597
598/// `fats setup <p> stop` and the menu's Stop the waiting form: ends `p`'s key form (its run file removed: the run
599/// exits within one 50 ms turn, `serve`), a dead one's file too; `dry` removes nothing. The words said; Err = the
600/// file is still there (the form still serves): what the remove said.
601pub fn stop(p: &str, dry: bool) -> Result<&'static str, String> {
602    let c = Cache::open();
603    let waiting = waiting_at(&c, p).is_some();
604    if dry {
605        return Ok(if waiting { "would stop the waiting form" } else { "no form waiting" });
606    }
607    let file = run_file(&c, p, "json");
608    match std::fs::remove_file(&file) {
609        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{}: {e}", file.display())),
610        _ => Ok(if waiting { "form stopped" } else { "no form waiting" }),
611    }
612}
613
614/// Way 2: the key form for `l`, served by a detached run (`--continue setup-<p>`, `serve`) on 127.0.0.1: the block
615/// the agent shows its user (`told`). One still waiting is shown again; a dead one is replaced.
616fn form(l: &'static Links) -> Out {
617    let (c, p) = (Cache::open(), l.short);
618    let ssh = crate::lang::WORDS.ssh.iter().any(|v| std::env::var_os(v).is_some());
619    let fill = |url: &str| told(l, url, ssh);
620    if let Some(url) = waiting_at(&c, p) {
621        return fill(&url);
622    }
623    let mut token = [0u8; 16];
624    let started = getrandom::fill(&mut token).map_err(|e| e.to_string()).and_then(|()| {
625        let token = token.iter().map(|x| format!("{x:02x}")).collect();
626        jsave(&run_file(&c, p, "json"), &Form { token, until: now() + LIFE, port: 0 })?;
627        crate::cli::detach(format!("setup-{p}"), &run_file(&c, p, "log"), None)
628    });
629    // the run binds its port and writes it: the URL exists once it listens
630    let up = || started.is_err() || waiting_at(&c, p).is_some();
631    (0..150).take_while(|_| !up()).for_each(|_| std::thread::sleep(Duration::from_millis(20))); // 3 s at most
632    let why = || format!("! setup_failed {}", started.as_ref().err().map_or("", String::as_str));
633    let failed = || Out::fail("setup_failed", format!("= setup {p} · ! setup_failed · $0"), why());
634    waiting_at(&c, p).map_or_else(failed, |url| fill(&url))
635}
636
637/// The block the agent shows its user: three numbered steps; the SSH way only over SSH (`ssh`), else an agent
638/// relays it as a fourth step.
639fn told(l: &'static Links, url: &str, ssh: bool) -> Out {
640    let block = format!("{}{}", page("agent"), if ssh { page("ssh") } else { "" });
641    let page = fill(&block, Some(l), &[("url", url), ("life", &format!("{}", LIFE / 60.0))]);
642    Out::new(page.lines().map(String::from).collect()).with("cost", 0.0)
643}
644
645/// The detached run of `fats setup <p>`: serves its form until one good key, `LIFE` or its run file no longer holds
646/// its token (`stop`, a new form), then exits. Exit code.
647pub fn serve(p: &str) -> i32 {
648    let c = Cache::open();
649    let (Some(l), Some(mut f)) = (links(p), jload::<Form>(&run_file(&c, p, "json"))) else { return 2 };
650    let Ok(lis) = TcpListener::bind("127.0.0.1:0") else { return 1 };
651    f.port = lis.local_addr().map_or(0, |a| a.port());
652    if jsave(&run_file(&c, p, "json"), &f).is_err() || lis.set_nonblocking(true).is_err() {
653        return 1;
654    }
655    while now() < f.until && jload::<Form>(&run_file(&c, p, "json")).is_some_and(|g| g.token == f.token) {
656        match lis.accept() {
657            // a key saved: no file = no form waits (one past its deadline stays: `form_row` says it is dead)
658            Ok((stream, _)) if answer(&stream, &f, l) => {
659                std::fs::remove_file(run_file(&c, p, "json")).ok();
660                break;
661            }
662            Ok(_) => {}
663            Err(_) => std::thread::sleep(Duration::from_millis(50)),
664        }
665    }
666    0
667}
668
669/// THE form's route rule: `Host` = `127.0.0.1:<port>` (else 400: DNS rebinding) and an `Origin`, when sent, the
670/// form's own (else 400: another page posting), then the page by GET and its `/save` by POST on the token path,
671/// nothing else (404); no CORS, no-store, a CSP that runs nothing. true = saved.
672fn answer(mut s: &TcpStream, f: &Form, l: &'static Links) -> bool {
673    s.set_nonblocking(false).ok();
674    s.set_read_timeout(Some(Duration::from_secs(5))).ok();
675    let mut r = std::io::BufReader::new(s.take(1 << 16));
676    let head: Vec<String> = (&mut r).lines().map_while(Result::ok).take_while(|l| !l.is_empty()).take(64).collect();
677    let get =
678        |h: &str| head.iter().skip(1).find_map(|l| Some(l.to_ascii_lowercase().strip_prefix(h)?.trim().to_string()));
679    let mut body = vec![0; get("content-length:").and_then(|v| v.parse().ok()).unwrap_or(0usize).min(16384)];
680    r.read_exact(&mut body).ok();
681    let (page, req) = (format!("/k/{}/{}", f.token, l.short), head.first().map_or("", String::as_str));
682    let (save, me) = (format!("{page}/save"), format!("127.0.0.1:{}", f.port));
683    let (code, html, done) = match req.split(' ').take(2).collect::<Vec<_>>()[..] {
684        _ if get("host:") != Some(me.clone()) || get("origin:").is_some_and(|o| o != format!("http://{me}")) => {
685            ("400 Bad Request", String::new(), false)
686        }
687        ["GET", at] if at == page => ("200 OK", html(l, 2, &[("save", &save), ("err", "")]), false),
688        ["POST", at] if at == save => post(l, &body, &save),
689        _ => ("404 Not Found", String::new(), false),
690    };
691    let head = fill(part(0), None, &[("code", code), ("len", &html.len().to_string())]).replace('\n', "\r\n");
692    s.write_all(format!("{head}{html}").as_bytes()).ok();
693    done
694}
695
696/// A POSTed key, checked ($0) and saved: the done page, else the form again with why.
697fn post(l: &'static Links, body: &[u8], save: &str) -> (&'static str, String, bool) {
698    let key =
699        url::form_urlencoded::parse(body).find(|(n, _)| n == "key").map_or(String::new(), |(_, v)| v.trim().into());
700    let saved = check(l, &key).map_err(|e| e.1).and_then(|(what, zones)| {
701        let (page, zone) = landed(l, &what, &zones);
702        settings::save_key(l.short, &key, zone.as_deref()).map(|()| page)
703    });
704    match saved.map_err(|e| format!("<p class=bad>! {} · try again</p>", esc(&e))) {
705        Ok(what) => ("200 OK", html(l, 3, &[("what", &what)]), true),
706        Err(bad) => ("200 OK", html(l, 2, &[("save", save), ("err", &bad)]), false),
707    }
708}
709
710/// The done page's line for a key that passed `check`, and Bright Data's zone saved with it: the configured one
711/// or the account's only one (`pick_zone`); else the zones named and the move the agent makes.
712fn landed(l: &Links, what: &str, zones: &[String]) -> (String, Option<String>) {
713    let (b, works, done) = (bin(), format!("<b>{} works</b>", l.name), "go back to your agent and say <b>done</b>");
714    match (l.short == "bd").then(|| pick_zone(zones, None)) {
715        Some(Err(_)) => {
716            let fix = format!("tell your agent: <b>{b} setup bd zone:&lt;name&gt;</b>");
717            (format!("<b>key saved</b> · ✗ no zone yet → {fix} · zones: {}", esc(&zones.join(", "))), None)
718        }
719        Some(Ok(z)) => (format!("{works} · zone {} · {done}", esc(&z)), Some(z)),
720        None => (format!("{works} · {} · {done}", esc(what)), None),
721    }
722}
723
724/// Part `n` of the form page (2 key, 3 done, `part`) in its frame, `vars` filled in.
725fn html(l: &Links, n: usize, vars: &[(&str, &str)]) -> String {
726    fill(part(1), Some(l), &[("body", &fill(part(n), None, vars))])
727}
728
729/// Part `n` of `setup-form.html`: 0 the HTTP head, 1 the page's frame, 2 the key form, 3 done.
730fn part(n: usize) -> &'static str {
731    FORM.split("<!-- -->\n").nth(n).unwrap_or_default()
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737
738    thread_local! {
739        /// Every frame `Term::draw` painted on this thread, in order.
740        pub(super) static FRAMES: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
741    }
742
743    /// Key `i` of a number row (`1` … `9`): it picks row or button `i`.
744    fn digit(i: usize) -> &'static [u8] {
745        &b"123456789"[i..=i]
746    }
747    /// Esc as the terminal sends it: back one list.
748    const ESC: &[u8] = b"\x1b";
749
750    /// One scripted walk from the main list: every key read, the done line, no frame's message a refusal and
751    /// every menu row within 100 columns. The frames drawn, without colour.
752    fn walked(script: Vec<&'static [u8]>, what: &str) -> Vec<String> {
753        FRAMES.with_borrow_mut(Vec::clear);
754        let mut t = Term(None, script.into());
755        let done = walk(&mut t, None);
756        assert!(t.1.is_empty() && done.starts_with("= setup done · "), "{what}: keys left {:?} · {done}", t.1);
757        let frames = FRAMES.take();
758        let lines = || frames.iter().flat_map(|f| f.lines()).map(str::trim_end);
759        let refused = lines().find(|l| l.trim_start().starts_with("✗ Can't"));
760        assert!(refused.is_none(), "{what}: a shown button answered {refused:?}");
761        let row =
762            |l: &&str| l.trim_start_matches([' ', '▸']).split_once(". ").is_some_and(|(n, _)| n.parse::<u8>().is_ok());
763        let wide: Vec<&str> = lines().filter(row).filter(|l| l.chars().count() > 100).collect();
764        assert!(wide.is_empty(), "{what}: rows over 100 columns {wide:?}");
765        frames
766    }
767
768    /// Every button on every screen works, in a keyless install, with Oxylabs and Bright Data keys, and with only
769    /// an Oxylabs key and the free fetch off: from the main list (`rows`) and Settings (`SETTINGS`), every row by
770    /// its number, then every button its screen shows (`buttons`), each from the state's files in this thread's own
771    /// key dir (fake keys, no network: a key that needs a provider's check is pasted as an empty line = back), then
772    /// q to the done line (`walked`; ← Back is a button, Esc leaves Settings). A switch pressed twice shows its new
773    /// state at once and ends as it began; a key saved keeps its screen.
774    #[test]
775    fn every_button_on_every_screen_works() {
776        let keys = crate::scratch::Scratch::new("setup-buttons");
777        settings::tests::KEY_DIR.set(Some(keys.to_path_buf()));
778        crate::lang::tests::NO_COLOR.set(Some(true));
779        let states: [(&[&str], bool); 3] = [(&[], true), (&["oxy", "bd"], true), (&["oxy"], false)];
780        for (keyed, free) in states {
781            // the state's two files, written as they are read (`settings::Saved`)
782            let reset = || {
783                let keys_of = keyed.iter().map(|k| (k.to_string(), "fake-key-0123456789".to_string())).collect();
784                let off = if free { vec![] } else { vec!["free".to_string()] };
785                let files = [(settings::AUTH, keys_of, vec![]), (settings::PREFS, Default::default(), off)];
786                for (f, keys_of, off) in files {
787                    let saved = settings::Saved { version: 1, keys: keys_of, off, ..Default::default() };
788                    std::fs::write(keys.join(f), serde_json::to_vec(&saved).expect("json")).expect("write");
789                }
790            };
791            let mut at: Vec<(Vec<&'static [u8]>, &str)> = Vec::new();
792            for (i, p) in rows().into_iter().enumerate() {
793                at.push((vec![digit(i)], p));
794                let inner = SETTINGS.into_iter().enumerate().map(|(j, s)| (vec![digit(i), digit(j)], s));
795                at.extend(inner.filter(|_| p == "settings"));
796            }
797            for (to, p) in at {
798                reset();
799                let what = format!("{keyed:?} free {free} · {p}");
800                // a row with a screen: each of its buttons; else the row alone (Settings left by Esc, a row that only
801                // shows stays, Done and Back leave the list)
802                let out: &[&[u8]] = match p {
803                    "done" => &[],
804                    "settings" => &[ESC, b"q"],
805                    "back" | "cache" | "stats" => &[b"q"],
806                    _ => {
807                        buttons(p).iter().enumerate().for_each(|(k, b)| press(&reset, &to, p, k, b, &what));
808                        continue;
809                    }
810                };
811                walked([&to[..], out].concat(), &what);
812            }
813        }
814        settings::tests::KEY_DIR.set(None);
815        crate::lang::tests::NO_COLOR.set(None);
816    }
817
818    /// Button `b`, the `k`-th on screen `p` reached by `to`, pressed from the state `reset` makes, and what it did
819    /// checked.
820    fn press(reset: &dyn Fn(), to: &[&'static [u8]], p: &str, k: usize, b: &str, what: &str) {
821        reset();
822        let what = &format!("{what} · {b}");
823        let (on, no_check) = (settings::on(p), !crate::provider::KEYS.into_iter().any(|t| t.spec().short == p));
824        // a paste arrives as one read, its line end too (`\r\n`): the `\n` must not press the next screen's Enter
825        let pasted: &[u8] = if no_check { b"fake-gh-token-0123\r\n" } else { b"\r\n" };
826        let then: &[&[u8]] = match b {
827            "Add a key" | "Paste a new key" => &[pasted, b"q"],
828            "Turn on" | "Turn off" => &[digit(k), b"q"], // pressed again
829            _ => &[b"q"],
830        };
831        let frames = walked([to, &[digit(k)], then].concat(), what);
832        let keyless = links(p).is_some() && settings::key(p).is_none() && b == "Add a key";
833        assert!(!keyless || frames.iter().any(|f| f.contains("│ Status  no key")), "{what}: Status no key");
834        let level = LEVELS.iter().find(|l| l.1 == b).map(|l| serde_json::Value::from(l.0.name()));
835        match b {
836            "Turn on" | "Turn off" => {
837                let flip = format!("{}. {}", k + 1, ["Turn off", "Turn on"][usize::from(b == "Turn off")]);
838                let shown = frames.iter().find(|f| f.contains(&flip));
839                assert!(shown.is_some_and(|f| f.contains("│ Status  off") == on), "{what}: {flip} at once");
840                assert_eq!(settings::on(p), on, "{what}: pressed twice, as it began");
841            }
842            "Remove this key" => {
843                assert!(settings::key(p).is_none(), "{what}: the key is gone");
844                // the removed key's old copy and the move that deletes it, said on the screen it was removed from
845                let bak = "○ key removed · old key kept in auth.json.bak (0600) · delete it: rm '";
846                assert!(frames.iter().any(|f| f.contains(bak)), "{what}: the backup named");
847            }
848            "Add a key" | "Paste a new key" if no_check => pasted_frames(&frames, 18, what),
849            // the add's own row inline (dry here: a unit test edits no host config)
850            _ if b.starts_with("Add to ") => {
851                let said = |f: &&String| {
852                    f.contains("   = dry setup mcp ") || f.contains("   = setup mcp ") || f.contains("   ! no_host ")
853                };
854                assert!(frames.iter().any(|f| said(&f)), "{what}: the add's row");
855            }
856            _ if level.is_some() => assert_eq!(settings::saved(settings::PREFS).set.get("telemetry"), level.as_ref()),
857            _ => {}
858        }
859    }
860
861    /// The frames of an `n`-byte key pasted with `\r\n` (`Term::secret`): one prompt (0 chars), then one frame a
862    /// byte with that many mask glyphs and the count, no key byte in any frame; then the check, then the provider's
863    /// screen with the key's tail saved (the `\n` pressed nothing: one prompt only).
864    fn pasted_frames(frames: &[String], n: usize, what: &str) {
865        let at = frames.iter().position(|f| f.contains("   0 chars")).unwrap_or(frames.len());
866        for (i, f) in frames.iter().skip(at).take(n + 1).enumerate() {
867            let mask = format!("\n   {}  {i} chars\r", "•".repeat(i));
868            assert!(f.contains(&mask), "{what}: byte {i} draws its mask: {f}");
869        }
870        assert!(!frames.iter().any(|f| f.contains("fake-gh") || f.contains("token-0")), "{what}: a key byte shown");
871        assert_eq!(frames.iter().filter(|f| f.contains("   0 chars")).count(), 1, "{what}: the \\n pressed Enter");
872        let (check, screen) = (frames.get(at + n + 1), frames.get(at + n + 2));
873        assert!(check.is_some_and(|f| f.contains("… checking the key with ")), "{what}: {check:?}");
874        let saved =
875            screen.is_some_and(|f| f.contains(" works · unchecked · key …0123 saved") && f.contains(". Paste a"));
876        assert!(saved && settings::key("gh").as_deref() == Some("fake-gh-token-0123"), "{what}: {screen:?}");
877    }
878
879    /// A frame is in colour (`lang::paint` styles): the marks (✓ green), the marked row bold around them, the
880    /// headings bold; under `NO_COLOR` not one escape.
881    #[test]
882    fn a_frame_is_in_colour_unless_no_color() {
883        let t = Term(None, Default::default());
884        let frame = |plain| {
885            crate::lang::tests::NO_COLOR.set(Some(plain));
886            t.draw(&text("oxy"), "✓ Oxylabs Web API works", &["   ▸ 1. ✓ Free fetch".into()], "q quit");
887            FRAMES.with_borrow_mut(Vec::pop).unwrap_or_default()
888        };
889        let (colour, plain) = (frame(false), frame(true));
890        crate::lang::tests::NO_COLOR.set(None);
891        assert!(colour.contains("\x1b[32m✓\x1b[0m Oxylabs Web API works"), "{colour:?}");
892        assert!(colour.contains("\x1b[1m   ▸ 1. \x1b[32m✓\x1b[0m\x1b[1m Free fetch\x1b[0m"), "{colour:?}");
893        assert!(colour.contains("\x1b[1mHow it works\x1b[0m") && colour.contains("\x1b[2mq quit\x1b[0m"));
894        assert!(!plain.contains('\x1b') && plain.contains("   ▸ 1. ✓ Free fetch") && plain.contains("How it works"));
895    }
896
897    /// The key prompt on raw reads: ⌫ takes a byte back, a space or a control byte is no key byte, Enter ends it
898    /// (the rest of that read dropped), Esc, ^C, no bytes or Enter alone = back; a frame shows the count only.
899    #[test]
900    fn the_key_prompt_masks_and_edits() {
901        let key = |script: Vec<&'static [u8]>| {
902            FRAMES.with_borrow_mut(Vec::clear);
903            let mut t = Term(None, script.into());
904            (t.secret(&text("oxy"), ""), t.1.len(), FRAMES.take())
905        };
906        let (got, left, frames) = key(vec![b"ab\x7fc d\t", b"e\r\nq", b"z"]);
907        assert_eq!((got.as_deref(), left), (Some("acde"), 1), "the next read is the menu's");
908        assert_eq!(frames.len(), 9, "the prompt, then a frame a byte before Enter");
909        let shown: Vec<usize> = [0, 1, 2, 1, 2, 2, 3, 3, 4].into();
910        for (f, n) in frames.iter().zip(shown) {
911            assert!(f.contains(&format!("\n   {}  {n} chars\r", "•".repeat(n))) && !f.contains("acde"), "{f}");
912        }
913        for script in [vec![&b"abc\x1b"[..]], vec![b"abc\x03"], vec![b"abc"], vec![b"\r"]] {
914            assert_eq!(key(script).0, None, "back");
915        }
916    }
917
918    /// The menu state machine on raw reads: moves wrap (both arrow encodings), a number jumps and picks, Enter or
919    /// → picks, Esc/←/⌫ back, q, ^C or no bytes quit.
920    #[test]
921    fn menu_steps() {
922        let up = (step(0, 3, b"\x1b[A"), step(0, 3, b"\x1bOA"), step(2, 3, b"\x1b[B"), step(1, 3, b"j"));
923        assert_eq!(up, ((2, None), (2, None), (0, None), (2, None)));
924        let pick = (step(1, 3, b"\r"), step(1, 3, b"\x1b[C"), step(0, 3, b"3"), step(0, 3, b"4"));
925        assert_eq!(pick, ((1, Some('\r')), (1, Some('\r')), (2, Some('\r')), (0, None)));
926        let back = (step(0, 3, b"\x1b"), step(0, 3, b"\x1b[D"), step(0, 3, b"\x7f"), step(0, 3, b"q"));
927        assert_eq!(back, ((0, Some('\x1b')), (0, Some('\x1b')), (0, Some('\x1b')), (0, Some('q'))));
928        assert_eq!(
929            (step(1, 3, b"s"), step(1, 3, b"\x03"), step(1, 3, b"")),
930            ((1, None), (1, Some('q')), (1, Some('q')))
931        );
932    }
933
934    /// Way 1 driven by a scripted key source: into Oxylabs' screen and back, Settings by its number, the agent
935    /// screen and back twice, then q: every key used, the done line printed. Reads settings only (no row that
936    /// saves, opens or copies).
937    #[test]
938    fn a_scripted_walk_ends_with_the_done_line() {
939        let script: [&[u8]; 10] =
940            [b"\x1b[B", b"\r", b"\x1b", b"6", b"\r", b"\x1b", b"\x1b[D", b"\x1bOA", b"\x1bOA", b"q"];
941        FRAMES.with_borrow_mut(Vec::clear);
942        let mut t = Term(None, script.into());
943        let done = walk(&mut t, None);
944        assert!(t.1.is_empty(), "every key read: {:?}", t.1);
945        assert!(done.starts_with("= setup done · ✓ free ") && done.ends_with(" example.com"), "{done}");
946        // ← on the main list quits (no list above it), its footer says so; Settings' ← goes back
947        let frames = FRAMES.take();
948        assert!(frames.first().is_some_and(|f| f.contains("· ← or q quit")), "{:?}", frames.first());
949        assert!(frames.iter().any(|f| f.contains("Agent connection (MCP)") && f.contains("· ← back · q quit")));
950        let mut t = Term(None, [&b"\x1b"[..], b"q"].into());
951        assert!(walk(&mut t, Some("bd")).starts_with("= setup done") && t.1.is_empty(), "bd's screen, back, q");
952    }
953
954    /// The main list: providers, then Settings and Done each under an empty line; Settings lists the agent
955    /// connection, Cache, Stats and Telemetry, then Back under an empty line; Telemetry's On saves `full`. Unit
956    /// tests share one scratch settings file across processes: this one saves only `full`, the level the others
957    /// read already (`off` there turned `weekly_counts_codes_only`'s tally off mid-run).
958    #[test]
959    fn settings_hold_cache_stats_and_telemetry() {
960        let row = |p: &&str| text(p)[0].clone();
961        assert_eq!(
962            SETTINGS.iter().map(row).collect::<Vec<_>>(),
963            ["Agent connection (MCP)", "Cache", "Stats", "Telemetry", "← Back"]
964        );
965        let row = state("cache").1;
966        assert!(row.contains(" pages, ") && row.ends_with("B · live ≤ 1 h"), "{row}");
967        let card = text("cache").into_iter().find(|l| l.contains("Status")).unwrap_or_default();
968        assert!(card.contains(" · pages live ≤ 1 h (30 min unread) · "), "{card}");
969        assert!(state("stats").1.starts_with("this session: 0 pages · $0"), "{}", state("stats").1);
970        assert!(state("telemetry").1.ends_with(" · anonymous usage stats, to fix and improve fats"));
971        // Settings (6), Telemetry (4), On (1), then back out and q
972        let mut t = Term(None, [&b"6"[..], b"4", b"1", b"\x1b", b"\x1b", b"q"].into());
973        let done = walk(&mut t, None);
974        let saved = settings::saved(settings::PREFS).set.get("telemetry").cloned();
975        settings::unset("telemetry").expect("unset");
976        assert!(t.1.is_empty() && done.starts_with("= setup done"), "{:?} {done}", t.1);
977        assert_eq!(saved, Some("full".into()), "the option's level stored, never its label");
978    }
979
980    /// A menu row fits 100 columns with a long cache dir (a scratch HOME under the temp dir): the row shortens the
981    /// dir, `~` for home and the middle parts as `…`; the card's Status keeps it whole.
982    #[test]
983    fn the_cache_row_fits_100_columns() {
984        // the OS's own separator, as the dirs it gets (`C:\Users\…\AppData\Local\fatsearch`)
985        let os = |p: &str| p.replace('/', std::path::MAIN_SEPARATOR_STR);
986        let tmp = os("/var/folders/s8/5n29mppx4z54b1vrnn6zpkrh0000gn/T/tmp.qXxiDel2af");
987        let dir = PathBuf::from(os(&format!("{tmp}/Library/Caches/fatsearch")));
988        assert!(dir.display().to_string().chars().count() >= 60);
989        let (row, card) = cache_words(&dir);
990        let line = format!("   ▸ 2.   {:18} {row}", "Cache");
991        assert!(line.chars().count() <= 100, "{} chars: {line}", line.chars().count());
992        assert!(
993            row.starts_with(&os("/var/folders/…/Caches/fatsearch · ")) && card.starts_with(&os(&format!("{tmp}/"))),
994            "{row}"
995        );
996        let home = Path::new(&tmp);
997        assert_eq!(row_path(&dir, Some(home)), os("~/Library/Caches/fatsearch"));
998        assert_eq!(row_path(Path::new("/srv/fats"), Some(home)), "/srv/fats", "a short dir stays whole");
999        let main = ["free", "oxy", "decodo", "bd", "gh", "settings", "done"];
1000        let row = |p: &&str| format!("   ▸ 2. {} {:18} {}", state(p).0, text(p)[0], state(p).1);
1001        let wide: Vec<String> = main.iter().chain(&SETTINGS).map(row).filter(|r| r.chars().count() > 100).collect();
1002        assert!(wide.is_empty(), "rows over 100 columns: {wide:?}");
1003    }
1004
1005    /// A provider's screen shows Stop the waiting form only while its form answers on its port; pressed, the form's
1006    /// run file is gone (its run exits on that), the screen says so and the button goes.
1007    #[test]
1008    fn a_waiting_form_has_a_stop_button() {
1009        let (c, stop) = (Cache::open(), "Stop the waiting form");
1010        let run = TcpListener::bind("127.0.0.1:0").expect("bind");
1011        let port = run.local_addr().expect("port").port();
1012        let file = run_file(&c, "decodo", "json");
1013        std::fs::create_dir_all(file.parent().expect("run dir")).expect("run dir");
1014        assert!(!buttons("decodo").contains(&stop.into()), "no form, no button");
1015        jsave(&file, &Form { token: "ab12".into(), until: now() + 600.0, port }).expect("form");
1016        let shown = buttons("decodo");
1017        let (i, k) = (rows().iter().position(|p| *p == "decodo"), shown.iter().position(|b| *b == stop));
1018        let (Some(i), Some(k)) = (i, k) else { panic!("{shown:?}") };
1019        crate::lang::tests::NO_COLOR.set(Some(true));
1020        let frames = walked(vec![digit(i), digit(k), b"q"], "stop");
1021        crate::lang::tests::NO_COLOR.set(None);
1022        assert!(frames.iter().any(|f| f.contains("   ✓ form stopped")) && !file.exists(), "the run file is gone");
1023        assert!(!buttons("decodo").contains(&stop.into()), "the button goes with the form");
1024    }
1025
1026    /// A Bright Data key with zones but none picked: saved, the page names the zones and the agent's move;
1027    /// the account's only zone is saved with the key.
1028    #[test]
1029    fn a_bd_key_without_its_zone_names_the_move() {
1030        let (bd, zones) = (links("bd").expect("bd"), ["web_unlocker1".to_string(), "cli_unlocker".into()]);
1031        let (page, zone) = landed(bd, "", &zones);
1032        let tail = " setup bd zone:&lt;name&gt;</b> · zones: web_unlocker1, cli_unlocker";
1033        assert!(zone.is_none() && page.starts_with("<b>key saved</b> · ✗ no zone yet → tell your agent: <b>"));
1034        assert!(page.ends_with(tail), "{page}");
1035        assert_eq!(landed(bd, "", &zones[..1]).1.as_deref(), Some("web_unlocker1"), "the only zone is saved");
1036    }
1037
1038    #[test]
1039    fn screens_and_form_parts() {
1040        let l = links("oxy").expect("oxy");
1041        // the user's part of `fats setup oxy`: three numbered steps, the SSH way only over SSH
1042        let steps =
1043            |o: &Out| o.lines.iter().filter(|r| r.starts_with(['1', '2', '3']) && r[1..].starts_with(". ")).count();
1044        let (here, ssh) = (told(l, "http://127.0.0.1:1/k/t/oxy", false), told(l, "http://127.0.0.1:1/k/t/oxy", true));
1045        assert!(steps(&here) == 3 && !here.lines.iter().any(|r| r.contains("SSH")), "{:?}", here.lines);
1046        assert!(
1047            steps(&ssh) == 3 && ssh.lines.last().is_some_and(|r| r.contains("(SSH)? the user runs")),
1048            "{:?}",
1049            ssh.lines
1050        );
1051        // the agent's last lines: what to do when the 30 min passed, how to end the form (the SSH way after them,
1052        // only over SSH)
1053        let dead = "link dead (30 min passed)? run fats setup oxy again and give the user the new line 3";
1054        let stop = "no key coming (the user stopped)? fats setup oxy stop ends the form, $0";
1055        let last: Vec<String> = here.lines.iter().rev().take(2).map(|r| r.replace(bin(), "fats")).collect();
1056        assert_eq!(last, [stop, dead], "{:?}", here.lines);
1057        assert!(
1058            here.lines[0].ends_with(" · 30 min · $0")
1059                && ssh.lines.iter().rev().nth(1).is_some_and(|r| r.starts_with("no key coming"))
1060        );
1061        let page = html(l, 2, &[("save", "/k/t/oxy/save"), ("err", "")]);
1062        assert!(page.contains("action=\"/k/t/oxy/save\"") && page.contains(l.mint) && !page.contains("<script"));
1063        let done = html(l, 3, &[("what", &landed(l, "351 scrapers", &[]).0)]);
1064        assert!(
1065            done.contains(
1066                "<p><b>Oxylabs Web API works</b> · 351 scrapers · go back to your agent and say <b>done</b>."
1067            )
1068        );
1069        let order: Vec<&str> = PROVIDERS.links.iter().map(|l| l.short).collect();
1070        assert_eq!(order, ["oxy", "decodo", "bd", "gh"], "the list's rank order");
1071        // a rank is a dated measurement, and only one provider is #1 (the card and the list render it)
1072        let ranks: Vec<_> = order.iter().map(|p| state(p).1).filter(|r| r.contains("#1")).collect();
1073        assert_eq!(ranks, ["#1 · 14/19 hard pages (median of 9 runs, 12–16, 2026-10-15)"], "{ranks:?}");
1074        assert!(
1075            text("oxy")
1076                .iter()
1077                .any(|l| l.ends_with("Rank    #1 · 14/19 hard pages (median of 9 runs, 12–16, 2026-10-15)"))
1078        );
1079        for p in ["free", "oxy", "decodo", "bd", "gh", "settings", "mcp", "cache", "stats", "telemetry", "back", "done"]
1080        {
1081            assert_eq!(text(p).get(6).map(String::as_str), Some(" ╰─"), "{p}: the card is 4 rows, every screen");
1082        }
1083        let hosts: Vec<String> = text("mcp").into_iter().skip(7).filter(|r| r.contains("mcp add")).collect();
1084        assert_eq!(hosts.len(), 2, "Claude Code and Codex lines, from the one HOSTS table");
1085        assert_eq!(esc("<a\"&>"), "&lt;a&quot;&amp;&gt;");
1086    }
1087}