tail-fin-cli-core 0.7.8

Shared CLI/daemon helpers for tail-fin: Ctx, browser session builders, cookie-path resolution, JSON output. Consumed by tail-fin-cli and tail-fin-daemon.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Shared helpers for the tail-fin CLI and daemon.
//!
//! This crate holds the CLI-adjacent plumbing that both the standalone
//! `tail-fin` binary and the `tfd` daemon need: optionally building a browser
//! session from a `--connect` host, resolving cookie file paths, and emitting
//! JSON/list responses. Site-specific logic does **not** live here — each
//! adapter crate owns its own Site impl + command handlers.
//!
//! Browser session helpers are gated behind the `browser` feature.

use std::path::PathBuf;

use tail_fin_common::TailFinError;

/// Unlink a stale chromiumoxide default-profile SingletonLock if it
/// points to a dead PID. No-op if the lock doesn't exist, points to a
/// live process, or is on a platform we don't need to handle.
///
/// Call this once at CLI startup so a prior tail-fin invocation that
/// died mid-launch can't block the current one. It's a symlink unlink,
/// not a profile-dir removal — the dir itself is safe to keep.
#[cfg(unix)]
pub fn reap_stale_default_profile_lock() {
    let temp = std::env::var_os("TMPDIR").unwrap_or_else(|| "/tmp".into());
    let lock = std::path::Path::new(&temp)
        .join("chromiumoxide-runner")
        .join("SingletonLock");

    let Ok(target) = std::fs::read_link(&lock) else {
        return;
    };
    let target_str = target.to_string_lossy();
    let Some(pid_str) = target_str.rsplit('-').next() else {
        return;
    };
    let Ok(pid) = pid_str.parse::<i32>() else {
        return;
    };
    // Reject non-positive and PID 1. `kill -0 0` targets our process
    // group, `kill -0 -1` targets every process we can signal, `kill -0
    // 1` targets init/launchd (non-root gets EPERM on macOS). None of
    // those answer the question "is the process that minted this lock
    // still around?" so we must not reap based on them.
    if pid <= 1 {
        return;
    }

    // `kill -0 <pid>` distinguishes:
    //   success       → target is alive AND we can signal it
    //   ESRCH         → no such process — definitely stale
    //   EPERM         → process exists but we can't signal it (owned by
    //                   another user). We treat this as "dead" too: our
    //                   default profile is per-user on Unix, so a lock
    //                   pointing at another user's PID is already
    //                   nonsense, and reaping it unblocks us.
    // We don't inspect errno (Command doesn't expose it cheaply); both
    // non-success exits collapse to "not alive for our purposes".
    let alive = std::process::Command::new("kill")
        .args(["-0", &pid.to_string()])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);

    if !alive {
        let _ = std::fs::remove_file(&lock);
    }
}

/// No-op on non-unix platforms.
#[cfg(not(unix))]
pub fn reap_stale_default_profile_lock() {}

/// Build a user-facing error for missing connection mode.
pub fn no_mode_error(service: &str, cmd: &str) -> TailFinError {
    TailFinError::Api(format!(
        "No connection mode specified for {service}.\n\
         \x20 Use --connect to use browser mode:\n\
         \x20   tail-fin --connect 127.0.0.1:9222 {service} {cmd}\n\
         \x20 Or --cookies to use saved cookies:\n\
         \x20   tail-fin --cookies auto {service} {cmd}\n\
         \x20 Some adapters (e.g. spotify) auto-launch a stealth browser when no mode is given."
    ))
}

/// Connection-mode context shared across CLI subcommands and the REPL.
pub struct Ctx {
    pub connect: Option<String>,
    pub cookies: Option<String>,
    pub headed: bool,
}

/// Default cookies path for a given site: `~/.tail-fin/<site>-cookies.txt`.
pub fn default_cookies_path(site: &str) -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home)
        .join(".tail-fin")
        .join(format!("{}-cookies.txt", site))
}

/// Default JSON credentials path for a given site: `~/.tail-fin/<site>-creds.json`.
pub fn default_creds_path(site: &str) -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home)
        .join(".tail-fin")
        .join(format!("{}-creds.json", site))
}

