splashboard 1.2.0

A customizable terminal splash screen with plugin-based data sources
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use std::future::Future;
use std::io::{self, BufRead, IsTerminal, Write, stdin, stdout};
use std::path::{Path, PathBuf};

use clap::{Parser, Subcommand};

use splashboard::catalog;
use splashboard::config::{
    self, Config, DashboardConfig, DashboardSource, SettingsConfig, WidgetConfig,
};
use splashboard::daemon::{self, DashboardKind};
use splashboard::fetcher::{Registry, Safety};
use splashboard::install::{self, InstallOptions};
use splashboard::logging;
use splashboard::paths;
use splashboard::render::Registry as RenderRegistry;
use splashboard::runtime;
use splashboard::secrets::SecretsConfig;
use splashboard::shell::{self, Shell};
use splashboard::trust::{TrustStore, load_dashboard_and_hash};

const OPT_OUT_ENV_VARS: &[&str] = &["CI", "SPLASHBOARD_SILENT", "NO_SPLASHBOARD"];
const MIN_WIDTH: u16 = 40;
const MIN_HEIGHT: u16 = 16;

#[derive(Parser)]
#[command(version, about = "A customizable terminal splash screen")]
struct Cli {
    /// Render only if the current directory directly resolves to a dashboard (per-dir file or
    /// git repo root); otherwise exit silently. Intended for cd-hook invocations so the splash
    /// shows exactly once per project entry instead of on every subdirectory navigation.
    #[arg(long)]
    on_cd: bool,

