From 74fe19f7e46d87304dcd07422b27132d106da2bf Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Mon, 20 Jul 2026 16:52:29 +0800 Subject: [PATCH] feat(auth): handle jwt expiry and relogin state --- docs/implementation-queue.md | 1 + docs/progress.md | 7 +++ src-tauri/src/networking/astrbot_client.rs | 59 +++++++++++++++++++++- src-tauri/src/networking/commands.rs | 6 ++- src-tauri/src/networking/runtime.rs | 28 +++++++++- src/features/chat/ChatPanel.tsx | 9 ++++ src/styles.css | 1 + 7 files changed, 107 insertions(+), 4 deletions(-) diff --git a/docs/implementation-queue.md b/docs/implementation-queue.md index 0b61937..5dd38a4 100644 --- a/docs/implementation-queue.md +++ b/docs/implementation-queue.md @@ -141,6 +141,7 @@ otification`、`offline`。 - 远端身份已拆分为协议 ID(`remote_username`)与 BOT 称呼昵称(`remote_display_name`),两者不再共用字段。 - 2D 纸片人桌宠已从 manifest 基础推进到可运行窗口:透明、无边框、跳过任务栏、关闭后回托盘,并预留状态动作循环。 +- JWT 运行时已支持 `exp` 过期识别、401/403 状态映射和聊天界面重新登录提示。 - 不复制 Hermes 或 Codex 的私有实现;只参考交互模式和资源组织方式。 - 不在首轮实现 Live2D、Spine、3D 桌宠或用户脚本插件。 diff --git a/docs/progress.md b/docs/progress.md index 2f79585..793a199 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -191,4 +191,11 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo - 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. + +## 2026-07-20: JWT runtime expiry handling + +- AstrBot JWT profiles now pass their authentication type through the Rust runtime instead of being treated as API Key-only profiles. +- Rust checks the JWT `exp` claim before activation and maps expired credentials to `AuthExpired` without logging or returning the token. +- AstrBot 401/403 responses during probe or chat now preserve the affected slot and expose an `authExpired` runtime error. +- Chat UI shows a re-login warning for the affected slot; credentials remain managed by Windows Credential Manager. - Validation: Rust workspace tests (65), Clippy, TypeScript, ESLint, Vitest (6), and Vite build pass. diff --git a/src-tauri/src/networking/astrbot_client.rs b/src-tauri/src/networking/astrbot_client.rs index d0146cb..b720e76 100644 --- a/src-tauri/src/networking/astrbot_client.rs +++ b/src-tauri/src/networking/astrbot_client.rs @@ -3,7 +3,7 @@ use std::{collections::VecDeque, sync::Arc, time::Duration}; use desktop_protocol::{ AstrBotApiEnvelope, AstrBotAttachment, AstrBotCapabilitySnapshot, AstrBotChatRequest, AstrBotConfigListData, AstrBotModelOption, AstrBotSessionListData, AstrBotStreamMapper, - BoundGatewayEvent, ConnectionState, GatewayEvent, PROTOCOL_VERSION, + AuthenticationType, BoundGatewayEvent, ConnectionState, GatewayEvent, PROTOCOL_VERSION, derive_astrbot_server_instance_id, }; use futures_util::StreamExt; @@ -25,6 +25,7 @@ pub struct AstrBotClientConfig { /// Remote WebChat username used as session owner identity. pub remote_username: String, pub remote_display_name: Option, + pub authentication_type: AuthenticationType, /// Optional sticky session id. When absent, the first chat response supplies one. pub session_id: Option, /// Expected server identity substitute. Empty means accept first observed identity. @@ -49,6 +50,8 @@ pub enum AstrBotClientError { ChannelClosed, #[error("invalid configuration: {0}")] InvalidConfig(&'static str), + #[error("astrbot credential expired")] + CredentialExpired, } impl From for GatewayError { @@ -62,6 +65,9 @@ impl From for GatewayError { AstrBotClientError::ApiStatus(message) => GatewayError::Adapter(message), AstrBotClientError::Map(message) => GatewayError::Adapter(message), AstrBotClientError::InvalidConfig(message) => GatewayError::Adapter(message.to_owned()), + AstrBotClientError::CredentialExpired => { + GatewayError::Adapter("AstrBot authentication has expired".into()) + } } } } @@ -112,6 +118,11 @@ impl AstrBotClient { if config.api_key.expose_secret().trim().is_empty() { return Err(AstrBotClientError::InvalidConfig("api_key is required")); } + if config.authentication_type == AuthenticationType::Jwt + && jwt_is_expired(config.api_key.expose_secret()) + { + return Err(AstrBotClientError::CredentialExpired); + } let base = config.base_url.trim_end_matches('/').to_owned(); let derived = derive_astrbot_server_instance_id(&base); @@ -499,6 +510,44 @@ fn urlencoding_username(username: &str) -> String { .collect() } +fn jwt_is_expired(token: &str) -> bool { + let Some(payload) = token.split('.').nth(1).and_then(decode_base64url) else { + return false; + }; + let Ok(value) = serde_json::from_slice::(&payload) else { + return false; + }; + let Some(exp) = value.get("exp").and_then(Value::as_i64) else { + return false; + }; + exp <= time::OffsetDateTime::now_utc().unix_timestamp() +} + +fn decode_base64url(value: &str) -> Option> { + let mut output = Vec::with_capacity(value.len() * 3 / 4); + let mut buffer = 0u32; + let mut bits = 0u8; + for byte in value.bytes() { + let digit = match byte { + b'A'..=b'Z' => byte - b'A', + b'a'..=b'z' => byte - b'a' + 26, + b'0'..=b'9' => byte - b'0' + 52, + b'-' => 62, + b'_' => 63, + b'=' => break, + _ => return None, + }; + buffer = (buffer << 6) | u32::from(digit); + bits += 6; + if bits >= 8 { + bits -= 8; + output.push((buffer >> bits) as u8); + buffer &= (1 << bits) - 1; + } + } + Some(output) +} + #[cfg(test)] mod tests { use super::*; @@ -512,6 +561,7 @@ mod tests { api_key: SecretString::from(String::new()), remote_username: "user".into(), remote_display_name: None, + authentication_type: AuthenticationType::ApiKey, session_id: None, expected_server_instance_id: None, }); @@ -527,10 +577,17 @@ mod tests { api_key: SecretString::from("abk_test".to_owned()), remote_username: "desktop-companion".into(), remote_display_name: Some("Desktop Companion".into()), + authentication_type: AuthenticationType::ApiKey, session_id: Some("s1".into()), expected_server_instance_id: None, }) .expect("client"); assert!(client.server_instance_id_blocking().starts_with("astrbot-")); } + + #[test] + fn detects_expired_jwt_without_logging_or_exposing_the_token() { + assert!(jwt_is_expired("e30.eyJleHAiOjF9.signature")); + assert!(!jwt_is_expired("not-a-jwt")); + } } diff --git a/src-tauri/src/networking/commands.rs b/src-tauri/src/networking/commands.rs index 8d383f6..5c50720 100644 --- a/src-tauri/src/networking/commands.rs +++ b/src-tauri/src/networking/commands.rs @@ -156,7 +156,7 @@ fn startup_activation_request( TransportKind::AstrBotOpenApi => { let secret = secret.ok_or(RuntimeCommandError { code: "credentialMissing", - message: "Enroll an API key before probing an AstrBot profile.", + message: "Enroll an AstrBot credential before probing this profile.", })?; let api_key = String::from_utf8(secret.secret().to_vec()).map_err(|_| RuntimeCommandError { @@ -176,6 +176,7 @@ fn startup_activation_request( bearer_token: None, remote_username: Some(remote_username), remote_display_name: profile.remote_display_name.clone(), + authentication_type: profile.authentication_type, session_id: profile.sticky_session_id.clone(), expected_server_instance_id: profile.server_instance_id.clone(), }) @@ -202,6 +203,7 @@ fn startup_activation_request( bearer_token: bearer, remote_username: None, remote_display_name: None, + authentication_type: profile.authentication_type, session_id: None, expected_server_instance_id: Some(expected), }) @@ -401,6 +403,7 @@ pub async fn probe_connection_slot( bearer_token: None, remote_username: Some(remote_username), remote_display_name: profile.remote_display_name.clone(), + authentication_type: profile.authentication_type, session_id: profile.sticky_session_id.clone(), expected_server_instance_id: profile.server_instance_id.clone(), } @@ -427,6 +430,7 @@ pub async fn probe_connection_slot( bearer_token: bearer, remote_username: None, remote_display_name: None, + authentication_type: profile.authentication_type, session_id: None, expected_server_instance_id: Some(expected), } diff --git a/src-tauri/src/networking/runtime.rs b/src-tauri/src/networking/runtime.rs index 9ae3414..0d23bd8 100644 --- a/src-tauri/src/networking/runtime.rs +++ b/src-tauri/src/networking/runtime.rs @@ -40,6 +40,7 @@ pub struct SlotActivationRequest { pub bearer_token: Option, pub remote_username: Option, pub remote_display_name: Option, + pub authentication_type: desktop_protocol::AuthenticationType, pub session_id: Option, pub expected_server_instance_id: Option, } @@ -260,10 +261,17 @@ impl DualSlotRuntime { api_key, remote_username, remote_display_name: request.remote_display_name.clone(), + authentication_type: request.authentication_type, session_id: request.session_id.clone(), expected_server_instance_id: request.expected_server_instance_id.clone(), }) - .map_err(|_| RuntimeCommandError::unavailable("AstrBot client failed to start."))?; + .map_err(|error| match error { + AstrBotClientError::CredentialExpired => RuntimeCommandError { + code: "authExpired", + message: "AstrBot authentication has expired. Re-login is required.", + }, + _ => RuntimeCommandError::unavailable("AstrBot client failed to start."), + })?; match client.probe().await { Ok(_) => { runtime.snapshot.state = ConnectionState::Connected; @@ -482,6 +490,17 @@ impl DualSlotRuntime { )); } Ok(session) => break Ok((ActiveClient::AstrBot(client), session)), + Err(AstrBotClientError::HttpStatus(status)) + if status.as_u16() == 401 || status.as_u16() == 403 => + { + break Err(( + ActiveClient::AstrBot(client), + RuntimeCommandError { + code: "authExpired", + message: "AstrBot authentication has expired. Re-login is required.", + }, + )); + } Err(error) if should_retry_astrbot(&error) && attempts < 2 => { attempts += 1; let mut guard = self.inner.lock().await; @@ -520,7 +539,11 @@ impl DualSlotRuntime { runtime.snapshot.transport = transport; runtime.snapshot.server_instance_id = server_instance_id; runtime.snapshot.active_session_id = session_id; - runtime.snapshot.state = ConnectionState::ServerUnavailable; + runtime.snapshot.state = if error.code == "authExpired" { + ConnectionState::AuthExpired + } else { + ConnectionState::ServerUnavailable + }; runtime.snapshot.last_error = Some(error.message.to_owned()); Err(error) } @@ -575,6 +598,7 @@ mod tests { bearer_token: None, remote_username: None, remote_display_name: None, + authentication_type: desktop_protocol::AuthenticationType::DeviceToken, session_id: None, expected_server_instance_id: None, }) diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx index db48097..b500349 100644 --- a/src/features/chat/ChatPanel.tsx +++ b/src/features/chat/ChatPanel.tsx @@ -400,6 +400,15 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { Session:{status[selectedSlot].activeSessionId ?? "未建立"} 状态:{connectionStateLabel(status[selectedSlot].state)} + {status[selectedSlot].state === "authExpired" ? ( +
+ 认证已过期 + 请到“连接”设置重新登录 AstrBot,当前槽位不会继续发送消息。 + +
+ ) : null} {remoteSessions.length > 0 ? (
{remoteSessions.map((session) => ( diff --git a/src/styles.css b/src/styles.css index 14968e7..105b467 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1133,6 +1133,7 @@ select:focus { .chat-session { display: grid; min-width: 11rem; gap: .2rem; padding: .65rem .75rem; border: 1px solid rgb(137 175 232 / 24%); border-radius: .7rem; color: #c7d4e9; background: rgb(7 18 34 / 55%); text-align: left; } .chat-session:hover, .chat-session.active { border-color: #7db0ff; background: rgb(36 80 140 / 52%); } .chat-session small { color: #91a7c9; font-size: .7rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.warning-banner { display: flex; flex-wrap: wrap; gap: .7rem; align-items: center; } .pet-window { position: relative; display: grid; min-height: 100vh; place-items: center; overflow: hidden; color: #f7faff; background: transparent; user-select: none; } .pet-window-close { position: absolute; top: .5rem; right: .5rem; z-index: 2; width: 1.8rem; height: 1.8rem; padding: 0; border: 1px solid rgb(255 255 255 / 25%); border-radius: 999px; color: #fff; background: rgb(8 17 31 / 72%); line-height: 1; }