teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! The host side: `teter link` serves this machine's sessions through a
//! relay, starting a session process when none runs; the hidden
//! `teter session` is a session process, which the link starts; `teter
//! status` shows what a frontend needs to attach to each session; `teter
//! kill` ends one.

use std::io::IsTerminal;
use std::path::PathBuf;

use teter_backend::registry::{self, Registry};
use teter_backend::session::{self, SessionConfig};
use teter_client::e2e::Secret;

/// Serve this machine's shells through a teter relay.
#[derive(clap::Args)]
pub struct LinkArgs {
    /// The relay, such as wss://relay.example.com (its /backend endpoint;
    /// one ending in /backend or /frontend is taken as the relay's).
    /// Default: the one the machine registered with (teter register), whose
    /// key it proves itself with.
    #[arg(long, env = "TETER_RELAY")]
    relay: Option<String>,

    /// The program to run in the terminal (default: $SHELL, or /bin/sh).
    #[arg(long)]
    shell: Option<String>,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,

    /// The directory of the session processes' sockets (default:
    /// $XDG_RUNTIME_DIR/teter).
    #[arg(long, env = "TETER_SOCKETS")]
    sockets: Option<PathBuf>,

    /// The file of this machine's session registry (default:
    /// $XDG_STATE_HOME/teter/sessions). Two links with different socket
    /// directories need different ones.
    #[arg(long, env = "TETER_REGISTRY")]
    registry: Option<PathBuf>,

    /// The exit status when the link cannot serve at all: another link serves
    /// the socket directory, the default session runs and is of a version
    /// this one cannot serve, the machine is not registered, or the relay
    /// does not know it. The
    /// systemd unit does not restart on 3; the launchd agent, which cannot
    /// skip a status, passes 0, which it does not restart on.
    #[arg(long, default_value_t = 3)]
    pub(crate) in_use_status: u8,
}

/// End a session: its shell ends, and the link does not start it again (the
/// default session always exists).
#[derive(clap::Args)]
pub struct KillArgs {
    /// The session's name on this machine, or `machine:session` for one of
    /// the account's machines.
    name: String,

    /// PEM file of the CA that signed the relay's certificate (for
    /// `machine:session`), when it does not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,

    /// The directory of the session processes' sockets (default:
    /// $XDG_RUNTIME_DIR/teter).
    #[arg(long, env = "TETER_SOCKETS")]
    sockets: Option<PathBuf>,

    /// The file of the session registry (default:
    /// $XDG_STATE_HOME/teter/sessions): the one the link uses.
    #[arg(long, env = "TETER_REGISTRY")]
    registry: Option<PathBuf>,
}

/// Show each session's name, relay session, frontend token and secret, asked
/// of its session process: for your terminal, never a log.
#[derive(clap::Args)]
pub struct StatusArgs {
    /// The directory of the session processes' sockets (default:
    /// $XDG_RUNTIME_DIR/teter).
    #[arg(long, env = "TETER_SOCKETS")]
    sockets: Option<PathBuf>,
}

/// Run one session process (the link starts these).
#[derive(clap::Args)]
pub struct SessionArgs {
    /// The session's name.
    #[arg(long)]
    name: String,

    /// The program to run in the terminal.
    #[arg(long)]
    shell: String,

    /// The directory of the session processes' sockets.
    #[arg(long)]
    sockets: PathBuf,

    /// Lines of history its terminal state keeps (#90).
    #[arg(long, default_value_t = teter_backend::screen::DEFAULT_HISTORY)]
    history_lines: usize,

    /// Where its history goes on disk, sealed to the account (#93).
    #[arg(long)]
    history_dir: Option<PathBuf>,
}