    /// Wait for fresh data before drawing (skips the cache-first fast path). Slower startup,
    /// guarantees the frame reflects current values. Equivalent to `general.wait_for_fresh`.
    #[arg(long)]
    wait: bool,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Emit a shell init snippet; source it from your rc file to render on new shells and on cd.
    Init {
        #[arg(value_enum)]
        shell: Shell,
    },
    /// One-shot onboarding: pick a home/project template pair, write them to
    /// `$HOME/.splashboard/`, and wire your shell rc so the splash renders on every new shell.
    /// Runs an interactive gallery picker in a TTY; non-TTY callers must pass
    /// `--home-template` and `--project-template`. Existing files are always backed up to
    /// `.bak` sidecars before being overwritten, so re-running is safe.
    Install {
        /// Shell to wire. Omit to auto-detect from `$SHELL`.
        #[arg(long, value_enum)]
        shell: Option<Shell>,
        /// Home template name (e.g. `home_splash`). Required in non-TTY mode.
        #[arg(long)]
        home_template: Option<String>,
        /// Project template name (e.g. `project_github`). Required in non-TTY mode.
        #[arg(long)]
        project_template: Option<String>,
        /// Theme preset for `settings.toml`. One of `default`, `catppuccin_mocha`,
        /// `dracula`, `gruvbox_dark`, `nord`, `tokyo_night`.
        #[arg(long)]
        theme: Option<String>,
        /// Inherit the terminal's own background instead of painting the Splash palette.
        /// Writes `bg = "reset"` + `bg_subtle = "reset"` into `settings.toml`.
        #[arg(long)]
        no_bg: bool,
        /// Block the first render until every widget has fetched at least once. Writes
        /// `wait_for_fresh = true` into `settings.toml`.
        #[arg(long)]
        wait: bool,
    },
    /// Grant this project-local dashboard permission to run Network widgets. Safe widgets
    /// always run regardless; this is the consent step for anything that talks to the outside
    /// world. Defaults to the nearest `.splashboard.toml` walking up from the current directory.
    Trust {
        #[arg(value_name = "PATH")]
        path: Option<PathBuf>,
    },
    /// Remove trust for a project-local dashboard. Network widgets in it will render the
    /// "🔒 requires trust" placeholder until re-trusted.
    Revoke {
        #[arg(value_name = "PATH")]
        path: Option<PathBuf>,
    },
    /// Print the currently trusted local dashboards.
    ListTrusted,
    /// Browse the built-in fetcher and renderer catalog — the same info the docs site exposes,
    /// rendered for the terminal. Run without a target for an overview; use
    /// `catalog fetcher [NAME]` or `catalog renderer [NAME]` to narrow.
    Catalog {
        #[command(subcommand)]
        target: Option<CatalogTarget>,
    },
    /// Print embedded license text. Defaults to the third-party dependency bundle
    /// (`THIRDPARTY-LICENSES.md`); pass `--own` for splashboard's own ISC LICENSE.
    License {
        /// Print splashboard's own ISC LICENSE instead of the third-party bundle.
        #[arg(long)]
        own: bool,
    },
    /// Internal: run fetchers and update the cache. Spawned as a detached child by the main
    /// splashboard invocation; not intended to be run directly.
    #[command(hide = true)]
    FetchOnly {
        #[arg(long, value_enum)]
        kind: DashboardKind,
        #[arg(long)]
        path: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum CatalogTarget {
    /// List all fetchers, or show details for one when NAME is given.
    #[command(alias = "fetchers")]
    Fetcher { name: Option<String> },
    /// List all renderers, or show details for one when NAME is given.
    #[command(alias = "renderers")]
    Renderer { name: Option<String> },
}

fn main() -> io::Result<()> {
    let cli = Cli::parse();
    match cli.command {
        Some(Command::Init { shell }) => {
            print!("{}", shell::init_snippet(shell));
            Ok(())
        }
        Some(Command::Install {
            shell,
            home_template,
            project_template,
            theme,
            no_bg,
            wait,
        }) => install::run(InstallOptions {
            shell,
            home_template,
            project_template,
            theme,
            // Flag absence = "leave it to the picker / default"; flag presence = force the
            // opposite of the default. `--no-bg` disables bg, `--wait` enables wait.
            bg: no_bg.then_some(false),
            wait: wait.then_some(true),
            ..Default::default()
        }),
        Some(Command::FetchOnly { kind, path }) => run_async({
            logging::init();
            apply_secrets();
            daemon::run_fetch_only(kind, path.as_deref())
        }),
        Some(Command::Trust { path }) => run_trust(path),
        Some(Command::Revoke { path }) => run_revoke(path),
        Some(Command::ListTrusted) => run_list_trusted(),
        Some(Command::Catalog { target }) => run_catalog(target),
        Some(Command::License { own }) => run_license(own),
        None => {
            if !should_render() {
                return Ok(());
            }
            logging::init();
            apply_secrets();
            // Swallow render errors at the shell-facing boundary so a broken splash never breaks
            // the user's prompt. Internal paths (FetchOnly above) still propagate errors.
            let _ = if cli.on_cd {
                run_async(render_for_cd(cli.wait))
            } else {
                run_async(render_splash(cli.wait))
            };
            Ok(())
        }
    }
}

fn run_async<F>(future: F) -> io::Result<()>
where
    F: Future<Output = io::Result<()>>,
{
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?
        .block_on(future)
}

async fn render_splash(wait: bool) -> io::Result<()> {
    if !should_render() {
        return Ok(());
    }
    let source = config::resolve_dashboard_source();
    let (config, ident) = load_full_config(&source)?;
    if matches!(source, DashboardSource::Home) && !config.general.auto_home {
        return Ok(());
    }
    let ident_ref = ident.as_ref().map(|(p, h)| (p.as_path(), h.as_str()));
    runtime::run(&config, &source, ident_ref, wait).await
}

async fn render_for_cd(wait: bool) -> io::Result<()> {
    if !should_render() {
        return Ok(());
    }
    let Some(source) = config::resolve_on_cd_dashboard_source() else {
        return Ok(());
    };
    let (config, ident) = load_full_config(&source)?;
    if !config.general.auto_on_cd {
        return Ok(());
    }
    let ident_ref = ident.as_ref().map(|(p, h)| (p.as_path(), h.as_str()));
    runtime::run(&config, &source, ident_ref, wait).await
}

fn should_render() -> bool {
    stdout().is_terminal()
        && stdin().is_terminal()
        && allow_render(|k| std::env::var(k).ok())
        && meets_minimum_size()
}

fn allow_render(env: impl Fn(&str) -> Option<String>) -> bool {
    if OPT_OUT_ENV_VARS.iter().any(|k| env(k).is_some()) {
        return false;
    }
    !matches!(env("TERM").as_deref(), Some("dumb"))
}

fn meets_minimum_size() -> bool {
    ratatui::crossterm::terminal::size()
        .map(|(w, h)| is_large_enough(w, h))
        .unwrap_or(false)
}

fn is_large_enough(width: u16, height: u16) -> bool {
    width >= MIN_WIDTH && height >= MIN_HEIGHT
}

/// Loads settings + the resolved dashboard and composes them into a `Config`. The optional
/// `(path, hash)` identifies a local dashboard for trust gating; HOME-backed sources return
/// `None` so they're treated as implicitly trusted.
fn load_full_config(source: &DashboardSource) -> io::Result<(Config, Option<(PathBuf, String)>)> {
    let settings = load_settings()?;
    let (dashboard, ident) = match source {
        DashboardSource::Local(p) => {
            let (d, h) = load_dashboard_and_hash(p).map_err(io::Error::other)?;
            (d, Some((p.clone(), h)))
        }
        DashboardSource::Home => (load_home_dashboard_or_baked()?, None),
        DashboardSource::Project => (load_project_dashboard_or_baked()?, None),
    };
    Ok((Config::from_parts(settings, dashboard), ident))
}

/// Loads `$HOME/.splashboard/secrets.toml` and exports each entry as a process env var, but
/// only when the env doesn't already define it. Runs once at startup so every fetcher
/// (`GH_TOKEN`, `TODOIST_TOKEN`, etc.) sees the same view regardless of who reads first.
/// Failures (parse error, unreadable file) log and continue — a stale token shouldn't break
/// the splash, and the user's shell env is still authoritative.
fn apply_secrets() {
    let Some(path) = paths::secrets_path() else {
        return;
    };
    match SecretsConfig::load_or_default(&path) {
        Ok(secrets) => {
            secrets.apply_to_env(
                |k| std::env::var(k).ok(),
                // SAFETY: called once from `main` before any user code reads env. The Tokio
                // worker threads exist but are idle — none of our fetchers / runtime tasks
                // have been spawned yet, so no thread is racing on `getenv`/`setenv`.
                |k, v| unsafe { std::env::set_var(k, v) },
            );
        }
        Err(e) => {
            tracing::warn!(error = %e, "failed to load secrets.toml; continuing without it");
        }
    }
}

fn load_settings() -> io::Result<SettingsConfig> {
    match paths::settings_path() {
        Some(p) => SettingsConfig::load_or_default(&p).map_err(io::Error::other),
        None => Ok(SettingsConfig::default_baked()),
    }
}

fn load_home_dashboard_or_baked() -> io::Result<DashboardConfig> {
    load_dashboard_file_or(paths::home_dashboard_path(), DashboardConfig::default_home)
}

fn load_project_dashboard_or_baked() -> io::Result<DashboardConfig> {
    load_dashboard_file_or(
        paths::project_dashboard_path(),
        DashboardConfig::default_project,
    )
}

fn load_dashboard_file_or(
    path: Option<PathBuf>,
    baked: impl FnOnce() -> DashboardConfig,
) -> io::Result<DashboardConfig> {
    let Some(path) = path else {
        return Ok(baked());
    };
    match std::fs::read_to_string(&path) {
        Ok(s) => DashboardConfig::parse(&s)
            .map_err(|e| io::Error::other(format!("{}: {e}", path.display()))),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(baked()),
        Err(e) => Err(e),
    }
}

fn run_trust(path: Option<PathBuf>) -> io::Result<()> {
    let Some(target) = resolve_trust_target(path) else {
        eprintln!(
            "no project-local dashboard found (run from inside a directory with .splashboard.toml)"
        );
        return Ok(());
    };
    // Read the bytes once so the hash we show the user matches the hash we store — and so an
    // attacker can't swap the file between "here's what it asks for" and "ok I trust it".
    let (dashboard, hash) = load_dashboard_and_hash(&target).map_err(io::Error::other)?;
    let registry = Registry::with_builtins();
    print_trust_summary(&target, &hash, &dashboard.widgets, &registry)?;
    if !prompt_yes_no("Trust this dashboard?")? {
        println!("not trusted");
        return Ok(());
    }
    let mut store = TrustStore::load();
    store.trust(&target, hash)?;
    println!("trusted: {}", target.display());
    Ok(())
}

fn run_revoke(path: Option<PathBuf>) -> io::Result<()> {
    let Some(target) = resolve_trust_target(path) else {
        eprintln!("no project-local dashboard found");
        return Ok(());
    };
    let mut store = TrustStore::load();
    let display = sanitize_for_display(&target.display().to_string());
    if store.revoke(&target)? {
        println!("revoked: {display}");
    } else {
        println!("not trusted: {display}");
    }
    Ok(())
}

fn run_list_trusted() -> io::Result<()> {
    let store = TrustStore::load();
    for entry in store.list() {
        println!(
            "{}  {}",
            entry.sha256,
            sanitize_for_display(&entry.path.display().to_string())
        );
    }
    Ok(())
}

fn run_catalog(target: Option<CatalogTarget>) -> io::Result<()> {
    let fetchers = Registry::with_builtins();
    let renderers = RenderRegistry::with_builtins();
    let output = match target {
        None => Ok(catalog::overview(&fetchers, &renderers)),
        Some(CatalogTarget::Fetcher { name: None }) => Ok(catalog::fetcher_list(&fetchers)),
        Some(CatalogTarget::Fetcher { name: Some(n) }) => {
            catalog::fetcher_detail(&n, &fetchers, &renderers)
        }
        Some(CatalogTarget::Renderer { name: None }) => Ok(catalog::renderer_list(&renderers)),
        Some(CatalogTarget::Renderer { name: Some(n) }) => {
            catalog::renderer_detail(&n, &renderers, &fetchers)
        }
    };
    match output {
        Ok(s) => {
            print!("{s}");
            Ok(())
        }
        Err(msg) => {
            eprintln!("{msg}");
            std::process::exit(2);
        }
    }
}

fn run_license(own: bool) -> io::Result<()> {
    let text = if own {
        include_str!("../LICENSE")
    } else {
        include_str!("../THIRDPARTY-LICENSES.md")
    };
    print!("{text}");
    Ok(())
}

fn resolve_trust_target(override_path: Option<PathBuf>) -> Option<PathBuf> {
    override_path.or_else(config::resolve_local_dashboard_path)
}

fn print_trust_summary(
    path: &Path,
    hash: &str,
    widgets: &[WidgetConfig],
    registry: &Registry,
) -> io::Result<()> {
    // Paths and widget ids/fetchers flow into the terminal unmodified; sanitize control chars so
    // a malicious config can't spoof the prompt with ANSI escape sequences.
    println!(
        "Dashboard: {}",
        sanitize_for_display(&path.display().to_string())
    );
    println!("sha256: {hash}");
    println!();

    let mut declared = 0usize;
    for w in widgets {
        let Some(fetcher) = registry.get(&w.fetcher) else {
            continue;
        };
        let label = match fetcher.safety() {
            Safety::Safe => continue,
            Safety::Network => "network",
            Safety::Exec => "exec",
        };
        if declared == 0 {
            println!("This dashboard requests:");
        }
        println!(
            "  - {label:<7}: {} ({})",
            sanitize_for_display(&w.id),
            sanitize_for_display(&w.fetcher)
        );
        declared += 1;
    }
    if declared == 0 {
        println!("(no Network or Exec widgets — nothing to trust)");
    }
    println!();
    Ok(())
}

/// Replaces control characters (including ANSI escape initiators) with U+FFFD so a hostile
/// config can't draw over the trust prompt to make it look like something else.
fn sanitize_for_display(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_control() {
                char::REPLACEMENT_CHARACTER
            } else {
                c
            }
        })
        .collect()
}

