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;
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.";
pub const SESSION_REFUSED: &str = "Sign-in needed: this device's session is unknown, expired, or revoked. Run openbutler connect again.";
pub const LOGIN_FAILED: &str = "Sign-in failed: that username or password is not right.";
pub const LOGIN_THROTTLED: &str = "Too many sign-in attempts. Wait a minute and try again.";
pub const NO_ACCOUNT: &str = "This host has no admin account yet. Create one on the host machine with: openbutler admin create";
pub const TOO_MANY_DEVICES: &str = "This account already has 10 devices. Revoke one on the host with: openbutler device revoke <id>";
pub const PAIR_FAILED: &str = "Pairing failed: that code is wrong, expired, or already used.";
pub const AUTH_FAILED: &str = "Authentication failed: this host does not accept that token.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FirstFrame<'a> {
Login {
id: &'a str,
username: &'a str,
password: &'a str,
},
Auth { id: &'a str, token: &'a str },
Pair { id: &'a str, code: &'a str },
Refused { id: &'a str },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthSuccess {
pub authenticated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoginSuccess {
pub device_id: String,
pub token: String,
pub expires_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PairSuccess {
pub token: String,
}
#[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())
}
}
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()
}
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 }
}
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'_'))
}
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()
}