openbutler-protocol 0.0.1

The wire contract between the OpenButler daemon and its clients: frame encoding, action envelopes, and the shared state types.
Documentation
//! Connection admission: the only frames an unauthenticated remote socket
//! may offer, and the exact wordings the host answers them with.
//!
//! Two credentials, two lifetimes. `login` bootstraps a device: the account
//! username and password travel once, and the host answers with a session
//! token. Every later connection on that device offers `auth` with that token.
//! The password therefore never becomes a per-connection credential, and the
//! token never has to be typed, copied, or stored by hand.
//!
//! `pair` is the legacy bootstrap (a one-time code minted on the host). It is
//! still classified here because the running host has not switched to accounts
//! yet; the slice that wires `login` also removes it, `PAIR_FAILED`, and the
//! pairing store. Both frames are classified during the transition, so a
//! half-migrated pair of binaries cannot misread each other.
//!
//! This module owns classification and wording only: verification, the account
//! and session stores, and the sign-in throttle live in the daemon, which
//! enforces the gate before dispatch sees anything.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::constants::{
    DAEMON_PROTOCOL_VERSION, MAX_DEVICE_LENGTH, MAX_ID_LENGTH, MAX_PASSWORD_LENGTH,
    MAX_SESSION_TOKEN_LENGTH, MAX_USERNAME_LENGTH, SESSION_TOKEN_BYTES,
};
use crate::envelope::js_length;

/// Refusal for a first frame that is neither `login` nor `auth`.
pub const REMOTE_FIRST_FRAME_REFUSED: &str = "This connection is remote and must authenticate first: send { version, id, action: \"login\", username, password } as the first frame.";
/// Answer when a session token is unknown, expired, or revoked; the
/// connection closes.
pub const SESSION_REFUSED: &str = "Sign-in needed: this device's session is unknown, expired, or revoked. Run openbutler connect again.";
/// Answer when the account username or password is wrong. It never says which
/// half was wrong, and an unknown username costs the same verification as a
/// known one, so the answer and its latency are both useless as an oracle.
pub const LOGIN_FAILED: &str = "Sign-in failed: that username or password is not right.";
/// Answer while the sign-in lock is armed. Fixed wording, no interpolated
/// number: the window is a constant the tests can pin byte for byte.
pub const LOGIN_THROTTLED: &str = "Too many sign-in attempts. Wait a minute and try again.";
/// Answer to `login` when the host has no account yet. The host binds no
/// remote listener in that state either, so this is a race-window answer, not
/// the normal path.
pub const NO_ACCOUNT: &str = "This host has no admin account yet. Create one on the host machine with: openbutler admin create";
/// Answer when the account already holds the maximum number of devices.
pub const TOO_MANY_DEVICES: &str = "This account already has 10 devices. Revoke one on the host with: openbutler device revoke <id>";

/// Legacy: answer when the pairing code is wrong, expired, or already
/// consumed. Removed with the `pair` frame.
pub const PAIR_FAILED: &str = "Pairing failed: that code is wrong, expired, or already used.";
/// Legacy: answer when the token path rejects a credential. Replaced by
/// [`SESSION_REFUSED`] when the host switches to accounts.
pub const AUTH_FAILED: &str = "Authentication failed: this host does not accept that token.";

/// What a remote socket's first frame turned out to be.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FirstFrame<'a> {
    /// A device signing in with the account credentials. `device` is not part
    /// of the verdict: it is a label, not a credential, and the host clamps it
    /// when it stores the session.
    Login {
        id: &'a str,
        username: &'a str,
        password: &'a str,
    },
    /// A device offering its session token.
    Auth { id: &'a str, token: &'a str },
    /// Legacy: a client offering the owner's one-time pairing code.
    Pair { id: &'a str, code: &'a str },
    /// Anything else: answered with [`REMOTE_FIRST_FRAME_REFUSED`] and closed.
    Refused { id: &'a str },
}

/// The success payload of an accepted `auth` frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthSuccess {
    /// Always `true`: a refusal is a failure envelope, never this shape.
    pub authenticated: bool,
}

/// The success payload of an accepted `login` frame: the device's session,
/// whose token exists in plaintext exactly once — here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoginSuccess {
    /// The session id `device list` prints and `device revoke` takes.
    pub device_id: String,
    /// The session token this device presents on every later connection.
    pub token: String,
    /// When the session stops being accepted (ISO-8601, millisecond, `Z`).
    pub expires_at: String,
}

