AstrBot-Desktop/src-tauri/src/auth.rs

216 行
6.5 KiB
Rust

2026-07-20 16:12:11 +08:00
use desktop_protocol::AuthenticationType;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use uuid::Uuid;
use crate::database::{ApplicationDatabase, DatabaseError};
use crate::secure_store::{
CredentialReference, SecretCredential, SecureCredentialStore, WindowsCredentialStore,
};
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct JwtLoginRequest {
pub profile_id: String,
pub username: String,
pub password: String,
#[serde(default)]
pub totp: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JwtLoginResult {
pub profile_id: String,
pub credential_reference: String,
pub dashboard_username: String,
pub authentication_type: AuthenticationType,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JwtLoginError {
pub code: &'static str,
pub message: &'static str,
}
impl JwtLoginError {
fn validation(message: &'static str) -> Self {
Self {
code: "validationFailed",
message,
}
}
fn network() -> Self {
Self {
code: "networkError",
message: "AstrBot login request failed.",
}
}
fn rejected() -> Self {
Self {
code: "loginRejected",
message: "AstrBot rejected the login credentials.",
}
}
fn response() -> Self {
Self {
code: "invalidResponse",
message: "AstrBot returned an invalid login response.",
}
}
fn database() -> Self {
Self {
code: "databaseUnavailable",
message: "The local profile database is unavailable.",
}
}
fn store() -> Self {
Self {
code: "secureStoreUnavailable",
message: "Windows Credential Manager is unavailable.",
}
}
fn not_found() -> Self {
Self {
code: "notFound",
message: "The connection profile no longer exists.",
}
}
}
impl std::fmt::Display for JwtLoginError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.message)
}
}
impl std::error::Error for JwtLoginError {}
#[tauri::command]
pub async fn login_profile_jwt(
database: tauri::State<'_, ApplicationDatabase>,
request: JwtLoginRequest,
) -> Result<JwtLoginResult, JwtLoginError> {
login_jwt(&database, &WindowsCredentialStore, request).await
}
async fn login_jwt(
database: &ApplicationDatabase,
store: &impl SecureCredentialStore,
request: JwtLoginRequest,
) -> Result<JwtLoginResult, JwtLoginError> {
if Uuid::parse_str(&request.profile_id).is_err() {
return Err(JwtLoginError::validation("profile_id must be a UUID."));
}
if request.username.trim().is_empty() || request.username.len() > 256 {
return Err(JwtLoginError::validation("dashboard username is invalid."));
}
if request.password.is_empty() || request.password.len() > 1024 {
return Err(JwtLoginError::validation("dashboard password is invalid."));
}
if request
.totp
.as_deref()
.is_some_and(|value| value.len() > 128)
{
return Err(JwtLoginError::validation("TOTP value is invalid."));
}
let profile = database
.profile(&request.profile_id)
.map_err(|_| JwtLoginError::database())?
.ok_or_else(JwtLoginError::not_found)?;
let base_url = profile.base_url.trim_end_matches('/');
let mut payload = serde_json::json!({
"username": request.username.trim(),
"password": request.password,
});
if let Some(totp) = request
.totp
.as_deref()
.filter(|value| !value.trim().is_empty())
{
payload["totp"] = Value::String(totp.trim().to_owned());
}
let response = reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(5))
.timeout(std::time::Duration::from_secs(20))
.build()
.map_err(|_| JwtLoginError::network())?
.post(format!("{base_url}/api/v1/auth/login"))
.json(&payload)
.send()
.await
.map_err(|_| JwtLoginError::network())?;
if response.status() == StatusCode::UNAUTHORIZED || response.status() == StatusCode::FORBIDDEN {
return Err(JwtLoginError::rejected());
}
if !response.status().is_success() {
return Err(JwtLoginError::network());
}
let body: Value = response
.json()
.await
.map_err(|_| JwtLoginError::response())?;
let token = body
.get("data")
.and_then(|data| data.get("token"))
.and_then(Value::as_str)
.or_else(|| body.get("token").and_then(Value::as_str))
.filter(|value| !value.trim().is_empty())
.ok_or_else(JwtLoginError::response)?;
if token.len() > 2_560 {
return Err(JwtLoginError::response());
}
let reference = CredentialReference::new();
let credential = SecretCredential::with_username(
Some(request.username.trim().to_owned()),
token.as_bytes().to_vec(),
)
.map_err(|_| JwtLoginError::store())?;
store
.write(reference, &credential)
.map_err(|_| JwtLoginError::store())?;
let mut updated = profile;
if let Some(previous) = updated
.credential_reference
.as_ref()
.and_then(|value| Uuid::parse_str(value).ok())
.map(CredentialReference::from_uuid)
{
let _ = store.delete(previous);
}
updated.credential_reference = Some(reference.as_uuid().to_string());
updated.authentication_type = AuthenticationType::Jwt;
updated.updated_at = OffsetDateTime::now_utc()
.format(&Rfc3339)
.map_err(|_| JwtLoginError::database())?;
database
.update_profile(&updated)
.map_err(|error| match error {
DatabaseError::ProfileNotFound => JwtLoginError::not_found(),
_ => JwtLoginError::database(),
})?;
Ok(JwtLoginResult {
profile_id: updated.id,
credential_reference: reference.as_uuid().to_string(),
dashboard_username: request.username.trim().to_owned(),
authentication_type: AuthenticationType::Jwt,
})
}
#[cfg(test)]
mod tests {
#[test]
fn extracts_token_from_nested_response() {
let body = serde_json::json!({ "status": "ok", "data": { "token": "jwt-value" } });
assert_eq!(body["data"]["token"].as_str(), Some("jwt-value"));
}
}