/// Resolve the cookies file path from the `--cookies` flag value.
/// `"auto"` expands to [`default_cookies_path`]; anything else is verbatim.
pub fn resolve_cookies_path(cookies_flag: &str, site: &str) -> PathBuf {
    if cookies_flag == "auto" {
        default_cookies_path(site)
    } else {
        PathBuf::from(cookies_flag)
    }
}

/// Connect to an existing Chrome instance via CDP at `ws://{host}`.
#[cfg(feature = "browser")]
pub async fn browser_session(
    host: &str,
    headed: bool,
) -> Result<night_fury_core::BrowserSession, TailFinError> {
    Ok(night_fury_core::BrowserSession::builder()
        .connect_to(format!("ws://{}", host))
        .headed(headed)
        .build()
        .await?)
}

/// Launch a fresh headless (or headed) browser — no existing Chrome required.
///
/// Returns `(profile_dir, session)`. The `TempDir` is first in the tuple
/// so the idiomatic `let (_profile, session) = launch_browser(...).await?`
/// binding declares `_profile` before `session`. Rust drops locals in
/// reverse declaration order, so `session` is dropped first (giving
/// Chromium time to tear down) and `_profile` is dropped second
/// (unlinking the profile dir only after Chromium is gone).
#[cfg(feature = "browser")]
pub async fn launch_browser(
    headed: bool,
) -> Result<(tempfile::TempDir, night_fury_core::BrowserSession), TailFinError> {
    launch_with_tempdir(headed).await
}

/// Auto-launch a stealth browser session when no connection mode is
/// specified. Adapters that support browser-only mode use this as their
/// fallback path. Emits a stderr notice before launching.
///
/// Returns `(profile_dir, session)`. See [`launch_browser`] for the
/// drop-order rationale behind the tuple shape.
#[cfg(feature = "browser")]
pub async fn auto_launch_stealth(
    url: &str,
    headed: bool,
) -> Result<(tempfile::TempDir, night_fury_core::BrowserSession), TailFinError> {
    eprintln!("No connection mode specified. Launching stealth browser...");
    launch_stealth_with_tempdir(url, headed, Some(std::time::Duration::from_secs(30))).await
}

/// Launch a stealth browser navigated to `url` with anti-detection.
/// Returns `(profile_dir, session)`; see [`launch_browser`] for the
/// drop-order rationale.
#[cfg(feature = "browser")]
pub async fn launch_stealth_session(
    url: &str,
    headed: bool,
) -> Result<(tempfile::TempDir, night_fury_core::BrowserSession), TailFinError> {
    launch_stealth_with_tempdir(url, headed, None).await
}

/// Like [`launch_stealth_session`] but blocks until Cloudflare clears (or
/// the timeout elapses). Use this from long-running services (e.g. the
/// `tfd` daemon's `--host auto` path) where the next request hits the
/// network *immediately* and must not race the CF interstitial.
///
/// Returns `(profile_dir, session)`; see [`launch_browser`] for the
/// drop-order rationale behind the tuple shape.
#[cfg(feature = "browser")]
pub async fn launch_stealth_session_blocking_cf(
    url: &str,
    headed: bool,
    cloudflare_timeout: std::time::Duration,
) -> Result<(tempfile::TempDir, night_fury_core::BrowserSession), TailFinError> {
    launch_stealth_with_tempdir(url, headed, Some(cloudflare_timeout)).await
}

#[cfg(feature = "browser")]
fn profile_tempdir() -> Result<tempfile::TempDir, TailFinError> {
    tempfile::Builder::new()
        .prefix("tail-fin-cli-")
        .tempdir()
        .map_err(|e| TailFinError::Api(format!("failed to create chromium profile tempdir: {e}")))
}

/// Shared inner: build an isolated Chromium profile, launch a non-stealth
/// browser, and return the tuple that keeps the profile alive.
#[cfg(feature = "browser")]
async fn launch_with_tempdir(
    headed: bool,
) -> Result<(tempfile::TempDir, night_fury_core::BrowserSession), TailFinError> {
    let profile_dir = profile_tempdir()?;
    let user_data_arg = format!("--user-data-dir={}", profile_dir.path().display());
    let session = night_fury_core::BrowserSession::builder()
        .headed(headed)
        .arg(user_data_arg)
        .build()
        .await?;
    Ok((profile_dir, session))
}

