diff --git a/docs/progress.md b/docs/progress.md index 2549da9..0df8ff2 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -176,3 +176,11 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo - Extended the pet-pack manifest with optional animation IDs, loop flags, and bounded movement modes for 2D paper-character actions. - Updated the pet importer copy and JWT selection UI; full Dashboard login, JWT expiry handling, and background pet window controller remain next-stage work. - Validation: Rust workspace tests, TypeScript, ESLint, Vitest (6), and Vite production build pass. + +## 2026-07-20: JWT login IPC + +- Added a Rust-owned login_profile_jwt command for AstrBot Dashboard login at /api/v1/auth/login. +- Dashboard username, password, and optional TOTP stay inside Rust; successful JWTs are written to Windows Credential Manager and the Profile is switched to JWT authentication. +- Added Profile UI fields for JWT login and retained API Key/device-token enrollment for non-JWT profiles. +- Full JWT expiry/401 re-login UX and nickname/remote-ID separation remain next increments. +- Validation: Rust workspace tests (65), Clippy, TypeScript, ESLint, Vitest (6), and Vite build pass. diff --git a/src-tauri/src/auth.rs b/src-tauri/src/auth.rs new file mode 100644 index 0000000..3971b98 --- /dev/null +++ b/src-tauri/src/auth.rs @@ -0,0 +1,215 @@ +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, +} + +#[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 { + login_jwt(&database, &WindowsCredentialStore, request).await +} + +async fn login_jwt( + database: &ApplicationDatabase, + store: &impl SecureCredentialStore, + request: JwtLoginRequest, +) -> Result { + 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")); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b48e17f..a1040c8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,4 @@ +pub mod auth; pub mod credentials; pub mod database; pub mod diagnostics; @@ -259,6 +260,7 @@ pub fn run() { _ => {} }) .invoke_handler(tauri::generate_handler![ + auth::login_profile_jwt, bootstrap_status, open_quick_chat_window, open_main_window, diff --git a/src/features/profiles/CredentialEnrollmentCard.tsx b/src/features/profiles/CredentialEnrollmentCard.tsx index eaaa7a6..47d98d3 100644 --- a/src/features/profiles/CredentialEnrollmentCard.tsx +++ b/src/features/profiles/CredentialEnrollmentCard.tsx @@ -1,109 +1,67 @@ -import { useState } from "react"; +import { useState } from "react"; import { invoke } from "@tauri-apps/api/core"; + import type { AuthenticationType, ConnectionProfile } from "../../types/profile"; -interface CredentialEnrollmentResult { - profileId: string; - credentialReference: string; - authenticationType: AuthenticationType; -} - -interface Props { - profile: ConnectionProfile; - onChanged: () => Promise | void; -} +interface CredentialEnrollmentResult { profileId: string; credentialReference: string; authenticationType: AuthenticationType; } +interface JwtLoginResult { profileId: string; credentialReference: string; dashboardUsername: string; authenticationType: "jwt"; } +interface Props { profile: ConnectionProfile; onChanged: () => Promise | void; } export function CredentialEnrollmentCard({ profile, onChanged }: Props) { const [secret, setSecret] = useState(""); - const [username, setUsername] = useState(profile.remoteUsername ?? ""); + const [remoteId, setRemoteId] = useState(profile.remoteUsername ?? ""); + const [dashboardUsername, setDashboardUsername] = useState(""); + const [dashboardPassword, setDashboardPassword] = useState(""); + const [totp, setTotp] = useState(""); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(null); async function enroll() { - setBusy(true); - setMessage(null); + setBusy(true); setMessage(null); try { - const result = await invoke( - "enroll_profile_credential", - { - request: { - profileId: profile.id, - authenticationType: profile.authenticationType, - secret, - username: username.trim() || undefined, - }, - }, - ); - setSecret(""); - setMessage(`已登记凭据引用 ${result.credentialReference}`); - await onChanged(); - } catch (error) { - setMessage( - error instanceof Error ? error.message : "凭据登记失败(详情未包含密钥)。", - ); - } finally { - setBusy(false); - } + const result = await invoke("enroll_profile_credential", { request: { profileId: profile.id, authenticationType: profile.authenticationType, secret, username: remoteId.trim() || undefined } }); + setSecret(""); setMessage(`已登记凭据引用 ${result.credentialReference}`); await onChanged(); + } catch (error) { setMessage(error instanceof Error ? error.message : "凭据登记失败。"); } + finally { setBusy(false); } + } + + async function loginJwt() { + setBusy(true); setMessage(null); + try { + const result = await invoke("login_profile_jwt", { request: { profileId: profile.id, username: dashboardUsername.trim(), password: dashboardPassword, totp: totp.trim() || undefined } }); + setDashboardPassword(""); setTotp(""); setMessage(`JWT 登录成功,凭据引用 ${result.credentialReference}`); await onChanged(); + } catch (error) { setMessage(error instanceof Error ? error.message : "JWT 登录失败。"); } + finally { setBusy(false); } } async function clearCredential() { - setBusy(true); - setMessage(null); - try { - await invoke("clear_profile_credential", { profileId: profile.id }); - setMessage("已清除凭据引用"); - await onChanged(); - } catch (error) { - setMessage( - error instanceof Error ? error.message : "清除凭据失败。", - ); - } finally { - setBusy(false); - } + setBusy(true); setMessage(null); + try { await invoke("clear_profile_credential", { profileId: profile.id }); setMessage("已清除凭据引用"); await onChanged(); } + catch (error) { setMessage(error instanceof Error ? error.message : "清除凭据失败。"); } + finally { setBusy(false); } } return (

安全凭据登记

-

- 密钥只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。 -

- - -
- - -
- {profile.credentialReference ? ( -

当前引用:{profile.credentialReference}

+

凭据只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。

+ + {profile.authenticationType === "jwt" ? ( + <> + + + + + ) : ( -

尚未登记凭据

+ <> + + + )} + + {profile.credentialReference ?

当前引用:{profile.credentialReference}

:

尚未登记凭据

} {message ?

{message}

: null}
); -} +}