teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! The account's sessions, found through the relay (#87): a logged-in device
//! asks for its machines and their session records, opens their names and
//! keys with the account's private key, and attaches with nothing carried by
//! hand.

use std::path::PathBuf;

use teter_client::account::AccountKeys;
use teter_client::e2e::Secret;
use teter_common::account::{AccountLimits, AccountReply, AccountRequest, MachineSessions, unhex};
use teter_frontend::Config;
use zeroize::Zeroizing;

/// The default session's name.
const DEFAULT_SESSION: &str = "main";

/// The logged-in account, its keys, its machines with their sessions, and
/// its limits on the relay (#104; `None` from an older relay).
async fn account_sessions(
    ca_cert: Option<&std::path::Path>,
) -> std::io::Result<(
    crate::account::Saved,
    AccountKeys,
    Vec<MachineSessions>,
    Option<AccountLimits>,
)> {
    let saved = crate::account::load().await?;
    let keys = unhex(&saved.private_keys)
        .map(Zeroizing::new)
        .and_then(|private| AccountKeys::from_private_bytes(&private))
        .ok_or_else(|| std::io::Error::other("the saved account is damaged: log in again"))?;
    let request = AccountRequest::Sessions {
        login: saved.token.clone(),
    };
    let (mut machines, mut limits) = sessions(&saved, ca_cert, &request).await?;
    // A machine registered with a token this device made is approved here,
    // on its proof (#133); then asked again, with its approval.
    if machines.iter().any(|machine| !approved(&keys, machine)) && crate::approve::has_pending() {
        let list = AccountRequest::MachineList {
            login: saved.token.clone(),
        };
        // A failure here must not stop what the user asked for.
        if let Ok(AccountReply::Machines { machines: listed }) =
            crate::account::ask_as(&saved, ca_cert, &list).await
            && crate::approve::pending_machines(&saved, &keys, ca_cert, &listed)
                .await
                .unwrap_or(0)
                > 0
        {
            (machines, limits) = sessions(&saved, ca_cert, &request).await?;
        }
    }
    Ok((saved, keys, machines, limits))
}

/// The machines and sessions the relay answers `request` with, and the
/// account's limits.
async fn sessions(
    saved: &crate::account::Saved,
    ca_cert: Option<&std::path::Path>,
    request: &AccountRequest,
) -> std::io::Result<(Vec<MachineSessions>, Option<AccountLimits>)> {
    let reply = crate::account::ask_as(saved, ca_cert, request).await?;
    let AccountReply::Sessions { machines, limits } = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    Ok((machines, limits))
}

use teter_client::sessions::{approved, signed};

/// Why `machine` has no signed session named `session_name`: none of that
/// name, or one whose record the machine did not sign.
fn no_session(
    machine: &MachineSessions,
    machine_name: &str,
    session_name: &str,
    opened: impl Fn(&[u8], &[u8]) -> Option<String>,
) -> std::io::Error {
    let unsigned = machine.sessions.iter().any(|record| {
        !signed(machine, record)
            && opened(
                &record.sealed_name,
                &teter_backend::session_name_info(&machine.id, &record.channel),
            )
            .as_deref()
                == Some(session_name)
    });
    std::io::Error::other(if unsigned {
        format!(
            "{machine_name}:{session_name} has a record its machine did not sign: update teter \
                 link on {machine_name} (or the relay altered it)"
        )
    } else {
        format!(
            "{machine_name} has no session named {session_name:?} (see `teter ls {machine_name}`)"
        )
    })
}

/// The approved machine named `name`, or why there is none.
fn find_machine<'a>(
    keys: &AccountKeys,
    machines: &'a [MachineSessions],
    name: &str,
    opened: impl Fn(&[u8], &[u8]) -> Option<String> + Copy,
) -> std::io::Result<&'a MachineSessions> {
    let named: Vec<&MachineSessions> = machines
        .iter()
        .filter(|machine| {
            opened(&machine.sealed_name, crate::machine::NAME_INFO).as_deref() == Some(name)
        })
        .collect();
    if named.is_empty() {
        return Err(no_machine(name, machines, opened));
    }
    // An old record of a machine registered again keeps its name: the
    // approved, connected one wins.
    named
        .into_iter()
        .filter(|machine| approved(keys, machine))
        .max_by_key(|machine| machine.relay.is_some())
        .ok_or_else(|| {
            std::io::Error::other(format!(
                "{name} is not approved by this account: on a logged-in device, run teter machine \
                 approve {name} --fingerprint <what teter machine fingerprint shows on {name}>"
            ))
        })
}

/// The error for a machine the account does not have, naming those it has.
fn no_machine(
    name: &str,
    machines: &[MachineSessions],
    opened: impl Fn(&[u8], &[u8]) -> Option<String>,
) -> std::io::Error {
    let known: Vec<String> = machines
        .iter()
        .filter_map(|machine| opened(&machine.sealed_name, crate::machine::NAME_INFO))
        .collect();
    let known = if known.is_empty() {
        "none".to_owned()
    } else {
        known.join(", ")
    };
    std::io::Error::other(format!(
        "no machine named {name:?} in this account (it has: {known})"
    ))
}