/// Legacy: the success payload of an accepted `pair` frame.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PairSuccess {
    /// The freshly minted token, in plaintext for the only time.
    pub token: String,
}

/// Typed admission input. Unknown fields are ignored without building a JSON
/// value tree; known fields retain their JSON types so malformed credentials
/// can still be refused with the request id.
#[derive(Debug, Deserialize)]
pub struct AdmissionFrame {
    #[serde(default)]
    version: Value,
    #[serde(default)]
    id: Option<Value>,
    #[serde(default)]
    action: Option<Value>,
    #[serde(default)]
    username: Option<Value>,
    #[serde(default)]
    password: Option<Value>,
    #[serde(default)]
    token: Option<Value>,
    #[serde(default)]
    code: Option<Value>,
    #[serde(default)]
    device: Option<Value>,
}

impl AdmissionFrame {
    pub fn classify(&self) -> FirstFrame<'_> {
        classify_fields(
            self.id.as_ref().and_then(Value::as_str).unwrap_or(""),
            Some(&self.version),
            self.action.as_ref().and_then(Value::as_str),
            self.username.as_ref().and_then(Value::as_str),
            self.password.as_ref().and_then(Value::as_str),
            self.token.as_ref().and_then(Value::as_str),
            self.code.as_ref().and_then(Value::as_str),
        )
    }

    pub fn device_label(&self) -> String {
        device_label_value(self.device.as_ref())
    }
}

/// Parses one bounded admission object without allocating unknown payload data.
pub fn parse_admission_frame(frame: &[u8]) -> Option<AdmissionFrame> {
    if frame.iter().find(|byte| !byte.is_ascii_whitespace()) != Some(&b'{') {
        return None;
    }
    serde_json::from_slice(frame).ok()
}

/// Classifies a parsed first frame. Invalid ids are not echoed back.
pub fn classify_first_frame(frame: &Value) -> FirstFrame<'_> {
    let record = frame.as_object();
    let field = |name: &str| record.and_then(|record| record.get(name));
    classify_fields(
        field("id").and_then(Value::as_str).unwrap_or(""),
        field("version"),
        field("action").and_then(Value::as_str),
        field("username").and_then(Value::as_str),
        field("password").and_then(Value::as_str),
        field("token").and_then(Value::as_str),
        field("code").and_then(Value::as_str),
    )
}

fn classify_fields<'a>(
    id: &'a str,
    version: Option<&Value>,
    action: Option<&'a str>,
    username: Option<&'a str>,
    password: Option<&'a str>,
    token: Option<&'a str>,
    code: Option<&'a str>,
) -> FirstFrame<'a> {
    let valid_id = (1..=MAX_ID_LENGTH).contains(&js_length(id));
    let refused_id = if valid_id { id } else { "" };
    let well_formed =
        valid_id && version.and_then(Value::as_f64) == Some(f64::from(DAEMON_PROTOCOL_VERSION));
    if well_formed {
        if action == Some("login")
            && let Some(username) = username
            && let Some(password) = password
            && (1..=MAX_USERNAME_LENGTH).contains(&js_length(username))
            && (1..=MAX_PASSWORD_LENGTH).contains(&js_length(password))
        {
            return FirstFrame::Login {
                id,
                username,
                password,
            };
        }
        if action == Some("auth")
            && let Some(token) = token
            && (1..=MAX_SESSION_TOKEN_LENGTH).contains(&js_length(token))
        {
            return FirstFrame::Auth { id, token };
        }
        if action == Some("pair")
            && let Some(code) = code
            && !code.is_empty()
        {
            return FirstFrame::Pair { id, code };
        }
    }
    FirstFrame::Refused { id: refused_id }
}

/// Returns whether a token has the exact shape issued by `SessionStore`.
pub fn is_session_token_shape(token: &str) -> bool {
    let Some(encoded) = token.strip_prefix(crate::constants::AUTH_TOKEN_PREFIX) else {
        return false;
    };
    encoded.len() == (SESSION_TOKEN_BYTES * 8).div_ceil(6)
        && encoded
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}

/// The device label is a display name, never a credential.
pub fn device_label(frame: &Value) -> String {
    device_label_value(frame.as_object().and_then(|record| record.get("device")))
}

fn device_label_value(value: Option<&Value>) -> String {
    value
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|label| (1..=MAX_DEVICE_LENGTH).contains(&js_length(label)))
        .unwrap_or("unknown")
        .to_owned()
}