teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter`: persistent terminal sessions on your own machines, reachable
//! from any device through a relay that cannot read them.
//!
//! One binary for hosts and clients: `link` serves this machine's sessions,
//! `status` and `kill` manage them, `attach` joins one from a terminal; the
//! hidden `session` subcommand is a session process, which the link starts.
//! The relay is `teter-relay`.

mod account;
mod approve;
mod attach;
mod host;
mod keyring;
mod machine;
mod remote;
mod sessions;
mod token;

use std::process::ExitCode;

use clap::{Parser, Subcommand};

/// The version: the release's tag, which the release build passes in
/// `TETER_VERSION` (YY.M.patch); else the crate's own version when it has
/// one (a crate from crates.io, which `scripts/publish-crates.sh` gave the
/// tag's); else `dev`, for a build from source (also when `TETER_VERSION` is
/// set but empty, as `scripts/dist.sh` names the tarball).
const VERSION: &str = match option_env!("TETER_VERSION") {
    Some(version) if !version.is_empty() => version,
    _ if matches!(env!("CARGO_PKG_VERSION").as_bytes(), b"0.0.0") => "dev",
    _ => env!("CARGO_PKG_VERSION"),
};

/// Persistent terminal sessions on your machines, through a teter relay.
#[derive(Parser)]
#[command(version = VERSION)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Serve this machine's sessions through a teter relay.
    Link(host::LinkArgs),
    /// Show what a frontend needs to attach to each session.
    Status(host::StatusArgs),
    /// End a session: on this machine by its name, or on one of the
    /// account's machines as `machine:session`.
    Kill(host::KillArgs),
    /// List the sessions of one of the account's machines.
    Ls(remote::LsArgs),
    /// Create a session on one of the account's machines, as
    /// `machine:session`, and start it.
    New(remote::NewArgs),
    /// Attach this terminal to a session. Ctrl-] detaches.
    ///
    /// The secret `teter status` shows comes from TETER_SECRET, never from
    /// the command line, where other users could read it in the process
    /// list.
    Attach(attach::AttachArgs),
    /// Make an account on a relay, and log this device in to it.
    Signup(account::SignupArgs),
    /// Log this device in to an account on a relay.
    Login(account::LoginArgs),
    /// Log this device out of its account.
    Logout(account::LogoutArgs),
    /// Change the account's password.
    Password(account::PasswordArgs),
    /// Replace the account's keys (a lost device, a key that may have
    /// leaked); its machines follow.
    RotateKeys(account::RotateArgs),
    /// Registration tokens, to register machines with the account.
    Token(token::TokenArgs),
    /// Register this machine with an account, with a registration token.
    Register(machine::RegisterArgs),
    /// Unregister this machine.
    Unregister(machine::UnregisterArgs),
    /// The account's machines.
    Machine(machine::MachineArgs),
    /// Run one session process (the link starts these).
    #[command(hide = true)]
    Session(host::SessionArgs),
}

/// The relay's endpoint `path` (`backend` or `frontend`) for `relay`, which
/// may name the relay alone or either endpoint: `link` and `attach` read the
/// same `TETER_RELAY`, on a machine that does both.
fn endpoint(relay: &str, path: &str) -> String {
    // Only the path, after the host, can name an endpoint: a relay whose
    // host is `backend` is not one.
    let host_at = relay.find("://").map_or(0, |at| at + 3);
    let path_at = relay
        .get(host_at..)
        .and_then(|rest| rest.find('/'))
        .map_or(relay.len(), |at| host_at + at);
    let (origin, relay_path) = relay.split_at(path_at);
    let relay_path = relay_path.trim_end_matches('/');
    let relay_path = relay_path
        .strip_suffix("/backend")
        .or_else(|| relay_path.strip_suffix("/frontend"))
        .unwrap_or(relay_path);
    format!("{origin}{relay_path}/{path}")
}

#[tokio::main]
async fn main() -> ExitCode {
    let cli = Cli::parse();
    // The terminal of `attach` is raw: logs would break it.
    if !matches!(cli.command, Command::Attach(_)) {
        tracing_subscriber::fmt()
            .with_writer(std::io::stderr)
            .with_env_filter(
                tracing_subscriber::EnvFilter::try_from_default_env()
                    .unwrap_or_else(|_| "warn".into()),
            )
            .init();
    }
    let (result, failure) = match cli.command {
        Command::Link(args) => {
            let in_use_status = args.in_use_status;
            let result = host::link(args).await;
            // Another link, or a session it cannot serve, holds the socket
            // directory: a service restart cannot help (the unit does not
            // restart on this status).
            let failure = match &result {
                Err(e) if teter_backend::LinkInUse::is(e) => ExitCode::from(in_use_status),
                _ => ExitCode::FAILURE,
            };
            (result, failure)
        }
        Command::Status(args) => (host::status(args).await, ExitCode::FAILURE),
        Command::Kill(args) => (host::kill(args).await, ExitCode::FAILURE),
        Command::Ls(args) => (remote::ls(args).await, ExitCode::FAILURE),
        Command::New(args) => (remote::new(args).await, ExitCode::FAILURE),
        Command::Signup(args) => (account::signup(args).await, ExitCode::FAILURE),
        Command::Login(args) => (account::login(args).await, ExitCode::FAILURE),
        Command::Logout(args) => (account::logout(args).await, ExitCode::FAILURE),
        Command::Password(args) => (account::change_password(args).await, ExitCode::FAILURE),
        Command::RotateKeys(args) => (account::rotate_keys(args).await, ExitCode::FAILURE),
        Command::Token(args) => (token::token(args).await, ExitCode::FAILURE),
        Command::Register(args) => (machine::register(args).await, ExitCode::FAILURE),
        Command::Unregister(args) => (machine::unregister(args).await, ExitCode::FAILURE),
        Command::Machine(args) => (machine::machine(args).await, ExitCode::FAILURE),
        Command::Session(args) => (host::serve_session(args).await, host::session_failure()),
        // Exit at once: a pending read of stdin holds a thread that would
        // otherwise keep the process alive after the session.
        Command::Attach(args) => std::process::exit(attach::attach(args).await),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("teter: {e}");
            failure
        }
    }
}

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

    #[test]
    fn either_endpoint_or_the_relay_alone_names_the_relay() {
        for relay in [
            "wss://relay.example.com",
            "wss://relay.example.com/",
            "wss://relay.example.com/backend",
            "wss://relay.example.com/frontend/",
        ] {
            assert_eq!(
                endpoint(relay, "backend"),
                "wss://relay.example.com/backend"
            );
            assert_eq!(
                endpoint(relay, "frontend"),
                "wss://relay.example.com/frontend"
            );
        }
        // A host named like an endpoint is a host.
        assert_eq!(
            endpoint("ws://backend", "frontend"),
            "ws://backend/frontend"
        );
        assert_eq!(
            endpoint("ws://frontend/", "backend"),
            "ws://frontend/backend"
        );
        assert_eq!(
            endpoint("ws://backend/backend", "frontend"),
            "ws://backend/frontend"
        );
        // A relay behind a path keeps it.
        assert_eq!(
            endpoint("wss://example.com/teter/backend", "frontend"),
            "wss://example.com/teter/frontend"
        );
    }
}