/// The link, serving every session of the machine.
pub async fn link(args: LinkArgs) -> std::io::Result<()> {
    // The registered machine's key: the only way in (#130). Without it the
    // link cannot serve at all, and a service must not start it again (#165).
    let host = crate::machine::load_host()?
        .filter(|host| !host.machine.is_empty())
        .ok_or_else(|| {
            teter_backend::LinkInUse::error(
                "this machine is not registered: make a token on a logged-in device (teter token \
                 create), then run teter register --token <token> here"
                    .into(),
            )
        })?;
    let machine = teter_backend::MachineAuth {
        id: host.machine.clone(),
        key: std::sync::Arc::new(host.key()?),
        account_keys: account_keys(&host.account_keys)?,
    };
    let relay = args.relay.unwrap_or_else(|| host.relay.clone());
    // Another URL of the same relay is fine; another relay is not, and a
    // TETER_RELAY exported for `attach` would make it so without a word.
    if crate::endpoint(&relay, "backend") != crate::endpoint(&host.relay, "backend") {
        tracing::warn!(
            relay,
            registered = host.relay,
            "linking through a relay other than the one this machine registered with \
             (--relay or TETER_RELAY): it must be another URL of the same relay"
        );
    }
    let defaults = teter_backend::Config::new(
        crate::endpoint(&relay, "backend"),
        machine,
        args.shell.unwrap_or_else(teter_backend::default_shell),
    );
    let config = teter_backend::Config {
        ca_cert: args.ca_cert,
        sockets: args.sockets.unwrap_or(defaults.sockets.clone()),
        // Without a place for it (no HOME), the link runs without one: the
        // default session, as before registries.
        registry: match args.registry {
            Some(path) => Some(path),
            None => registry::default_path()
                .inspect_err(|e| tracing::warn!(error = %e, "running without a session registry"))
                .ok(),
        },
        ..defaults
    };
    // The token only to a terminal: a service's output lands in a journal or
    // a log file that outlives it (#152). `teter status` gives it anywhere.
    let to_terminal = std::io::stdout().is_terminal();
    teter_backend::run(&config, move |session| {
        println!("session: {}", session.id);
        if to_terminal {
            println!("token: {}", session.frontend_token);
        }
        if let Some(name) = &session.name {
            println!("name: {name}");
        }
        if let Some(channel) = &session.channel {
            println!("channel: {channel}");
        }
    })
    .await
}

/// The account's keys from `host.json` (hex), kept there again when the
/// link follows a rotation the old keys signed (#89).
fn account_keys(hex: &str) -> std::io::Result<teter_backend::AccountKeysCell> {
    let keys = teter_common::account::unhex(hex)
        .ok_or_else(|| std::io::Error::other("host.json is damaged: register again"))?;
    Ok(teter_backend::AccountKeysCell::saving(keys, |keys| {
        if let Err(e) = crate::machine::save_account_keys(keys) {
            tracing::warn!(error = %e, "could not keep the account's new keys in host.json");
        }
    }))
}

/// A session process. Its secret never goes to the relay, the link, or any
/// output: `status` asks for it (until accounts carry it, #87).
pub async fn serve_session(args: SessionArgs) -> std::io::Result<()> {
    let bound = session::bind(&args.sockets, &args.name)?;
    let secret = Secret::generate()?;
    // It outlives the link: it must not hold the link's output open.
    let null = std::fs::OpenOptions::new().write(true).open("/dev/null")?;
    rustix::stdio::dup2_stdout(null)?;
    let config = SessionConfig {
        history_lines: args.history_lines,
        history_dir: args.history_dir,
        ..SessionConfig::new(args.name, args.shell, secret)
    };
    session::serve(config, bound).await
}

/// Prints each session's values, as its session process tells them.
pub async fn status(args: StatusArgs) -> std::io::Result<()> {
    let sockets = args.sockets.unwrap_or_else(session::socket_dir);
    let answers = teter_backend::status(&sockets).await?;
    if answers.is_empty() {
        return Err(std::io::Error::other(format!(
            "no session runs (no socket in {})",
            sockets.display()
        )));
    }
    let mut answered = false;
    for (name, answer) in answers {
        match answer {
            Ok(values) => {
                answered = true;
                println!("{}", values.name);
                match values.relay {
                    Some((id, token)) => {
                        println!("  session: {id}");
                        println!("  token: {token}");
                        if let Some(channel) = &values.channel {
                            println!("  channel: {channel}");
                        }
                    }
                    None => println!("  session: none yet (no link has reached the relay)"),
                }
                println!("  secret: {}", *values.secret);
            }
            Err(e) => eprintln!("teter: {name}: {e}"),
        }
    }
    if answered {
        Ok(())
    } else {
        Err(std::io::Error::other(format!(
            "no session process in {} answered",
            sockets.display()
        )))
    }
}

/// Ends a session, and says what it did.
pub async fn kill(args: KillArgs) -> std::io::Result<()> {
    // A session name holds no `:`: this names another machine's.
    if args.name.contains(':') {
        return crate::remote::kill(&args.name, args.ca_cert).await;
    }
    let registry = Registry::at(match args.registry {
        Some(path) => path,
        None => registry::default_path()?,
    });
    let sockets = args.sockets.unwrap_or_else(session::socket_dir);
    let ended = match teter_backend::kill(&sockets, &registry, &args.name).await {
        Ok(ended) => ended,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(std::io::Error::new(
                e.kind(),
                format!("{e} on this machine (another machine's: teter kill machine:session)"),
            ));
        }
        Err(e) => return Err(e),
    };
    if ended {
        println!("ended the session {:?}", args.name);
    } else {
        println!(
            "removed the session {:?}; no session process of it ran",
            args.name
        );
    }
    Ok(())
}

/// The exit status of a session process that fails.
pub fn session_failure() -> std::process::ExitCode {
    std::process::ExitCode::from(session::FAILURE_EXIT)
}