OXYGENHUB
# 87f601ccce6d spectra / src / cli / open.rs
3.7 KiB · Rust · last changed spectra open --page: land on the Constellation, Briefs, Channels or Log 1 day ago source blame history raw
1
//! `spectra open`: sign in to Radar (spec §8.3). The owner's CLI signs a
2
//! request for a one-time link with the owner's key; the link, valid for a
3
//! minute, opens a level-2 browser session.
4
5
use super::identity::{owner_home, recorded_owner};
6
use super::{ui, Ctx};
7
use anyhow::{bail, Context, Result};
8
use spectra_core::ledger::Ledger;
9
use spectra_mcp::client::Client;
10
use std::path::PathBuf;
11
12
/// The sign-in link, landing on `page` if one is named.
13
fn with_page(url: String, page: Option<&str>) -> String {
14
    match page.filter(|p| !p.is_empty() && *p != "live") {
15
        Some(p) => format!("{url}&next={}", p.trim_start_matches('/')),
16
        None => url,
17
    }
18
}
19
20
pub async fn open(ctx: &Ctx, owner_home_flag: Option<PathBuf>, launch: bool, page: Option<&str>) -> Result<i32> {
21
    let socket = ctx.socket();
22
    if !Client::alive(&socket).await {
23
        bail!("Spectra is not serving {} (spectra serve)", ctx.data.display());
24
    }
25
    let home = owner_home(ctx, owner_home_flag);
26
    let ledger = Ledger::open_read_only(&ctx.db()?).await?;
27
    let owner = recorded_owner(&ledger, &home).await?;
28
    let r = Client::new(&socket, Some(owner)).send("POST", "/radar/link", &[], Vec::new()).await?;
29
    if r.status != 200 {
30
        bail!("the daemon refused the sign-in: {}", String::from_utf8_lossy(&r.body));
31
    }
32
    let url = r.json()?.get("url").and_then(|u| u.as_str()).map(String::from).context("no link in the answer")?;
33
    let url = with_page(url, page);
34
    println!("{} {}", ui::done("Signed"), ui::subject("a one-time link to Radar, good for a minute"));
35
    show(&url, launch);
36
    Ok(0)
37
}
38
39
fn show(url: &str, launch: bool) {
40
    println!("  {}", ui::id(url));
41
    if launch
42
        && std::process::Command::new("xdg-open")
43
            .arg(url)
44
            .stdout(std::process::Stdio::null())
45
            .stderr(std::process::Stdio::null())
46
            .spawn()
47
            .is_ok()
48
    {
49
        println!("  {} {}", ui::note(), ui::dim("opened in your browser"));
50
    }
51
}
52
53
/// `spectra open` with Spectra on another machine (spec §8.6): serve Radar
54
/// through a loopback proxy to the pinned server, and sign in through it.
55
pub async fn open_remote(ctx: &Ctx, owner_home_flag: Option<PathBuf>, launch: bool, port: u16, page: Option<&str>) -> Result<i32> {
56
    let cfg = ctx.remote()?.context("no server configured")?;
57
    let home = owner_home(ctx, owner_home_flag);
58
    let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
59
        .await
60
        .with_context(|| format!("binding 127.0.0.1:{port} for Radar (another `spectra open` running? --port picks another)"))?;
61
    let port = listener.local_addr()?.port();
62
    let client = ctx.owner_client(&home).await?.context("no server configured")?;
63
    let r = client.send("POST", "/radar/link", &[], Vec::new()).await?;
64
    if r.status != 200 {
65
        bail!("the server refused the sign-in: {}", String::from_utf8_lossy(&r.body));
66
    }
67
    let url = r.json()?.get("url").and_then(|u| u.as_str()).map(String::from).context("no link in the answer")?;
68
    let local = with_page(spectra_mcp::proxy::local_link(&url, port), page);
69
    println!("{} {}{}{}", ui::done("Serving"), ui::subject("Radar"), ui::sep(), ui::dim(format!("from {} over pinned TLS", cfg.server)));
70
    println!("{}", ui::kv("radar", format!("http://127.0.0.1:{port}")));
71
    println!("{} {}", ui::done("Signed"), ui::subject("a one-time link, good for a minute"));
72
    show(&local, launch);
73
    println!("  {} {}", ui::note(), ui::dim("Ctrl-C stops the proxy"));
74
    use std::io::Write;
75
    std::io::stdout().flush().ok();
76
    let app = spectra_mcp::proxy::router(cfg.endpoint()?, port);
77
    axum::serve(listener, app)
78
        .with_graceful_shutdown(async {
79
            let _ = tokio::signal::ctrl_c().await;
80
        })
81
        .await?;
82
    Ok(0)
83
}