feat(auth): add dashboard jwt login
这个提交存在于:
父节点
058bfc7029
当前提交
b2856ce075
共有 4 个文件被更改,包括 268 次插入 和 85 次删除
|
|
@ -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.
|
||||
|
|
|
|||
215
src-tauri/src/auth.rs
普通文件
215
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<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"));
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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> | 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> | 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<string | null>(null);
|
||||
|
||||
async function enroll() {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
setBusy(true); setMessage(null);
|
||||
try {
|
||||
const result = await invoke<CredentialEnrollmentResult>(
|
||||
"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<CredentialEnrollmentResult>("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<JwtLoginResult>("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 (
|
||||
<section className="credential-card" aria-label={`凭据登记 ${profile.displayName}`}>
|
||||
<h4>安全凭据登记</h4>
|
||||
<p>
|
||||
密钥只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。
|
||||
</p>
|
||||
<label>
|
||||
用户名(可选,AstrBot 可用)
|
||||
<input
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
API Key / Token(一次性)
|
||||
<input
|
||||
type="password"
|
||||
value={secret}
|
||||
onChange={(event) => setSecret(event.target.value)}
|
||||
disabled={busy}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
<div className="button-row">
|
||||
<button type="button" disabled={busy || !secret.trim()} onClick={() => void enroll()}>
|
||||
登记凭据
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !profile.credentialReference}
|
||||
onClick={() => void clearCredential()}
|
||||
>
|
||||
清除凭据
|
||||
</button>
|
||||
</div>
|
||||
{profile.credentialReference ? (
|
||||
<p>当前引用:{profile.credentialReference}</p>
|
||||
<p>凭据只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。</p>
|
||||
<label>远端 ID(英文数字)<input value={remoteId} onChange={(event) => setRemoteId(event.target.value)} disabled={busy} placeholder="yokiiro01" /></label>
|
||||
{profile.authenticationType === "jwt" ? (
|
||||
<>
|
||||
<label>AstrBot Dashboard 用户名<input value={dashboardUsername} onChange={(event) => setDashboardUsername(event.target.value)} disabled={busy} autoComplete="username" /></label>
|
||||
<label>Dashboard 密码<input type="password" value={dashboardPassword} onChange={(event) => setDashboardPassword(event.target.value)} disabled={busy} autoComplete="current-password" /></label>
|
||||
<label>TOTP(可选)<input value={totp} onChange={(event) => setTotp(event.target.value)} disabled={busy} inputMode="numeric" /></label>
|
||||
<button type="button" disabled={busy || !dashboardUsername.trim() || !dashboardPassword} onClick={() => void loginJwt()}>登录 AstrBot Dashboard</button>
|
||||
</>
|
||||
) : (
|
||||
<p>尚未登记凭据</p>
|
||||
<>
|
||||
<label>API Key / Token(一次性)<input type="password" value={secret} onChange={(event) => setSecret(event.target.value)} disabled={busy} autoComplete="off" /></label>
|
||||
<button type="button" disabled={busy || !secret.trim()} onClick={() => void enroll()}>登记凭据</button>
|
||||
</>
|
||||
)}
|
||||
<button type="button" disabled={busy || !profile.credentialReference} onClick={() => void clearCredential()}>清除凭据</button>
|
||||
{profile.credentialReference ? <p>当前引用:{profile.credentialReference}</p> : <p>尚未登记凭据</p>}
|
||||
{message ? <p role="status">{message}</p> : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用