use std::{net::SocketAddr, time::SystemTime};
use bytes::Bytes;
use http_body_util::{BodyExt, Full, Limited};
use hyper::{body::Incoming, header, Method, Request, Response, StatusCode};
use rho_protocol::{PairRequest, PairResponse};
use super::{
pairing_codes::{CodeRefused, DeviceName, PairingCodeSet},
server::{refusal, Body, TokenLoader},
tokens::DaemonTokenSet,
};
use crate::app::mcp_server::token_store;
pub(super) const PAIR_ENDPOINT: &str = "/pair";
const MAX_BODY_BYTES: usize = 4 * 1024;
const NAME_MAX: usize = 64;
const PLATFORM_MAX: usize = 32;
const FALLBACK_NAME: &str = "device";
#[derive(Debug)]
pub(super) enum RedeemRefused {
Code(CodeRefused),
Failed(anyhow::Error),
}
pub(super) async fn redeem_in_store(
code: String,
device_name: String,
platform: Option<String>,
) -> Result<PairResponse, RedeemRefused> {
tokio::task::spawn_blocking(move || {
let now = unix_now();
let name = token_store::update(|codes: &mut PairingCodeSet| Ok(codes.take(&code, now)))
.map_err(RedeemRefused::Failed)?
.map_err(RedeemRefused::Code)?;
token_store::update(|tokens: &mut DaemonTokenSet| {
pair_device(tokens, name, &device_name, platform)
})
.map_err(RedeemRefused::Failed)
})
.await
.map_err(|error| RedeemRefused::Failed(error.into()))?
}
pub(super) fn pair_device(
tokens: &mut DaemonTokenSet,
name: DeviceName,
device_name: &str,
platform: Option<String>,
) -> anyhow::Result<PairResponse> {
let name = match name {
DeviceName::Chosen(name) => name,
DeviceName::FromDevice => unclaimed(&token_name(device_name), tokens),
};
let token = tokens.rotate(&name)?;
tokens.set_platform(&name, platform);
Ok(PairResponse::new(token.secret(), name))
}
fn token_name(device_name: &str) -> String {
let mut name = String::new();
let mut gap = false;
for character in device_name.chars() {
if character.is_ascii_alphanumeric() || character == '_' {
if gap && !name.is_empty() {
name.push('-');
}
gap = false;
name.push(character);
} else if character == '-' || character.is_whitespace() || character == '.' {
gap = true;
}
}
name.truncate(NAME_MAX);
let name = name.trim_end_matches('-');
if name.is_empty() {
FALLBACK_NAME.to_owned()
} else {
name.to_owned()
}
}
fn unclaimed(base: &str, tokens: &DaemonTokenSet) -> String {
if !tokens.contains(base) {
return base.to_owned();
}
(2_u32..)
.map(|number| {
let suffix = format!("-{number}");
let stem = &base[..base.len().min(NAME_MAX - suffix.len())];
format!("{stem}{suffix}")
})
.find(|name| !tokens.contains(name))
.expect("some suffix is free")
}
fn platform(raw: Option<&str>) -> Option<String> {
let platform: String = raw?
.chars()
.filter(|character| {
character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
})
.take(PLATFORM_MAX)
.collect();
(!platform.is_empty()).then_some(platform)
}
pub(super) async fn serve(
tokens: &impl TokenLoader,
request: Request<Incoming>,
peer: SocketAddr,
) -> Response<Body> {
let refused = |status: StatusCode, reason: &str| {
eprintln!("rho daemon serve: refused a pairing from {peer}: {reason}");
no_store(refusal(status, reason))
};
if request.method() != Method::POST {
let mut response = refused(StatusCode::METHOD_NOT_ALLOWED, "method not allowed");
response
.headers_mut()
.insert(header::ALLOW, header::HeaderValue::from_static("POST"));
return response;
}
if !is_json(&request) {
return refused(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"send the pairing as application/json",
);
}
let Ok(body) = Limited::new(request.into_body(), MAX_BODY_BYTES)
.collect()
.await
else {
return refused(
StatusCode::BAD_REQUEST,
"the pairing's body could not be read, or is over 4 KiB",
);
};
let Ok(pair) = serde_json::from_slice::<PairRequest>(&body.to_bytes()) else {
return refused(
StatusCode::BAD_REQUEST,
"the pairing is not {code, device_name, platform}",
);
};
let platform = platform(pair.platform.as_deref());
let device_name = pair.device_name.clone();
match tokens
.redeem(pair.code, pair.device_name, platform.clone())
.await
{
Ok(paired) => {
eprintln!(
"rho daemon serve: paired device {:?} ({device_name:?}, platform {platform:?}) from {peer}",
paired.name
);
let body = serde_json::to_vec(&paired).expect("two strings encode");
let mut response = Response::new(Full::new(Bytes::from(body)).boxed());
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
);
no_store(response)
}
Err(RedeemRefused::Code(why @ CodeRefused::Unknown)) => {
refused(StatusCode::FORBIDDEN, &why.to_string())
}
Err(RedeemRefused::Code(why @ CodeRefused::Expired)) => {
refused(StatusCode::GONE, &why.to_string())
}
Err(RedeemRefused::Failed(error)) => {
eprintln!("rho daemon serve: could not pair a device from {peer}: {error:#}");
no_store(refusal(
StatusCode::INTERNAL_SERVER_ERROR,
"could not pair the device; the bridge's log says why",
))
}
}
}
fn is_json<B>(request: &Request<B>) -> bool {
request
.headers()
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"))
}
fn no_store(mut response: Response<Body>) -> Response<Body> {
response.headers_mut().insert(
header::CACHE_CONTROL,
header::HeaderValue::from_static("no-store"),
);
response
}
fn unix_now() -> u64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs())
.unwrap_or_default()
}
#[cfg(test)]
#[path = "redeem_tests.rs"]
mod tests;