fn prompt_yes_no(question: &str) -> io::Result<bool> {
    print!("{question} [y/N] ");
    stdout().flush()?;
    let mut line = String::new();
    stdin().lock().read_line(&mut line)?;
    Ok(matches!(line.trim(), "y" | "Y" | "yes" | "Yes"))
}

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

    fn env_with(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
        move |k: &str| {
            pairs
                .iter()
                .find(|(key, _)| *key == k)
                .map(|(_, v)| (*v).to_string())
        }
    }

    #[test]
    fn allows_render_in_plain_env() {
        assert!(allow_render(env_with(&[])));
    }

    #[test]
    fn ci_env_blocks_render() {
        assert!(!allow_render(env_with(&[("CI", "true")])));
    }

    #[test]
    fn splashboard_silent_blocks_render() {
        assert!(!allow_render(env_with(&[("SPLASHBOARD_SILENT", "1")])));
    }

    #[test]
    fn no_splashboard_blocks_render() {
        assert!(!allow_render(env_with(&[("NO_SPLASHBOARD", "1")])));
    }

    #[test]
    fn dumb_terminal_blocks_render() {
        assert!(!allow_render(env_with(&[("TERM", "dumb")])));
    }

    #[test]
    fn normal_term_allows_render() {
        assert!(allow_render(env_with(&[("TERM", "xterm-256color")])));
    }

    #[test]
    fn large_enough_size_passes() {
        assert!(super::is_large_enough(80, 24));
        assert!(super::is_large_enough(super::MIN_WIDTH, super::MIN_HEIGHT));
    }

    #[test]
    fn below_min_width_fails() {
        assert!(!super::is_large_enough(39, 40));
    }

    #[test]
    fn below_min_height_fails() {
        assert!(!super::is_large_enough(80, 15));
    }

    #[test]
    fn sanitize_replaces_control_chars() {
        let evil = "legit\x1b[2Kspoof";
        let safe = super::sanitize_for_display(evil);
        assert!(!safe.contains('\x1b'));
        assert!(safe.contains('\u{FFFD}'));
    }

    #[test]
    fn sanitize_preserves_normal_text() {
        let s = super::sanitize_for_display("hello/world-dashboard_01");
        assert_eq!(s, "hello/world-dashboard_01");
    }

    #[test]
    fn sanitize_replaces_newline_and_tab() {
        let s = super::sanitize_for_display("a\nb\tc");
        assert_eq!(s.matches('\u{FFFD}').count(), 2);
    }
}