teter-common 26.11.7

Shared types and protocol definitions for teter
Documentation
//! Commands from a device of the account to one of its machines (#88): to
//! start or end a session, and later others.
//!
//! They travel as `input` and `output` on a command channel of the
//! machine's relay session, so the relay carries them like any other bytes.
//! The machine answers a [`ToMachine::Hello`] with a fresh
//! [`FromMachine::Challenge`]: a nonce and a one-time X25519 key, signed by
//! the machine's key. The device signs the command, bound to the machine and
//! the nonce, with the account's key, and seals it to the one-time key. The
//! machine opens it, checks the signature against the account key it pinned
//! at registration, uses the nonce once, runs the command and seals the
//! outcome to the account. The relay learns that a command went and its
//! size.

use serde::{Deserialize, Serialize};

/// What a command channel's name starts with. Session channels are hex, so
/// the `m` keeps the two apart.
pub const CHANNEL_PREFIX: &str = "cmd";

/// Whether `channel` is a command channel.
pub fn is_command_channel(channel: &str) -> bool {
    channel.starts_with(CHANNEL_PREFIX)
}

/// The most a command frame may take: room for a list of a few hundred
/// sessions (bytes go as JSON numbers).
pub const MAX_FRAME: usize = 256 * 1024;

/// From the device, as the data of an `input`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ToMachine {
    /// Asks for a challenge.
    Hello,
    /// A [`Signed`] command, sealed to the challenge's one-time key.
    Command {
        /// The sealed command.
        sealed: Vec<u8>,
    },
}

/// From the machine, as the data of an `output`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FromMachine {
    /// A fresh challenge, good for one command on this channel.
    Challenge {
        /// The nonce the command is bound to.
        nonce: Vec<u8>,
        /// The one-time X25519 key the command is sealed to.
        key: Vec<u8>,
        /// The machine's signature of [`challenge_bytes`].
        signature: Vec<u8>,
    },
    /// The [`Outcome`], sealed to the account.
    Reply {
        /// The sealed outcome.
        sealed: Vec<u8>,
        /// The machine's signature of [`reply_bytes`]: anyone can seal to
        /// the account's public keys, only the machine signs.
        signature: Vec<u8>,
    },
    /// The command was refused before it ran: no challenge, a used one, one
    /// that expired, or one that did not open or was not signed by the
    /// account.
    Refused {
        /// Why.
        reason: String,
    },
}

/// What the device asks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Command {
    /// The machine's sessions (#78).
    List,
    /// Registers session `name` and starts it; the link serves it (#78).
    New {
        /// The session's name.
        name: String,
    },
    /// Ends session `name`, as `teter kill` does on the machine.
    Kill {
        /// The session's name.
        name: String,
    },
}

/// A command and the account's signature of [`command_bytes`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Signed {
    /// The command.
    pub command: Command,
    /// The signature.
    pub signature: Vec<u8>,
}

/// How a command went.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Outcome {
    /// It ran.
    Done,
    /// The answer to [`Command::List`].
    Sessions {
        /// The sessions, by name.
        sessions: Vec<SessionInfo>,
    },
    /// It ran and failed.
    Failed {
        /// Why.
        reason: String,
    },
}

/// One of the machine's sessions, as [`Command::List`] gives it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionInfo {
    /// Its name.
    pub name: String,
    /// Its opaque ID: the channel it is served on when it runs, else its
    /// registry ID; empty for one running unregistered that holds no
    /// channel yet.
    pub id: String,
    /// Whether its session process runs now.
    pub running: bool,
    /// Its terminal's size, columns and rows, when it runs (#135); `None`
    /// from a machine older than the field.
    #[serde(default)]
    pub size: Option<(u16, u16)>,
}

/// What the machine signs in a challenge.
pub fn challenge_bytes(machine: &str, nonce: &[u8], key: &[u8]) -> Vec<u8> {
    let mut bytes = b"teter-challenge-v1 ".to_vec();
    bytes.extend_from_slice(machine.as_bytes());
    bytes.push(0);
    bytes.extend_from_slice(nonce);
    bytes.extend_from_slice(key);
    bytes
}

/// What the account signs: the command, bound to the machine and the
/// challenge's nonce.
pub fn command_bytes(machine: &str, nonce: &[u8], command: &Command) -> Vec<u8> {
    let mut bytes = b"teter-command-v1 ".to_vec();
    bytes.extend_from_slice(machine.as_bytes());
    bytes.push(0);
    bytes.extend_from_slice(nonce);
    // A command always serializes.
    bytes.extend_from_slice(&serde_json::to_vec(command).unwrap_or_default());
    bytes
}

/// What the machine signs in a reply: the sealed outcome, bound to the
/// machine and the challenge's nonce.
pub fn reply_bytes(machine: &str, nonce: &[u8], sealed: &[u8]) -> Vec<u8> {
    let mut bytes = b"teter-reply-v1 ".to_vec();
    bytes.extend_from_slice(machine.as_bytes());
    bytes.push(0);
    bytes.extend_from_slice(nonce);
    bytes.extend_from_slice(sealed);
    bytes
}

/// What a sealed command is bound to.
pub fn command_info(machine: &str, nonce: &[u8]) -> Vec<u8> {
    let mut info = b"command ".to_vec();
    info.extend_from_slice(machine.as_bytes());
    info.push(b' ');
    info.extend_from_slice(crate::account::hex(nonce).as_bytes());
    info
}

/// What a sealed outcome is bound to.
pub fn reply_info(machine: &str, nonce: &[u8]) -> Vec<u8> {
    let mut info = b"command reply ".to_vec();
    info.extend_from_slice(machine.as_bytes());
    info.push(b' ');
    info.extend_from_slice(crate::account::hex(nonce).as_bytes());
    info
}