/// The frontend settings for `target` (`machine[:session]`), from the
/// logged-in account.
pub async fn resolve(target: &str, ca_cert: Option<PathBuf>) -> std::io::Result<Config> {
    let (machine_name, session_name) = target.split_once(':').unwrap_or((target, DEFAULT_SESSION));
    let (saved, keys, machines, _) = account_sessions(ca_cert.as_deref()).await?;
    // The history a session kept on disk before a restart is sealed to the
    // account (#93): the joins of this attach take it and open it.
    if let Some(copy) = AccountKeys::from_private_bytes(keys.private_bytes().as_ref()) {
        teter_frontend::hold_account_keys(copy);
    }
    let opened = |sealed: &[u8], info: &[u8]| {
        keys.open_sealed(info, sealed)
            .ok()
            .and_then(|plain| String::from_utf8(plain.to_vec()).ok())
    };
    let machine = find_machine(&keys, &machines, machine_name, opened)?;
    // A stale record of the same name (not cleared yet) loses to the served one.
    let Some(record) = machine
        .sessions
        .iter()
        .filter(|record| signed(machine, record))
        .filter(|record| {
            opened(
                &record.sealed_name,
                &teter_backend::session_name_info(&machine.id, &record.channel),
            )
            .as_deref()
                == Some(session_name)
        })
        .max_by_key(|record| record.relay.is_some())
    else {
        return Err(no_session(machine, machine_name, session_name, opened));
    };
    let Some((relay_session, token)) = record.relay.clone() else {
        return Err(std::io::Error::other(format!(
            "{machine_name}:{session_name} is not served now (is teter link running there?)"
        )));
    };
    let secret = keys
        .open_sealed(
            &teter_local::session_key_info(&record.channel),
            &record.sealed_key,
        )
        .ok()
        .and_then(|text| Secret::parse(std::str::from_utf8(&text).ok()?).ok())
        .ok_or_else(|| {
            std::io::Error::other("the session's key does not open with this account")
        })?;
    Ok(Config {
        relay: crate::endpoint(&saved.relay, "frontend"),
        session: relay_session,
        token,
        secret,
        ca_cert,
        channel: Some(record.channel.clone()),
        history: 0,
        rows: 0,
        // A first join takes the history kept on disk, sealed to the
        // account (#93).
        sealed_history: true,
    })
}

/// A command channel to the account's machine `machine_name`, and the
/// account's keys to sign with (#79).
pub async fn command_channel(
    machine_name: &str,
    ca_cert: Option<PathBuf>,
) -> std::io::Result<(teter_client::command::Channel, AccountKeys)> {
    let (channel, keys, _) = command_channel_and_clients(machine_name, ca_cert).await?;
    Ok((channel, keys))
}

/// As [`command_channel`], with how many frontends the relay says are
/// attached to each of the machine's sessions, by channel (#135; absent from
/// a relay older than that).
pub async fn command_channel_and_clients(
    machine_name: &str,
    ca_cert: Option<PathBuf>,
) -> std::io::Result<(
    teter_client::command::Channel,
    AccountKeys,
    std::collections::HashMap<String, u32>,
)> {
    open_channel(machine_name, ca_cert, false).await
}

/// As [`command_channel`], for a new session: refused here, with why, when
/// the account keeps as many sessions as its relay allows (#104).
pub async fn command_channel_for_new(
    machine_name: &str,
    ca_cert: Option<PathBuf>,
) -> std::io::Result<(teter_client::command::Channel, AccountKeys)> {
    let (channel, keys, _) = open_channel(machine_name, ca_cert, true).await?;
    Ok((channel, keys))
}

/// A command channel to `machine_name`, with the clients of its sessions;
/// with `new_session`, refused when the account has no room for one more.
async fn open_channel(
    machine_name: &str,
    ca_cert: Option<PathBuf>,
    new_session: bool,
) -> std::io::Result<(
    teter_client::command::Channel,
    AccountKeys,
    std::collections::HashMap<String, u32>,
)> {
    let (saved, keys, machines, limits) = account_sessions(ca_cert.as_deref()).await?;
    if new_session {
        let kept = machines.iter().map(|machine| machine.sessions.len()).sum();
        if let Some(reason) = limits.and_then(|limits| limits.no_room_for_a_session(kept)) {
            return Err(std::io::Error::other(reason));
        }
    }
    let opened = |sealed: &[u8], info: &[u8]| {
        keys.open_sealed(info, sealed)
            .ok()
            .and_then(|plain| String::from_utf8(plain.to_vec()).ok())
    };
    let machine = find_machine(&keys, &machines, machine_name, opened)?;
    let Some((session, token)) = machine.relay.clone() else {
        return Err(std::io::Error::other(format!(
            "{machine_name} is not connected to the relay now (is teter link running there?)"
        )));
    };
    let channel = teter_client::command::Channel::open(
        &crate::endpoint(&saved.relay, "frontend"),
        ca_cert.as_deref(),
        session,
        token,
        machine.id.clone(),
        machine.public_key.clone(),
    )
    .await?;
    let clients = machine
        .sessions
        .iter()
        .filter_map(|record| Some((record.channel.clone(), record.clients?)))
        .collect();
    Ok((channel, keys, clients))
}