use axum::{Json, extract::State}; use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; use tracing::{error, info}; use tranquil_db_traits::OAuthRepository; use tranquil_pds::api::SuccessResponse; use tranquil_pds::api::error::{ApiError, DbResultExt}; use tranquil_types::DeviceId; use tranquil_pds::auth::{Active, Auth}; use tranquil_pds::state::AppState; const TRUST_DURATION_DAYS: i64 = 30; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum DeviceTrustState { Untrusted, Trusted, Expired, } impl DeviceTrustState { pub fn from_timestamps( trusted_at: Option>, trusted_until: Option>, ) -> Self { match (trusted_at, trusted_until) { (Some(_), Some(until)) if until > Utc::now() => Self::Trusted, (Some(_), Some(_)) => Self::Expired, _ => Self::Untrusted, } } pub fn is_trusted(&self) -> bool { matches!(self, Self::Trusted) } pub fn is_expired(&self) -> bool { matches!(self, Self::Expired) } pub fn as_str(&self) -> &'static str { match self { Self::Untrusted => "untrusted", Self::Trusted => "trusted", Self::Expired => "expired", } } } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustedDevice { pub id: DeviceId, pub user_agent: Option, pub friendly_name: Option, pub trusted_at: Option>, pub trusted_until: Option>, pub last_seen_at: DateTime, pub trust_state: DeviceTrustState, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct ListTrustedDevicesOutput { pub devices: Vec, } pub async fn list_trusted_devices( State(state): State, auth: Auth, ) -> Result, ApiError> { let rows = state .repos .oauth .list_trusted_devices(&auth.did) .await .log_db_err("listing trusted devices")?; let devices = rows .into_iter() .map(|row| { let trust_state = DeviceTrustState::from_timestamps(row.trusted_at, row.trusted_until); TrustedDevice { id: row.id, user_agent: row.user_agent, friendly_name: row.friendly_name, trusted_at: row.trusted_at, trusted_until: row.trusted_until, last_seen_at: row.last_seen_at, trust_state, } }) .collect(); Ok(Json(ListTrustedDevicesOutput { devices })) } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct RevokeTrustedDeviceInput { pub device_id: DeviceId, } pub async fn revoke_trusted_device( State(state): State, auth: Auth, Json(input): Json, ) -> Result, ApiError> { match state .repos .oauth .device_belongs_to_user(&input.device_id, &auth.did) .await { Ok(true) => {} Ok(false) => { return Err(ApiError::DeviceNotFound); } Err(e) => { error!("DB error: {:?}", e); return Err(ApiError::InternalError(None)); } } state .repos .oauth .delete_account_device(&auth.did, &input.device_id) .await .log_db_err("forgetting remembered device")?; info!(did = %&auth.did, device_id = %input.device_id, "Remembered device forgotten"); Ok(Json(SuccessResponse { success: true })) } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct RememberedAppChoice { pub client_id: tranquil_types::ClientId, pub scopes: Vec, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct ListRememberedAppChoicesOutput { pub choices: Vec, } pub async fn list_remembered_app_choices( State(state): State, auth: Auth, ) -> Result, ApiError> { let rows = state .repos .oauth .list_scope_preference_clients(&auth.did) .await .log_db_err("listing remembered app choices")?; Ok(Json(ListRememberedAppChoicesOutput { choices: rows .into_iter() .map(|row| RememberedAppChoice { client_id: row.client_id, scopes: row .preferences .into_iter() .filter(|preference| preference.granted) .map(|preference| preference.scope) .collect(), }) .collect(), })) } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ForgetRememberedAppChoiceInput { pub client_id: tranquil_types::ClientId, } pub async fn forget_remembered_app_choice( State(state): State, auth: Auth, Json(input): Json, ) -> Result, ApiError> { state .repos .oauth .delete_scope_preferences(&auth.did, &input.client_id) .await .log_db_err("forgetting remembered app choice")?; Ok(Json(SuccessResponse { success: true })) } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct UpdateTrustedDeviceInput { pub device_id: DeviceId, pub friendly_name: Option, } pub async fn update_trusted_device( State(state): State, auth: Auth, Json(input): Json, ) -> Result, ApiError> { match state .repos .oauth .device_belongs_to_user(&input.device_id, &auth.did) .await { Ok(true) => {} Ok(false) => { return Err(ApiError::DeviceNotFound); } Err(e) => { error!("DB error: {:?}", e); return Err(ApiError::InternalError(None)); } } state .repos .oauth .update_device_friendly_name(&input.device_id, &auth.did, input.friendly_name.as_deref()) .await .log_db_err("updating device friendly name")?; info!(did = %auth.did, device_id = %input.device_id, "Trusted device updated"); Ok(Json(SuccessResponse { success: true })) } pub async fn get_device_trust_state( oauth_repo: &dyn OAuthRepository, device_id: &DeviceId, did: &tranquil_types::Did, ) -> DeviceTrustState { match oauth_repo.get_device_trust_info(device_id, did).await { Ok(Some(info)) => DeviceTrustState::from_timestamps(info.trusted_at, info.trusted_until), _ => DeviceTrustState::Untrusted, } } pub async fn is_device_trusted( oauth_repo: &dyn OAuthRepository, device_id: &DeviceId, did: &tranquil_types::Did, ) -> bool { get_device_trust_state(oauth_repo, device_id, did) .await .is_trusted() } pub async fn trust_device( oauth_repo: &dyn OAuthRepository, device_id: &DeviceId, did: &tranquil_types::Did, ) -> Result<(), tranquil_db_traits::DbError> { let now = Utc::now(); let trusted_until = now + Duration::days(TRUST_DURATION_DAYS); oauth_repo .trust_device(device_id, did, now, trusted_until) .await } pub async fn extend_device_trust( oauth_repo: &dyn OAuthRepository, device_id: &DeviceId, did: &tranquil_types::Did, ) -> Result<(), tranquil_db_traits::DbError> { let trusted_until = Utc::now() + Duration::days(TRUST_DURATION_DAYS); oauth_repo .extend_device_trust(device_id, did, trusted_until) .await }