/// Shared inner: build an isolated Chromium profile, launch stealth,
/// return the tuple that keeps the profile alive for the session's
/// lifetime.
#[cfg(feature = "browser")]
async fn launch_stealth_with_tempdir(
    url: &str,
    headed: bool,
    cloudflare_timeout: Option<std::time::Duration>,
) -> Result<(tempfile::TempDir, night_fury_core::BrowserSession), TailFinError> {
    let profile_dir = profile_tempdir()?;
    let user_data_arg = format!("--user-data-dir={}", profile_dir.path().display());

    let mut builder = night_fury_core::BrowserSession::builder()
        .headed(headed)
        .arg(user_data_arg);
    if let Some(t) = cloudflare_timeout {
        builder = builder.cloudflare_timeout(t);
    }

    let session = builder.launch_stealth(url).await?;
    Ok((profile_dir, session))
}

/// Require `--connect` and return the host, or a friendly error pointing at
/// the correct invocation.
pub fn require_browser(
    connect: &Option<String>,
    service: &str,
    action_name: &str,
) -> Result<String, TailFinError> {
    match connect {
        Some(host) => Ok(host.clone()),
        None => Err(TailFinError::Api(format!(
            "`{service} {action_name}` requires browser mode (--connect).\n\
             \x20 Use: tail-fin --connect 127.0.0.1:9222 {service} {action_name} ..."
        ))),
    }
}

/// Browser-only adapter: reject `--cookies`, require `--connect`, return a
/// ready-to-use [`BrowserSession`].
///
/// [`BrowserSession`]: night_fury_core::BrowserSession
#[cfg(feature = "browser")]
pub async fn require_browser_session(
    ctx: &Ctx,
    service: &str,
) -> Result<night_fury_core::BrowserSession, TailFinError> {
    if ctx.cookies.is_some() {
        return Err(TailFinError::Api(format!(
            "{service} cookie mode is not supported.\n\
             \x20 Use --connect for browser mode."
        )));
    }
    let host = match ctx.connect.as_deref() {
        Some(h) => h,
        None => {
            return Err(TailFinError::Api(format!(
                "{service} requires --connect.\n\
                 \x20 Example: tail-fin --connect 127.0.0.1:9222 {service} ..."
            )));
        }
    };
    browser_session(host, ctx.headed).await
}

/// Print a serializable value as pretty JSON to stdout.
pub fn print_json(value: &(impl serde::Serialize + ?Sized)) -> Result<(), TailFinError> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

/// Print a list result as `{ "<key>": items, "count": N }` JSON.
pub fn print_list(
    key: &str,
    items: &impl serde::Serialize,
    count: usize,
) -> Result<(), TailFinError> {
    println!(
        "{}",
        serde_json::to_string_pretty(&serde_json::json!({
            key: items,
            "count": count,
        }))?
    );
    Ok(())
}

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

    #[cfg(unix)]
    fn env_lock() -> &'static std::sync::Mutex<()> {
        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
        LOCK.get_or_init(|| std::sync::Mutex::new(()))
    }

    // Acquire the TMPDIR env lock, recovering from poisoning so one panicking
    // reaper test doesn't cascade-fail every later test.
    #[cfg(unix)]
    fn lock_env() -> std::sync::MutexGuard<'static, ()> {
        env_lock().lock().unwrap_or_else(|e| e.into_inner())
    }

    #[cfg(unix)]
    #[test]
    fn reap_no_op_when_no_lock() {
        let _guard = lock_env();
        let td = tempfile::TempDir::new().unwrap();
        let original = std::env::var_os("TMPDIR");
        std::env::set_var("TMPDIR", td.path());

        reap_stale_default_profile_lock();

        match original {
            Some(v) => std::env::set_var("TMPDIR", v),
            None => std::env::remove_var("TMPDIR"),
        }
    }

    // Check that the symlink itself exists at `p`, without following the
    // target. `Path::exists()` follows symlinks, so it returns false for
    // dangling symlinks even though the symlink entry is still on disk —
    // useless for these tests which point at fake PID names.
    #[cfg(unix)]
    fn symlink_exists(p: &std::path::Path) -> bool {
        std::fs::symlink_metadata(p).is_ok()
    }

    #[cfg(unix)]
    #[test]
    fn reap_removes_stale_symlink_pointing_at_dead_pid() {
        use std::os::unix::fs::symlink;

        let _guard = lock_env();
        let td = tempfile::TempDir::new().unwrap();
        let runner_dir = td.path().join("chromiumoxide-runner");
        std::fs::create_dir_all(&runner_dir).unwrap();

        let dead_pid = 999_999_999i32;
        let lock = runner_dir.join("SingletonLock");
        symlink(format!("fake-host-{dead_pid}"), &lock).unwrap();

        let original = std::env::var_os("TMPDIR");
        std::env::set_var("TMPDIR", td.path());
        reap_stale_default_profile_lock();
        match original {
            Some(v) => std::env::set_var("TMPDIR", v),
            None => std::env::remove_var("TMPDIR"),
        }

        assert!(
            !symlink_exists(&lock),
            "reaper should have unlinked dead-pid lock"
        );
    }

    #[cfg(unix)]
    #[test]
    fn reap_preserves_symlink_pointing_at_live_pid() {
        use std::os::unix::fs::symlink;

        let _guard = lock_env();
        let td = tempfile::TempDir::new().unwrap();
        let runner_dir = td.path().join("chromiumoxide-runner");
        std::fs::create_dir_all(&runner_dir).unwrap();

        // Use our own PID as the "live" probe — it's guaranteed to be
        // alive and signalable by us. Using PID 1 (init/launchd) works
        // on Linux but fails on macOS where non-root can't signal
        // launchd, so `kill -0 1` returns EPERM and the reaper would
        // incorrectly treat it as dead.
        let live_pid = std::process::id() as i32;
        let lock = runner_dir.join("SingletonLock");
        symlink(format!("fake-host-{live_pid}"), &lock).unwrap();

        let original = std::env::var_os("TMPDIR");
        std::env::set_var("TMPDIR", td.path());
        reap_stale_default_profile_lock();
        match original {
            Some(v) => std::env::set_var("TMPDIR", v),
            None => std::env::remove_var("TMPDIR"),
        }

        assert!(
            symlink_exists(&lock),
            "reaper must not touch a live-pid lock"
        );
    }

    #[test]
    fn resolve_cookies_path_auto_ends_with_site_cookies_txt() {
        let p = resolve_cookies_path("auto", "twitter");

        assert_eq!(
            p.file_name().and_then(|n| n.to_str()),
            Some("twitter-cookies.txt"),
            "unexpected filename in: {}",
            p.display()
        );

        assert_eq!(
            p.parent()
                .and_then(|pp| pp.file_name())
                .and_then(|n| n.to_str()),
            Some(".tail-fin"),
            "unexpected parent directory in: {}",
            p.display()
        );
    }

    #[test]
    fn resolve_cookies_path_explicit_is_verbatim() {
        let p = resolve_cookies_path("/explicit/cookies.txt", "twitter");
        assert_eq!(p.to_string_lossy(), "/explicit/cookies.txt");
    }

    #[test]
    fn default_creds_path_uses_tail_fin_json_name() {
        let p = default_creds_path("nansen");
        assert!(p.to_string_lossy().contains(".tail-fin"));
        assert!(p.ends_with("nansen-creds.json"));
    }

    #[test]
    fn require_browser_errors_when_connect_missing() {
        let err = require_browser(&None, "twitter", "timeline").unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("--connect"),
            "error should mention --connect; got: {msg}"
        );
        assert!(
            msg.contains("twitter timeline"),
            "error should mention the service/action; got: {msg}"
        );
    }

    #[test]
    fn require_browser_returns_host_when_present() {
        let host = require_browser(&Some("127.0.0.1:9222".to_string()), "twitter", "timeline")
            .expect("should succeed when --connect is provided");
        assert_eq!(host, "127.0.0.1:9222");
    }
}