feat(app-iced): M114 账户页三轨登录(微软正版 / 第三方皮肤站 / 本地档案)
- 账户页:当前账户卡 + 全部账户列表 + 空态三入口 + 皮肤区;五项动作(添加/切换/删除/重新登录/校验) - 三轨添加流程:设备码(用户码+链接+倒计时+过期重试+取消)、授权码(浏览器+可复制链接+取消)、 本地档案(名字校验)、第三方站(服务地址 + 服务发现校验 + 密码登录,密码掩码且用完即弃) - 导航:账户为一等页,入口是轨底头像位(未登录=描边剪影 / 已登录=首字母块+名字;窄高收成图标条) - 凭据红线:DTO 侧形状脱敏 + 状态层二次脱敏 + 密码掩码;Inject-JWT 测试断言视图模型干净(已做变异取证) - presenter:authlib 登录/服务发现/皮肤抓取(复用下载引擎的 HTTP 客户端,无新增依赖)、 皮肤原图经 DTO 到 UI 裁剪成头像(既有 image 依赖,未改 Cargo.toml) - i18n:新增 account 域 51 条中英文案(离线档案口径全量写入),金表同步
This commit is contained in:
1 parent
e7b04c4afe
commit
1ff00bbe50
43 files changed
+4343
-117
No files matched your search
@@ -3,6 +3,19 @@
|
||||
//! **凭据红线**:本模块(以及整个 `crate::dto`)只有 [`AccountView`] 这种公开字段视图。
|
||||
//! `core::auth` 的 `Credentials` / `MicrosoftSession` / token 永远不进 app 层——
|
||||
//! host 侧在拿到账户快照的那一刻就丢掉凭据,只留「能显示什么」。
|
||||
//!
|
||||
//! | 文件 | 职责 |
|
||||
//! |---|---|
|
||||
//! | 本文件 | 账户/登录**可见状态**(全部是可上屏字段) |
|
||||
//! | [`redact`] | 形状脱敏:JWT / 不透明串 / `token=...` 一律抹掉(第二道脱敏器) |
|
||||
//! | `tests` | 契约 round-trip + 凭据红线的入口断言 |
|
||||
|
||||
mod redact;
|
||||
#[cfg(test)]
|
||||
#[path = "accounts/tests.rs"]
|
||||
mod tests;
|
||||
|
||||
pub use redact::{looks_like_jwt, redact, REDACTED};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -18,7 +31,7 @@ pub enum AccountKind {
|
||||
}
|
||||
|
||||
impl AccountKind {
|
||||
/// 徽标文字。
|
||||
/// 徽标文字(CLI/终端用;GUI 走 i18n 词表,不读这里的中文)。
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Offline => "离线",
|
||||
@@ -60,9 +73,63 @@ pub struct AccountView {
|
||||
/// 登录名(微软轨才有;可空)
|
||||
pub login_name: String,
|
||||
/// 创建时间展示串(`2026-10-31 20:12`)
|
||||
///
|
||||
/// 口径:core 的 `AccountMeta` 只有 `created_at_ms`,**没有 last-used**,所以列表上贴的是
|
||||
/// 「添加于 {created}」,不伪造「最近使用」(缺口登记在 M114 报告)。
|
||||
pub created: String,
|
||||
/// 是否是当前启动使用的账户
|
||||
pub active: bool,
|
||||
/// 第三方轨的认证服务器 API 根(其余轨为空串)
|
||||
#[serde(default)]
|
||||
pub server_url: String,
|
||||
/// 皮肤原图(第三方轨才可能有;`None` = 没有/没取到,UI 退回首字母块)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub skin: Option<SkinImage>,
|
||||
}
|
||||
|
||||
impl AccountView {
|
||||
/// 首字母块上的字:展示名第一个非空字符(大写化),空名字回落 `?`。
|
||||
///
|
||||
/// 放在 DTO 而不是页面里,是为了「没有皮肤时画什么」这件事只有一处判据,两个 UI 版一致。
|
||||
#[must_use]
|
||||
pub fn monogram(&self) -> String {
|
||||
self.name
|
||||
.chars()
|
||||
.find(|c| !c.is_whitespace())
|
||||
.map(|c| c.to_uppercase().to_string())
|
||||
.unwrap_or_else(|| "?".to_string())
|
||||
}
|
||||
|
||||
/// 首字母块的取色索引(0..6):由 `profile_id` 稳定推导,同一个人每次都是同一个色块。
|
||||
#[must_use]
|
||||
pub fn monogram_tone(&self) -> u8 {
|
||||
let mut hash: u32 = 2_166_136_261;
|
||||
for byte in self.profile_id.as_bytes() {
|
||||
hash ^= u32::from(*byte);
|
||||
hash = hash.wrapping_mul(16_777_619);
|
||||
}
|
||||
u8::try_from(hash % 6).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// 一张皮肤原图。
|
||||
///
|
||||
/// **停在「原图」这一层是刻意的**:presenter 不引入图片解码依赖(`presenter-no-ui` +
|
||||
/// 依赖极简),裁剪/缩放/取首字母块都由 UI 层自己做。离线轨永远没有它——没有皮肤就不给假皮肤。
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SkinImage {
|
||||
/// PNG 字节(Minecraft 皮肤:64×64 或旧版 64×32)
|
||||
pub png: Vec<u8>,
|
||||
/// 来源 URL(**只进取证日志,不上屏**)
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
impl SkinImage {
|
||||
/// 是否有可用字节(0 字节等同没有皮肤)。
|
||||
#[must_use]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.png.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// 微软登录阶段(UI 据此切换面板;两条流共用)。
|
||||
@@ -174,7 +241,7 @@ impl DeviceLoginView {
|
||||
expires_in.max(1)
|
||||
);
|
||||
if let Some(warning) = warning {
|
||||
message.push_str(&format!("({warning})"));
|
||||
message.push_str(&format!("({})", redact(warning)));
|
||||
}
|
||||
Self {
|
||||
phase: DeviceLoginPhase::Waiting,
|
||||
@@ -187,11 +254,11 @@ impl DeviceLoginView {
|
||||
}
|
||||
}
|
||||
|
||||
/// 失败态。
|
||||
/// 失败态(文案在入口就脱敏:错误原文里可能带着服务端回显的 token)。
|
||||
pub fn failed(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
phase: DeviceLoginPhase::Failed,
|
||||
message: message.into(),
|
||||
message: redact(&message.into()),
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
@@ -208,63 +275,119 @@ impl DeviceLoginView {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
/// 第三方轨(authlib-injector)登录请求。
|
||||
///
|
||||
/// **凭据红线**:`password` 只是「用户这一次输入的请求值」,从页面流到 host 的
|
||||
/// `AuthlibAuth::authenticate` 调用栈里,host 取走即弃——不入账户库、不进日志、
|
||||
/// 不进任何回程 DTO。所以本类型只有一个方向(UI → host),回程只有 [`AuthlibLoginView`]。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AuthlibRequest {
|
||||
/// 认证服务器地址(用户原样输入;host 侧 `normalize_api_root` 规范化)
|
||||
pub server: String,
|
||||
/// 登录名(邮箱或用户名)
|
||||
pub login: String,
|
||||
/// 密码(只在本调用栈里出现)
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kind_round_trips_through_stable_ids() {
|
||||
for kind in [
|
||||
AccountKind::Offline,
|
||||
AccountKind::Microsoft,
|
||||
AccountKind::Authlib,
|
||||
] {
|
||||
assert_eq!(AccountKind::parse(kind.as_str()), kind);
|
||||
assert!(!kind.label().is_empty());
|
||||
impl AuthlibRequest {
|
||||
/// 构造。
|
||||
pub fn new(
|
||||
server: impl Into<String>,
|
||||
login: impl Into<String>,
|
||||
password: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
server: server.into(),
|
||||
login: login.into(),
|
||||
password: password.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_login_view_never_carries_tokens() {
|
||||
let view = DeviceLoginView::waiting("ABCD-EFGH", "https://www.microsoft.com/link", 900, "");
|
||||
assert_eq!(view.phase, DeviceLoginPhase::Waiting);
|
||||
assert!(view.phase.busy());
|
||||
assert!(view.qr_link.contains("ABCD-EFGH"));
|
||||
let json = serde_json::to_string(&view).expect("序列化");
|
||||
for forbidden in ["token", "secret", "password", "refresh"] {
|
||||
assert!(
|
||||
!json.to_lowercase().contains(forbidden),
|
||||
"视图里不该出现 {forbidden}"
|
||||
);
|
||||
/// 可打印形态(日志/诊断/错误路径用):**密码恒被抹掉**。
|
||||
#[must_use]
|
||||
pub fn redacted(&self) -> String {
|
||||
format!(
|
||||
"server={} login={} password={REDACTED}",
|
||||
redact(&self.server),
|
||||
redact(&self.login)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 第三方轨登录的可见状态(阶段复用 [`DeviceLoginPhase`]:都是「申请 → 等待 → 成/败」)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AuthlibLoginView {
|
||||
/// 阶段
|
||||
pub phase: DeviceLoginPhase,
|
||||
/// 认证服务器地址(规范化后的 API 根)
|
||||
pub server: String,
|
||||
/// 服务发现里的服务器名(校验通过后才有;空 = 没校验/没名字)
|
||||
pub server_name: String,
|
||||
/// 状态/错误文案(已脱敏)
|
||||
pub message: String,
|
||||
/// 成功后入库的账户展示名
|
||||
pub account_name: String,
|
||||
}
|
||||
|
||||
impl Default for AuthlibLoginView {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthlibLoginView {
|
||||
/// 空闲态。
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
phase: DeviceLoginPhase::Idle,
|
||||
server: String::new(),
|
||||
server_name: String::new(),
|
||||
message: String::new(),
|
||||
account_name: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 进行中(校验服务器地址 / 换 token)。
|
||||
pub fn running(server: &str, message: &str) -> Self {
|
||||
Self {
|
||||
phase: DeviceLoginPhase::Requesting,
|
||||
server: server.to_string(),
|
||||
server_name: String::new(),
|
||||
message: redact(message),
|
||||
account_name: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 地址校验通过(服务发现拿到了服务器名)。
|
||||
pub fn reachable(server: &str, server_name: &str) -> Self {
|
||||
Self {
|
||||
phase: DeviceLoginPhase::Waiting,
|
||||
server: server.to_string(),
|
||||
server_name: redact(server_name),
|
||||
message: format!("服务器可用:{}", server_name.trim()),
|
||||
account_name: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_waiting_shows_a_copyable_link_instead_of_a_user_code() {
|
||||
let view = DeviceLoginView::browser_waiting(
|
||||
"https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id=x",
|
||||
300,
|
||||
Some("拉起浏览器失败"),
|
||||
);
|
||||
assert_eq!(view.phase, DeviceLoginPhase::Waiting);
|
||||
assert!(view.phase.busy());
|
||||
assert!(view.user_code.is_empty(), "授权码流没有用户码");
|
||||
assert_eq!(view.qr_link, view.verification_uri);
|
||||
assert!(view.message.contains("浏览器"));
|
||||
assert!(view.message.contains("拉起浏览器失败"), "{}", view.message);
|
||||
let json = serde_json::to_string(&view).expect("序列化");
|
||||
for forbidden in ["refresh", "mc-access"] {
|
||||
assert!(!json.contains(forbidden), "视图里不该出现 {forbidden}");
|
||||
/// 失败态(文案在入口就脱敏)。
|
||||
pub fn failed(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
phase: DeviceLoginPhase::Failed,
|
||||
message: redact(&message.into()),
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn succeeded_and_failed_clear_the_code() {
|
||||
let ok = DeviceLoginView::succeeded("Steve");
|
||||
assert_eq!(ok.phase, DeviceLoginPhase::Succeeded);
|
||||
assert!(ok.user_code.is_empty());
|
||||
let bad = DeviceLoginView::failed("网络超时");
|
||||
assert_eq!(bad.phase, DeviceLoginPhase::Failed);
|
||||
assert_eq!(bad.message, "网络超时");
|
||||
/// 成功态。
|
||||
pub fn succeeded(server_name: &str, account_name: impl Into<String>) -> Self {
|
||||
let account_name = account_name.into();
|
||||
Self {
|
||||
phase: DeviceLoginPhase::Succeeded,
|
||||
server_name: server_name.to_string(),
|
||||
message: format!("已登录:{account_name}"),
|
||||
account_name,
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! 凭据红线的**形状脱敏**:把 JWT / 不透明 token / `token=...` 这类串从任何要上屏的文案里抹掉。
|
||||
//!
|
||||
//! ## 为什么还要第二道脱敏器
|
||||
//!
|
||||
//! `core::launch::redact` 是**按已知明文值**替换的(拿着会话里的 token 原串去抹)。这里要挡的是
|
||||
//! **没登记过的**字符串:服务端在错误响应里回显一个 token、HTTP 库把 header 拼进错误文案、
|
||||
//! 某段调试串被画到面板上。两者互补,缺一不可:
|
||||
//!
|
||||
//! | 场景 | `core::launch::redact` | 本模块 |
|
||||
//! |---|---|---|
|
||||
//! | 已知会话 token 出现在日志里 | ✅ | ❌(不知道明文) |
|
||||
//! | 服务端回包里的陌生 JWT 被画到错误面板 | ❌ | ✅ |
|
||||
//!
|
||||
//! 走形状识别(三段 base64url / 超长不透明串 / 敏感键名)就够拦住「一眼能看出是凭据」的串,
|
||||
//! 而普通文案(URL、用户码 `ABCD-EFGH`、服务器名)**一个字都不动**——脱敏器本身不能变成噪音源。
|
||||
|
||||
/// 脱敏占位符(**故意刺眼**:宁可难看,也不许静默把凭据画到屏幕上)。
|
||||
pub const REDACTED: &str = "⟪redacted⟫";
|
||||
|
||||
/// 把一段要上屏的文案里的凭据形状串抹掉(空白与其余字符**原样保留**)。
|
||||
#[must_use]
|
||||
pub fn redact(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for piece in text.split_inclusive(char::is_whitespace) {
|
||||
let split = piece.find(char::is_whitespace).unwrap_or(piece.len());
|
||||
let (chunk, space) = piece.split_at(split);
|
||||
out.push_str(&redact_chunk(chunk));
|
||||
out.push_str(space);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 单个「词」的脱敏:① 敏感键名的值 ② 整个词本身就是凭据形状。
|
||||
fn redact_chunk(chunk: &str) -> String {
|
||||
if let Some((key, _value)) = chunk.split_once('=') {
|
||||
if is_sensitive_key(key) || looks_opaque(chunk) {
|
||||
return format!("{key}={REDACTED}");
|
||||
}
|
||||
}
|
||||
if looks_opaque(chunk) {
|
||||
return REDACTED.to_string();
|
||||
}
|
||||
chunk.to_string()
|
||||
}
|
||||
|
||||
/// 键名是否属于「它的值一定是凭据」(`accessToken` / `refresh_token` / `password` …)。
|
||||
fn is_sensitive_key(key: &str) -> bool {
|
||||
let key = key
|
||||
.trim_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '-')
|
||||
.to_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"passwd",
|
||||
"authorization",
|
||||
"bearer",
|
||||
"session",
|
||||
]
|
||||
.iter()
|
||||
.any(|needle| key.contains(needle))
|
||||
}
|
||||
|
||||
/// 词的形状是否像凭据:① 三段 base64url(JWT)② 长度 ≥40 的不透明串。
|
||||
fn looks_opaque(chunk: &str) -> bool {
|
||||
let trimmed = chunk.trim_matches(|c: char| {
|
||||
!c.is_ascii_alphanumeric() && c != '_' && c != '-' && c != '.' && c != '+'
|
||||
});
|
||||
looks_like_jwt(trimmed) || (trimmed.len() >= 40 && trimmed.chars().all(is_base64url))
|
||||
}
|
||||
|
||||
/// 是否是 JWT 形状:`header.payload.signature`,三段都非空且够长、全是 base64url 字符。
|
||||
///
|
||||
/// 公开是为了单测能直接钉这条判据(UI 侧「注入 JWT 必须被抹掉」的测试也用它)。
|
||||
#[must_use]
|
||||
pub fn looks_like_jwt(token: &str) -> bool {
|
||||
let parts: Vec<&str> = token.split('.').collect();
|
||||
parts.len() == 3
|
||||
&& parts
|
||||
.iter()
|
||||
.all(|part| part.len() >= 8 && part.chars().all(is_base64url))
|
||||
}
|
||||
|
||||
/// base64url 字母表(含 `=` 填充与 `+`/`/` 的宽容分支)。
|
||||
fn is_base64url(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '+' | '/' | '=' | '.')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 标准 JWT 形状(2 段 header/payload + 1 段签名)。
|
||||
const JWT: &str =
|
||||
"eyJhbGciOiJSUzI1NiIsIng1dCI6IkFCQyJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlLXZhbHVl";
|
||||
|
||||
#[test]
|
||||
fn the_jwt_shape_judgement_is_not_a_length_heuristic() {
|
||||
assert!(looks_like_jwt(JWT));
|
||||
assert!(!looks_like_jwt("not.a.jwt"), "短段不算 JWT");
|
||||
assert!(!looks_like_jwt("a.b.c.d"), "四段不算 JWT");
|
||||
assert!(!looks_like_jwt("ABCD-EFGH"), "设备码不是 JWT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_jwts_and_sensitive_pairs_are_redacted() {
|
||||
assert_eq!(redact(JWT), REDACTED);
|
||||
assert_eq!(
|
||||
redact(&format!("Bearer {JWT}")),
|
||||
format!("Bearer {REDACTED}")
|
||||
);
|
||||
assert_eq!(
|
||||
redact(&format!("accessToken={JWT}")),
|
||||
format!("accessToken={REDACTED}")
|
||||
);
|
||||
// 敏感键名 + 短值(真实 refresh token 常常很短,靠键名兜)
|
||||
assert_eq!(redact("password=hunter2"), format!("password={REDACTED}"));
|
||||
assert_eq!(
|
||||
redact("refresh_token=abc"),
|
||||
format!("refresh_token={REDACTED}")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_copy_is_left_byte_for_byte() {
|
||||
for text in [
|
||||
"在浏览器打开 https://www.microsoft.com/link 并输入 ABCD-EFGH",
|
||||
"服务器不可达:dns error",
|
||||
"HTTP 403 Forbidden — 该服务器要求白名单",
|
||||
"",
|
||||
] {
|
||||
assert_eq!(redact(text), text, "普通文案被改了:{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitespace_and_line_breaks_survive() {
|
||||
let text = format!("第一行 token={JWT}\n\n第二行 缩进");
|
||||
let out = redact(&text);
|
||||
assert!(out.contains("\n\n"), "{out}");
|
||||
assert!(out.contains(" 缩进"), "{out}");
|
||||
assert!(!out.contains(JWT), "{out}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! 账户 DTO 的契约测试(凭据红线的主要断言都在这里)。
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn kind_round_trips_through_stable_ids() {
|
||||
for kind in [
|
||||
AccountKind::Offline,
|
||||
AccountKind::Microsoft,
|
||||
AccountKind::Authlib,
|
||||
] {
|
||||
assert_eq!(AccountKind::parse(kind.as_str()), kind);
|
||||
assert!(!kind.label().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_login_view_never_carries_tokens() {
|
||||
let view = DeviceLoginView::waiting("ABCD-EFGH", "https://www.microsoft.com/link", 900, "");
|
||||
assert_eq!(view.phase, DeviceLoginPhase::Waiting);
|
||||
assert!(view.phase.busy());
|
||||
assert!(view.qr_link.contains("ABCD-EFGH"));
|
||||
let json = serde_json::to_string(&view).expect("序列化");
|
||||
for forbidden in ["token", "secret", "password", "refresh"] {
|
||||
assert!(
|
||||
!json.to_lowercase().contains(forbidden),
|
||||
"视图里不该出现 {forbidden}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_waiting_shows_a_copyable_link_instead_of_a_user_code() {
|
||||
let view = DeviceLoginView::browser_waiting(
|
||||
"https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id=x",
|
||||
300,
|
||||
Some("拉起浏览器失败"),
|
||||
);
|
||||
assert_eq!(view.phase, DeviceLoginPhase::Waiting);
|
||||
assert!(view.phase.busy());
|
||||
assert!(view.user_code.is_empty(), "授权码流没有用户码");
|
||||
assert_eq!(view.qr_link, view.verification_uri);
|
||||
assert!(view.message.contains("浏览器"));
|
||||
assert!(view.message.contains("拉起浏览器失败"), "{}", view.message);
|
||||
let json = serde_json::to_string(&view).expect("序列化");
|
||||
for forbidden in ["refresh", "mc-access"] {
|
||||
assert!(!json.contains(forbidden), "视图里不该出现 {forbidden}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn succeeded_and_failed_clear_the_code() {
|
||||
let ok = DeviceLoginView::succeeded("Steve");
|
||||
assert_eq!(ok.phase, DeviceLoginPhase::Succeeded);
|
||||
assert!(ok.user_code.is_empty());
|
||||
let bad = DeviceLoginView::failed("网络超时");
|
||||
assert_eq!(bad.phase, DeviceLoginPhase::Failed);
|
||||
assert_eq!(bad.message, "网络超时");
|
||||
}
|
||||
|
||||
/// 凭据红线(审核项):JWT 形状串从**任何**入口进来都必须被抹掉。
|
||||
///
|
||||
/// 抓得住:`redact` 被摘掉、判据被放宽成「长度 ≥40 就行」、或者某个构造器绕过它。
|
||||
/// 抓不住:真实凭据的明文值(那是 `core::launch::redact` 的活儿,按已知值替换)。
|
||||
#[test]
|
||||
fn jwt_shaped_text_is_redacted_at_every_entry_point() {
|
||||
let jwt =
|
||||
"eyJhbGciOiJSUzI1NiIsIng1dCI6IkFCQyJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlLXZhbHVl";
|
||||
|
||||
let device = DeviceLoginView::failed(format!("登录失败:accessToken={jwt}"));
|
||||
assert!(!device.message.contains(jwt), "{}", device.message);
|
||||
assert!(device.message.contains(REDACTED), "{}", device.message);
|
||||
|
||||
let authlib = AuthlibLoginView::failed(format!("服务器回包异常 {jwt}"));
|
||||
assert!(!authlib.message.contains(jwt), "{}", authlib.message);
|
||||
assert!(authlib.message.contains(REDACTED), "{}", authlib.message);
|
||||
|
||||
let ready = AuthlibLoginView::reachable("https://littleskin.cn/", "LittleSkin");
|
||||
assert!(!ready.message.contains(jwt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authlib_request_never_prints_the_password() {
|
||||
let request = AuthlibRequest::new(
|
||||
"https://littleskin.cn/api/yggdrasil/",
|
||||
"me@example.com",
|
||||
"hunter2",
|
||||
);
|
||||
let shown = request.redacted();
|
||||
assert!(!shown.contains("hunter2"), "{shown}");
|
||||
assert!(shown.contains("littleskin"), "{shown}");
|
||||
assert!(shown.contains(REDACTED), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authlib_view_carries_the_server_name_and_no_tokens() {
|
||||
let view = AuthlibLoginView::reachable("https://littleskin.cn/api/yggdrasil/", "LittleSkin");
|
||||
assert_eq!(view.phase, DeviceLoginPhase::Waiting);
|
||||
assert_eq!(view.server_name, "LittleSkin");
|
||||
assert!(view.message.contains("LittleSkin"));
|
||||
|
||||
let ok = AuthlibLoginView::succeeded("LittleSkin", "Steve");
|
||||
assert_eq!(ok.phase, DeviceLoginPhase::Succeeded);
|
||||
assert_eq!(ok.account_name, "Steve");
|
||||
let json = serde_json::to_string(&ok).expect("序列化");
|
||||
for forbidden in ["accessToken", "clientToken", "refresh", "password"] {
|
||||
assert!(!json.contains(forbidden), "视图里不该出现 {forbidden}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_view_serializes_without_credentials() {
|
||||
let view = AccountView {
|
||||
id: "account:a".to_string(),
|
||||
name: "Steve".to_string(),
|
||||
kind: AccountKind::Authlib,
|
||||
profile_id: "0f8f".to_string(),
|
||||
login_name: "me@example.com".to_string(),
|
||||
created: "2026-10-31 20:12".to_string(),
|
||||
active: true,
|
||||
server_url: "https://littleskin.cn/api/yggdrasil/".to_string(),
|
||||
skin: Some(SkinImage {
|
||||
png: vec![1, 2, 3],
|
||||
source: "textures".to_string(),
|
||||
}),
|
||||
};
|
||||
let json = serde_json::to_string(&view).expect("序列化");
|
||||
for forbidden in ["token", "secret", "password", "refresh"] {
|
||||
assert!(
|
||||
!json.to_lowercase().contains(forbidden),
|
||||
"账户视图里不该出现 {forbidden}"
|
||||
);
|
||||
}
|
||||
assert!(json.contains("\"png\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monogram_is_stable_and_never_empty() {
|
||||
let mut view = AccountView {
|
||||
id: "account:a".to_string(),
|
||||
name: " steve".to_string(),
|
||||
kind: AccountKind::Microsoft,
|
||||
profile_id: "0f8f".to_string(),
|
||||
login_name: String::new(),
|
||||
created: String::new(),
|
||||
active: false,
|
||||
server_url: String::new(),
|
||||
skin: None,
|
||||
};
|
||||
assert_eq!(view.monogram(), "S");
|
||||
let tone = view.monogram_tone();
|
||||
assert!(tone < 6);
|
||||
view.profile_id = "0f8f".to_string();
|
||||
assert_eq!(view.monogram_tone(), tone, "同一个人每次同一个色块");
|
||||
view.name = String::new();
|
||||
assert_eq!(view.monogram(), "?", "空名字也要有字,不能画白块");
|
||||
}
|
||||
@@ -9,10 +9,12 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::dialogs::{DialogId, DialogRequest};
|
||||
use crate::dto::CreateRequest;
|
||||
use crate::dto::{
|
||||
AccountView, AgentEvent, ContentInstallRequest, ContentQuery, ContentResults, DeviceLoginView,
|
||||
DiagnosisReport, InstallProgressView, InstanceId, InstanceRuntime, InstanceSummary,
|
||||
JavaPageView, LoaderKind, LogLine, LogOutcome, LogSession, NoticeView, PackCommand, PackEvent,
|
||||
SessionId, SettingGroupView, VersionCategory, VersionSummary,
|
||||
// 主线(M109 的 Content* / M113 的 Pack*)与 M114 的 Authlib* 的并集。
|
||||
AccountView, AgentEvent, AuthlibLoginView, AuthlibRequest, ContentInstallRequest, ContentQuery,
|
||||
ContentResults, DeviceLoginView, DiagnosisReport, InstallProgressView, InstanceId,
|
||||
InstanceRuntime, InstanceSummary, JavaPageView, LoaderKind, LogLine, LogOutcome, LogSession,
|
||||
NoticeView, PackCommand, PackEvent, SessionId, SettingGroupView, VersionCategory,
|
||||
VersionSummary,
|
||||
};
|
||||
use crate::toast::Toast;
|
||||
|
||||
@@ -68,6 +70,8 @@ pub enum CoreEvent {
|
||||
AccountsChanged(Vec<AccountView>),
|
||||
/// 微软登录状态刷新
|
||||
DeviceLoginChanged(DeviceLoginView),
|
||||
/// 第三方轨(authlib-injector)登录/校验状态刷新
|
||||
AuthlibLoginChanged(AuthlibLoginView),
|
||||
/// Java 页快照(发行版/回退链/运行时)
|
||||
JavaChanged(JavaPageView),
|
||||
/// 安装进度(`None` = 清掉进度面板)
|
||||
@@ -168,6 +172,12 @@ pub enum AppCommand {
|
||||
StartBrowserLogin,
|
||||
/// 取消/关掉微软登录面板(已发出的请求会在收尾时丢弃结果)
|
||||
CancelDeviceLogin,
|
||||
/// 加一个第三方皮肤站(authlib-injector)账户:校验服务器 + 密码登录
|
||||
///
|
||||
/// **凭据红线**:`request.password` 只是这一次的请求值,host 用完即弃,绝不进回程 DTO。
|
||||
AddAuthlibAccount(AuthlibRequest),
|
||||
/// 只校验第三方皮肤站地址(服务发现):结果走 `AuthlibLoginChanged`
|
||||
ProbeAuthlibServer(String),
|
||||
/// 安装指定发行版的托管 JDK(`temurin` / `oracle` / `microsoft` / `zulu`)
|
||||
InstallJava(String),
|
||||
/// 写一条设置(`key` 必须是 core schema 里的键)
|
||||
@@ -246,6 +256,8 @@ mod tests {
|
||||
login_name: String::new(),
|
||||
created: "2026-10-31 20:12".to_string(),
|
||||
active: true,
|
||||
server_url: String::new(),
|
||||
skin: None,
|
||||
}]));
|
||||
let text = serde_json::to_string(&account).expect("序列化");
|
||||
let back: AppEvent = serde_json::from_str(&text).expect("反序列化");
|
||||
@@ -273,5 +285,29 @@ mod tests {
|
||||
login
|
||||
);
|
||||
assert!(DeviceLoginPhase::Waiting.busy());
|
||||
|
||||
// 第三方轨(M114):请求进、状态出,两边都不带 token 字段
|
||||
let authlib = AppCommand::AddAuthlibAccount(AuthlibRequest::new(
|
||||
"https://littleskin.cn/api/yggdrasil/",
|
||||
"me@example.com",
|
||||
"hunter2",
|
||||
));
|
||||
let text = serde_json::to_string(&authlib).expect("序列化");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AppCommand>(&text).expect("反序列化"),
|
||||
authlib
|
||||
);
|
||||
|
||||
let view = AppEvent::Core(CoreEvent::AuthlibLoginChanged(AuthlibLoginView::reachable(
|
||||
"https://littleskin.cn/api/yggdrasil/",
|
||||
"LittleSkin",
|
||||
)));
|
||||
let text = serde_json::to_string(&view).expect("序列化");
|
||||
let back: AppEvent = serde_json::from_str(&text).expect("反序列化");
|
||||
assert_eq!(back, view);
|
||||
assert!(
|
||||
!text.to_lowercase().contains("token"),
|
||||
"回程视图里不该有 token"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,10 @@ mod pack;
|
||||
mod settings;
|
||||
mod versions;
|
||||
|
||||
pub use accounts::{AccountKind, AccountView, DeviceLoginPhase, DeviceLoginView};
|
||||
pub use accounts::{
|
||||
looks_like_jwt, redact, AccountKind, AccountView, AuthlibLoginView, AuthlibRequest,
|
||||
DeviceLoginPhase, DeviceLoginView, SkinImage, REDACTED,
|
||||
};
|
||||
pub use agent::{AgentEvent, ChatMessage, ChatRole, ConfirmRequest, Sensitivity, ToolCallView};
|
||||
pub use content::{
|
||||
loader_facet, ContentHit, ContentInstallRequest, ContentKind, ContentQuery, ContentResults,
|
||||
|
||||
@@ -25,6 +25,11 @@ use super::env::HostEnv;
|
||||
use super::job::{spawn, HostTask, JobSender};
|
||||
use super::opener;
|
||||
|
||||
/// 第三方轨(服务发现 / 密码登录 / 皮肤抓取)。
|
||||
pub mod authlib;
|
||||
|
||||
pub use authlib::{fetch_skin, spawn_probe, start_login as start_authlib_login};
|
||||
|
||||
/// 账户列表(公开字段)。
|
||||
pub fn accounts(env: &HostEnv, active: Option<&str>) -> Vec<AccountView> {
|
||||
let store = AccountStore::open(env.layout.auth_data());
|
||||
@@ -39,6 +44,9 @@ pub fn accounts(env: &HostEnv, active: Option<&str>) -> Vec<AccountView> {
|
||||
login_name: meta.login_name.clone().unwrap_or_default(),
|
||||
created: display_ms(meta.created_at_ms),
|
||||
active: active.is_some_and(|id| id == meta.id.as_str()),
|
||||
server_url: meta.server_url.clone().unwrap_or_default(),
|
||||
// 皮肤是网络产物:列表先给 `None`,host 抓到之后按账户 id 盖回去(见 `CoreHost`)
|
||||
skin: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
//! 第三方轨(authlib-injector):服务发现校验、密码登录、皮肤原图抓取。
|
||||
//!
|
||||
//! 全部跑在后台线程里(网络),出口只有 [`AuthlibLoginView`] / [`SkinImage`]——
|
||||
//! 密码与 accessToken 在调用栈里就地丢弃,永不进 DTO 回程(M114 凭据红线)。
|
||||
//!
|
||||
//! ## 三条流的坐标
|
||||
//!
|
||||
//! | 动作 | 端点 | 产出 |
|
||||
//! |---|---|---|
|
||||
//! | 服务发现(「校验」按钮) | `GET {apiRoot}` | 服务器名 / skinDomains(`meta` 缺失即判「不是认证服务器」) |
|
||||
//! | 登录 | `POST {apiRoot}authserver/authenticate` | `AuthlibSession`(入库,不外传) |
|
||||
//! | 皮肤 | `GET {apiRoot}sessionserver/session/minecraft/profile/{uuid}` → textures → 皮肤 URL | 皮肤 PNG 原图 |
|
||||
//!
|
||||
//! `core::download::http::build_client` 是唯一的 HTTP 基座(复用下载器的客户端配置),
|
||||
//! 所以本 crate **不新增任何依赖**(`presenter-no-ui` 与依赖最小化同时成立)。
|
||||
|
||||
use unlucky_core::auth::account::{AccountKind as CoreAccountKind, AccountMeta, Credentials};
|
||||
use unlucky_core::auth::authlib::{
|
||||
normalize_api_root, AuthlibAuth, AuthlibServerMeta, AuthlibSession,
|
||||
};
|
||||
use unlucky_core::auth::microsoft::now_ms;
|
||||
use unlucky_core::auth::{AccountStore, Secret};
|
||||
use unlucky_core::download::blocking::block_on;
|
||||
|
||||
use crate::dto::{AuthlibLoginView, AuthlibRequest, SkinImage, REDACTED};
|
||||
|
||||
use super::super::engine;
|
||||
use super::super::env::HostEnv;
|
||||
use super::super::job::{spawn, HostTask, JobSender};
|
||||
use super::LoginJob;
|
||||
|
||||
/// 一次 GET 的超时上限(秒):服务器不可达时要能失败,而不是挂住 UI 的登录面板。
|
||||
const HTTP_TIMEOUT_SECS: u64 = 15;
|
||||
|
||||
/// 校验认证服务器地址(「校验」按钮的后端)。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 地址不合法、网络不可达、HTTP 非 2xx、响应不是 authlib-injector 的服务发现 JSON 时,
|
||||
/// 返回**具名**的用户可读文案(这是任务要求的「失败态 + 具名错误」)。
|
||||
pub fn probe_authlib(env: &HostEnv, input: &str) -> Result<(String, AuthlibServerMeta), String> {
|
||||
let api_root = normalize_api_root(input).map_err(|error| error.to_string())?;
|
||||
let (status, text) = get_text(env, &api_root)?;
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(format!(
|
||||
"服务器返回 HTTP {status}({api_root} 不像可用的 authlib 认证服务器)"
|
||||
));
|
||||
}
|
||||
let value: serde_json::Value = serde_json::from_str(&text).map_err(|_| {
|
||||
format!("响应不是 JSON:{api_root} —— 可能填成了网页地址,而不是 API 根(通常以 /api/yggdrasil/ 结尾)")
|
||||
})?;
|
||||
if value.get("meta").is_none() && value.get("skinDomains").is_none() {
|
||||
return Err(
|
||||
"响应里没有 meta / skinDomains:这看起来不是 authlib-injector 服务器".to_string(),
|
||||
);
|
||||
}
|
||||
let meta = AuthlibServerMeta::from_value(&value);
|
||||
Ok((api_root, meta))
|
||||
}
|
||||
|
||||
/// 起一次第三方轨登录(后台线程)。
|
||||
pub fn start_login(env: HostEnv, tx: JobSender, job: LoginJob, request: AuthlibRequest) {
|
||||
spawn("authlib-login", move || {
|
||||
let mut request = request;
|
||||
// 日志只打脱敏形态;密码在下面用完立刻丢弃。
|
||||
eprintln!("[auth] authlib 登录开始({})", request.redacted());
|
||||
stage(&tx, &request.server, "正在校验服务器地址…");
|
||||
|
||||
let (api_root, meta) = match probe_authlib(&env, &request.server) {
|
||||
Ok(found) => found,
|
||||
Err(reason) => return fail(&tx, reason),
|
||||
};
|
||||
let server_name = meta
|
||||
.name
|
||||
.clone()
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.unwrap_or_else(|| api_root.clone());
|
||||
stage(
|
||||
&tx,
|
||||
&api_root,
|
||||
&format!("服务器 {server_name} 可用,正在登录…"),
|
||||
);
|
||||
|
||||
let auth = match AuthlibAuth::new() {
|
||||
Ok(auth) => auth,
|
||||
Err(error) => return fail(&tx, error.to_string()),
|
||||
};
|
||||
let client_token = Secret::new(client_token());
|
||||
let password_text = std::mem::take(&mut request.password);
|
||||
let password = Secret::new(password_text.clone());
|
||||
let login_name = request.login.clone();
|
||||
let result = block_on(auth.authenticate(&api_root, &login_name, &password, &client_token));
|
||||
drop(password);
|
||||
|
||||
if job.is_cancelled() {
|
||||
let _ = tx.send(HostTask::Authlib(Box::default()));
|
||||
return;
|
||||
}
|
||||
match result {
|
||||
Ok(session) => match store(&env, session, &api_root, &login_name) {
|
||||
Ok(account) => {
|
||||
let _ = tx.send(HostTask::Authlib(Box::new(AuthlibLoginView::succeeded(
|
||||
&server_name,
|
||||
&account,
|
||||
))));
|
||||
let _ = tx.send(HostTask::Accounts(super::accounts(
|
||||
&env,
|
||||
Some(account.as_str()),
|
||||
)));
|
||||
}
|
||||
Err(reason) => fail(&tx, reason),
|
||||
},
|
||||
// 错误原文里可能有服务端回显的凭据:先按**形状**脱敏(`AuthlibLoginView::failed`),
|
||||
// 再按**已知值**兜一遍(万一服务端把密码原样回显)。
|
||||
Err(error) => fail(&tx, scrub_known(&error.to_string(), &password_text)),
|
||||
}
|
||||
drop(password_text);
|
||||
});
|
||||
}
|
||||
|
||||
/// 只校验服务器地址(「校验服务器」按钮);结果走同一条 `AuthlibLoginChanged`。
|
||||
pub fn spawn_probe(env: HostEnv, tx: JobSender, server: String) {
|
||||
spawn("authlib-probe", move || {
|
||||
stage(&tx, &server, "正在校验服务器地址…");
|
||||
match probe_authlib(&env, &server) {
|
||||
Ok((api_root, meta)) => {
|
||||
let name = meta
|
||||
.name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map_or_else(|| api_root.clone(), str::to_string);
|
||||
let _ = tx.send(HostTask::Authlib(Box::new(AuthlibLoginView::reachable(
|
||||
&api_root, &name,
|
||||
))));
|
||||
}
|
||||
Err(reason) => fail(&tx, reason),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 抓第三方轨账户的皮肤原图(`profile_id` → textures → 皮肤 URL → PNG 字节)。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 服务器不可达、响应缺 textures、纹理不是 PNG 时返回原因(调用方按「没有皮肤」处理)。
|
||||
pub fn fetch_skin(env: &HostEnv, api_root: &str, profile_id: &str) -> Result<SkinImage, String> {
|
||||
let base = normalize_api_root(api_root).map_err(|error| error.to_string())?;
|
||||
let url = format!("{base}sessionserver/session/minecraft/profile/{profile_id}");
|
||||
let (status, text) = get_text(env, &url)?;
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(format!("皮肤接口返回 HTTP {status}"));
|
||||
}
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(&text).map_err(|error| format!("皮肤接口响应不是 JSON:{error}"))?;
|
||||
let encoded = value
|
||||
.get("properties")
|
||||
.and_then(|properties| properties.as_array())
|
||||
.and_then(|properties| {
|
||||
properties
|
||||
.iter()
|
||||
.find(|entry| entry.get("name").and_then(|name| name.as_str()) == Some("textures"))
|
||||
})
|
||||
.and_then(|entry| entry.get("value"))
|
||||
.and_then(|value| value.as_str())
|
||||
.ok_or_else(|| "档案里没有 textures 属性".to_string())?;
|
||||
let raw = base64_decode(encoded)?;
|
||||
let textures: serde_json::Value =
|
||||
serde_json::from_slice(&raw).map_err(|error| format!("textures 属性解不开:{error}"))?;
|
||||
let skin_url = textures
|
||||
.get("textures")
|
||||
.and_then(|textures| textures.get("SKIN"))
|
||||
.and_then(|skin| skin.get("url"))
|
||||
.and_then(|url| url.as_str())
|
||||
.ok_or_else(|| "textures 里没有 SKIN 条目".to_string())?;
|
||||
let (status, bytes) = get_bytes(env, skin_url)?;
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(format!("皮肤图片返回 HTTP {status}"));
|
||||
}
|
||||
if !bytes.starts_with(b"\x89PNG") {
|
||||
return Err("皮肤图片不是 PNG".to_string());
|
||||
}
|
||||
Ok(SkinImage {
|
||||
png: bytes,
|
||||
source: skin_url.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 入库(元数据 + 凭据分文件);返回展示名。
|
||||
fn store(
|
||||
env: &HostEnv,
|
||||
session: AuthlibSession,
|
||||
api_root: &str,
|
||||
login_name: &str,
|
||||
) -> Result<String, String> {
|
||||
let profile = session
|
||||
.selected_profile
|
||||
.clone()
|
||||
.filter(|profile| !profile.name.trim().is_empty() && !profile.id.is_empty())
|
||||
.ok_or_else(|| {
|
||||
"服务器没有返回角色:这个账号可能还没在皮肤站里创建角色(建好后再试)".to_string()
|
||||
})?;
|
||||
let mut meta = AccountMeta::new(
|
||||
CoreAccountKind::AuthlibInjector,
|
||||
profile.id,
|
||||
profile.name,
|
||||
now_ms(),
|
||||
);
|
||||
meta.login_name = Some(login_name.to_string());
|
||||
meta.server_url = Some(api_root.to_string());
|
||||
let name = meta.display_name().to_string();
|
||||
let mut account_store = AccountStore::open(env.layout.auth_data());
|
||||
account_store
|
||||
.insert(meta, Credentials::AuthlibInjector(session))
|
||||
.and_then(|()| account_store.save())
|
||||
.map_err(|error| format!("账户入库失败:{error}"))?;
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// 发一条「进行中」状态(UI 据此只转圈不误报)。
|
||||
fn stage(tx: &JobSender, server: &str, message: &str) {
|
||||
let _ = tx.send(HostTask::Authlib(Box::new(AuthlibLoginView::running(
|
||||
server, message,
|
||||
))));
|
||||
}
|
||||
|
||||
/// 失败收尾:**先脱敏再上屏**(服务端错误原文里可能带 token)。
|
||||
fn fail(tx: &JobSender, message: String) {
|
||||
let _ = tx.send(HostTask::Authlib(Box::new(AuthlibLoginView::failed(
|
||||
message,
|
||||
))));
|
||||
}
|
||||
|
||||
/// 启动器侧生成的 `clientToken`(Yggdrasil 要求刷新/校验都带,且服务端回传必须一致)。
|
||||
fn client_token() -> String {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
let mut out = String::with_capacity(32);
|
||||
for salt in 0..2u64 {
|
||||
// `RandomState` 每个实例自带随机种子(标准库给的是进程级随机),不引第三方随机库。
|
||||
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
|
||||
hasher.write_u64(now_ms() ^ salt);
|
||||
hasher.write_u32(std::process::id());
|
||||
out.push_str(&format!("{:016x}", hasher.finish()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// GET 文本(状态码 + 正文)。
|
||||
///
|
||||
/// 客户端来自**既有的下载引擎**(`host::engine::engine`):代理/超时/证书栈与本仓的下载器
|
||||
/// 完全同源,不在这里另起一套 HTTP 配置(本 crate 也没有 reqwest 依赖,拿到的只是它的 `&Client`)。
|
||||
fn get_text(env: &HostEnv, url: &str) -> Result<(u16, String), String> {
|
||||
let engine = engine::engine(env);
|
||||
let client = engine.client();
|
||||
let url = url.to_string();
|
||||
block_on(async move {
|
||||
let reply = client
|
||||
.get(&url)
|
||||
.timeout(std::time::Duration::from_secs(HTTP_TIMEOUT_SECS))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("服务器不可达:{error}"))?;
|
||||
let status = reply.status().as_u16();
|
||||
let text = reply
|
||||
.text()
|
||||
.await
|
||||
.map_err(|error| format!("读取响应失败:{error}"))?;
|
||||
Ok((status, text))
|
||||
})
|
||||
}
|
||||
|
||||
/// GET 字节(皮肤图片)。
|
||||
fn get_bytes(env: &HostEnv, url: &str) -> Result<(u16, Vec<u8>), String> {
|
||||
let engine = engine::engine(env);
|
||||
let client = engine.client();
|
||||
let url = url.to_string();
|
||||
block_on(async move {
|
||||
let reply = client
|
||||
.get(&url)
|
||||
.timeout(std::time::Duration::from_secs(HTTP_TIMEOUT_SECS))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("皮肤图片不可达:{error}"))?;
|
||||
let status = reply.status().as_u16();
|
||||
let bytes = reply
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|error| format!("读取皮肤图片失败:{error}"))?
|
||||
.to_vec();
|
||||
Ok((status, bytes))
|
||||
})
|
||||
}
|
||||
|
||||
/// base64 解码(标准字母表,容忍 URL-safe 变体与缺失填充)。
|
||||
///
|
||||
/// 为什么自己写:textures 属性是 base64 编码的 JSON,而本 crate 不能引第三方解码库
|
||||
/// (依赖最小化);这段是 40 行的确定性算法,配单测比拖一个依赖更划算。
|
||||
fn base64_decode(input: &str) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::with_capacity(input.len() / 4 * 3);
|
||||
let mut buffer: u32 = 0;
|
||||
let mut bits = 0u32;
|
||||
for byte in input.bytes() {
|
||||
let value = 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'+' | b'-' => 62,
|
||||
b'/' | b'_' => 63,
|
||||
b'=' | b'\n' | b'\r' | b' ' => continue,
|
||||
other => return Err(format!("base64 里有非法字符:{:?}", other as char)),
|
||||
};
|
||||
buffer = (buffer << 6) | u32::from(value);
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(u8::try_from((buffer >> bits) & 0xFF).unwrap_or(0));
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("base64 内容为空".to_string());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 错误文案里可能混进已知凭据值:按值再兜一遍(形状脱敏由 `AuthlibLoginView::failed` 做)。
|
||||
#[must_use]
|
||||
pub fn scrub_known(message: &str, secret: &str) -> String {
|
||||
if secret.is_empty() {
|
||||
return message.to_string();
|
||||
}
|
||||
message.replace(secret, REDACTED)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base64_decodes_textures_payload() {
|
||||
// `{"textures":{}}` 的 base64
|
||||
let encoded = "eyJ0ZXh0dXJlcyI6e319";
|
||||
assert_eq!(base64_decode(encoded).expect("解码"), br#"{"textures":{}}"#);
|
||||
// URL-safe 变体 + 填充 + 换行都要吃
|
||||
assert_eq!(
|
||||
base64_decode("eyJ0ZXh0dXJlcyI6e319\n").expect("解码"),
|
||||
br#"{"textures":{}}"#
|
||||
);
|
||||
assert!(base64_decode("!!!").is_err());
|
||||
assert!(base64_decode("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_token_is_stable_length_and_unique() {
|
||||
let a = client_token();
|
||||
let b = client_token();
|
||||
assert_eq!(a.len(), 32);
|
||||
assert_ne!(
|
||||
a, b,
|
||||
"两次生成的 clientToken 不能相同(会被服务端当成重放)"
|
||||
);
|
||||
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_secret_is_scrubbed_from_error_text() {
|
||||
let text = scrub_known("登录失败:hunter2 被拒绝", "hunter2");
|
||||
assert!(!text.contains("hunter2"), "{text}");
|
||||
assert!(text.contains(REDACTED));
|
||||
assert_eq!(scrub_known("普通错误", ""), "普通错误");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_page_address_is_rejected_with_a_named_error() {
|
||||
// 不发网络请求:只测「规范化 + 空输入」这条不联网的分支
|
||||
let dir = std::env::temp_dir().join(format!("ull-authlib-probe-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let env = HostEnv::at_root(&dir);
|
||||
std::fs::create_dir_all(env.layout.cache()).expect("cache");
|
||||
let error = probe_authlib(&env, " ").expect_err("空地址必须报错");
|
||||
assert!(error.contains("不能为空"), "{error}");
|
||||
let error = probe_authlib(&env, "https://").expect_err("只给协议头也必须报错");
|
||||
assert!(!error.is_empty());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -154,9 +154,31 @@ impl CoreHost {
|
||||
job.cancel();
|
||||
}
|
||||
self.login = None;
|
||||
// 第三方轨的面板也归这条「关掉登录面板」:两条轨都不该留一个转不完的圈
|
||||
if let Some(job) = &self.authlib {
|
||||
job.cancel();
|
||||
}
|
||||
self.authlib = None;
|
||||
self.send(CoreEvent::DeviceLoginChanged(
|
||||
crate::dto::DeviceLoginView::new(),
|
||||
));
|
||||
self.send(CoreEvent::AuthlibLoginChanged(
|
||||
crate::dto::AuthlibLoginView::new(),
|
||||
));
|
||||
}
|
||||
AppCommand::AddAuthlibAccount(request) => {
|
||||
self.authlib = Some(LoginJob::new());
|
||||
let job = self.authlib.clone().unwrap_or_default();
|
||||
self.send(CoreEvent::AuthlibLoginChanged(
|
||||
crate::dto::AuthlibLoginView::running(&request.server, "正在校验服务器地址…"),
|
||||
));
|
||||
accounts::start_authlib_login(self.env.clone(), self.tx.clone(), job, request);
|
||||
}
|
||||
AppCommand::ProbeAuthlibServer(server) => {
|
||||
// 只探活:后台线程跑服务发现,结果回到同一条 `AuthlibLoginChanged`
|
||||
let env = self.env.clone();
|
||||
let tx = self.tx.clone();
|
||||
accounts::spawn_probe(env, tx, server);
|
||||
}
|
||||
AppCommand::InstallJava(vendor) => {
|
||||
self.java_busy = true;
|
||||
|
||||
@@ -91,6 +91,13 @@ impl CoreHost {
|
||||
self.refresh_instances();
|
||||
}
|
||||
HostTask::Login(view) => self.send(CoreEvent::DeviceLoginChanged(*view)),
|
||||
HostTask::Authlib(view) => self.send(CoreEvent::AuthlibLoginChanged(*view)),
|
||||
HostTask::Avatar { id, skin } => {
|
||||
// 抓到/没抓到都记下来(`None` = 试过了,不再重试),再把列表盖好发出去
|
||||
self.skins.insert(id, skin);
|
||||
self.attach_skins();
|
||||
self.send(CoreEvent::AccountsChanged(self.accounts.clone()));
|
||||
}
|
||||
HostTask::Java(page) => self.send(CoreEvent::JavaChanged(*page)),
|
||||
HostTask::Logs {
|
||||
sessions,
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
|
||||
use crate::dto::{
|
||||
AccountView, ContentResults, DeviceLoginView, DiagnosisReport, InstallProgressView, InstanceId,
|
||||
InstanceRuntime, JavaPageView, LaunchFinished, LiveLogBatch, LoaderKind, LogLine, LogOutcome,
|
||||
LogSession, NoticeView, PackEvent, SessionId, VersionSummary,
|
||||
// 主线(M109 ContentResults / M105 LoaderKind / M113 PackEvent)与 M114 的账户轨并集。
|
||||
AccountView, AuthlibLoginView, ContentResults, DeviceLoginView, DiagnosisReport,
|
||||
InstallProgressView, InstanceId, InstanceRuntime, JavaPageView, LaunchFinished, LiveLogBatch,
|
||||
LoaderKind, LogLine, LogOutcome, LogSession, NoticeView, PackEvent, SessionId, SkinImage,
|
||||
VersionSummary,
|
||||
};
|
||||
use crate::toast::Toast;
|
||||
|
||||
@@ -66,6 +68,15 @@ pub enum HostTask {
|
||||
Accounts(Vec<AccountView>),
|
||||
/// 设备码登录状态
|
||||
Login(Box<DeviceLoginView>),
|
||||
/// 第三方轨(authlib-injector)登录/校验状态
|
||||
Authlib(Box<AuthlibLoginView>),
|
||||
/// 账户皮肤抓取结果(`skin = None` = 没取到;UI 退回首字母块)
|
||||
Avatar {
|
||||
/// 账户 id
|
||||
id: String,
|
||||
/// 皮肤原图
|
||||
skin: Option<SkinImage>,
|
||||
},
|
||||
/// Java 页(发行版/回退链/运行时)
|
||||
Java(Box<JavaPageView>),
|
||||
/// 日志页快照(会话列表 + 选中会话的行 + 诊断)
|
||||
|
||||
@@ -37,8 +37,8 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::dto::{
|
||||
AccountView, AppCommand, AppEvent, Backend, CoreEvent, DiagnosisReport, InstallProgressView,
|
||||
InstanceRuntime, JavaChainStep, NoticeView,
|
||||
AccountKind, AccountView, AppCommand, AppEvent, Backend, CoreEvent, DiagnosisReport,
|
||||
InstallProgressView, InstanceRuntime, JavaChainStep, NoticeView, SkinImage,
|
||||
};
|
||||
use crate::mock::MockBackend;
|
||||
use crate::toast::{Toast, ToastKind};
|
||||
@@ -72,6 +72,13 @@ pub struct CoreHost {
|
||||
active_account: Option<String>,
|
||||
accounts: Vec<AccountView>,
|
||||
login: Option<LoginJob>,
|
||||
/// 第三方轨(authlib)登录任务句柄(与微软两条流共用取消语义,但**不复用槽位**:
|
||||
/// 两条轨同时点「登录」时各自的结果不能互相踩)
|
||||
authlib: Option<LoginJob>,
|
||||
/// 已抓到的皮肤(账户 id → 原图;`None` = 试过但没取到,不再重试)
|
||||
skins: BTreeMap<String, Option<SkinImage>>,
|
||||
/// 已经发起过皮肤抓取的账户 id(防每次刷新都重新抓一遍)
|
||||
skin_requested: BTreeSet<String>,
|
||||
java_chain: Vec<JavaChainStep>,
|
||||
java_busy: bool,
|
||||
java_message: String,
|
||||
@@ -126,6 +133,9 @@ impl CoreHost {
|
||||
active_account: None,
|
||||
accounts: Vec::new(),
|
||||
login: None,
|
||||
authlib: None,
|
||||
skins: BTreeMap::new(),
|
||||
skin_requested: BTreeSet::new(),
|
||||
java_chain: Vec::new(),
|
||||
java_busy: false,
|
||||
java_message: String::new(),
|
||||
@@ -219,9 +229,54 @@ impl CoreHost {
|
||||
self.active_account = self.accounts.first().map(|account| account.id.clone());
|
||||
self.accounts = accounts::accounts(&self.env, self.active_account.as_deref());
|
||||
}
|
||||
self.attach_skins();
|
||||
self.request_skins();
|
||||
self.send(CoreEvent::AccountsChanged(self.accounts.clone()));
|
||||
}
|
||||
|
||||
/// 把已抓到的皮肤盖到账户视图上。
|
||||
///
|
||||
/// 只盖第三方轨:离线档案没有皮肤,微软轨不做真头像(M114 口径)——
|
||||
/// 「没有皮肤就画首字母块」,绝不给假皮肤/白块。
|
||||
fn attach_skins(&mut self) {
|
||||
for account in &mut self.accounts {
|
||||
if account.kind != AccountKind::Authlib {
|
||||
account.skin = None;
|
||||
continue;
|
||||
}
|
||||
if let Some(skin) = self.skins.get(&account.id) {
|
||||
account.skin = skin.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 给还没抓过皮肤的第三方轨账户起后台抓取(每个账户只抓一次)。
|
||||
///
|
||||
/// 抓不到就记 `None`:错误在面板上不显示(皮肤是装饰,不是业务失败),但也不会重试刷屏。
|
||||
fn request_skins(&mut self) {
|
||||
let mut pending = Vec::new();
|
||||
for account in &self.accounts {
|
||||
if account.kind != AccountKind::Authlib || account.server_url.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if self.skin_requested.insert(account.id.clone()) {
|
||||
pending.push((
|
||||
account.id.clone(),
|
||||
account.server_url.clone(),
|
||||
account.profile_id.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
for (id, server, profile) in pending {
|
||||
let tx = self.tx.clone();
|
||||
let env = self.env.clone();
|
||||
job::spawn("account-skin", move || {
|
||||
let skin = accounts::fetch_skin(&env, &server, &profile).ok();
|
||||
let _ = tx.send(HostTask::Avatar { id, skin });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_java(&mut self) {
|
||||
let page = java::page(
|
||||
&self.env,
|
||||
|
||||
@@ -16,6 +16,9 @@ use crate::dto::{
|
||||
use crate::mock_data::{mock_instances, mock_log_lines, mock_log_sessions, mock_versions};
|
||||
use crate::toast::{Toast, ToastKind};
|
||||
|
||||
#[path = "mock/accounts.rs"]
|
||||
mod accounts_screen;
|
||||
|
||||
/// 启动脚本:按时间推进 download → verify → launch → running。
|
||||
#[derive(Debug)]
|
||||
struct LaunchScript {
|
||||
@@ -65,6 +68,18 @@ impl MockBackend {
|
||||
)));
|
||||
self.events
|
||||
.push_back(AppEvent::Core(CoreEvent::LogLinesChanged(mock_log_lines())));
|
||||
self.seed_accounts();
|
||||
}
|
||||
|
||||
/// 账户页的截图矩阵(`ULL_ACCOUNT_STATE`,见 [`accounts_screen`])。
|
||||
fn seed_accounts(&mut self) {
|
||||
let scenario = accounts_screen::scenario();
|
||||
self.emit(AppEvent::Core(CoreEvent::AccountsChanged(
|
||||
accounts_screen::accounts(&scenario),
|
||||
)));
|
||||
if let Some(view) = accounts_screen::device_login(&scenario) {
|
||||
self.emit(AppEvent::Core(CoreEvent::DeviceLoginChanged(view)));
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(&mut self, event: AppEvent) {
|
||||
@@ -260,7 +275,8 @@ impl Backend for MockBackend {
|
||||
crate::mock_data::mock_diagnosis(id),
|
||||
)));
|
||||
}
|
||||
AppCommand::RefreshAll | AppCommand::RefreshLogSessions | AppCommand::StopAgent => {}
|
||||
AppCommand::RefreshAll => self.seed_accounts(),
|
||||
AppCommand::RefreshLogSessions | AppCommand::StopAgent => {}
|
||||
// 其余指令(安装向导/账户/Java/设置/通知)由真实 host 承接:mock 不模拟
|
||||
_ => {}
|
||||
}
|
||||
@@ -281,7 +297,12 @@ mod tests {
|
||||
fn seeds_instances_and_versions() {
|
||||
let mut backend = MockBackend::new();
|
||||
let events = backend.drain_events();
|
||||
assert_eq!(events.len(), 4);
|
||||
// 实例 / 版本 / 会话 / 日志行 **+ 账户页的种子**(M114:账户列表 + 可选的登录面板态)
|
||||
assert!(
|
||||
events.len() >= 5,
|
||||
"至少含账户列表,实际 {} 条",
|
||||
events.len()
|
||||
);
|
||||
assert!(events
|
||||
.iter()
|
||||
.all(|event| matches!(event, AppEvent::Core(_))));
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! 截图/演示用的账户矩阵(**只在 mock 后端**里被调用)。
|
||||
//!
|
||||
//! D30 要求账户页出五态 × 浅深:空态 / 多账号列表 / 设备码进行中 / 登录失败 / 第三方站表单。
|
||||
//! 截图通道强制 mock 后端(`AppOptions::mock`),所以这五态的**数据**必须由 mock 造:
|
||||
//! 走 `ULL_ACCOUNT_STATE` 选场景,与 `ULL_START_ROUTE` / `ULL_APPEARANCE_*` 同一套取证开关。
|
||||
//!
|
||||
//! ## 造的是什么、不造什么
|
||||
//!
|
||||
//! - 列表行造的是**公开字段**(名字 / 轨道 / 创建时间 / 服务器),与真 host 的
|
||||
//! `AccountView` 同构;
|
||||
//! - **不造皮肤字节**:第三方轨的真图来自服务器,mock 里没有(伪造一张「假皮肤」正好违反
|
||||
//! M114 的口径)。所以截图里皮肤区显示的是首字母块 + 「没有可用皮肤」。
|
||||
|
||||
use crate::dto::{AccountKind, AccountView, DeviceLoginView};
|
||||
|
||||
/// 场景名(`ULL_ACCOUNT_STATE`;未知值按 `list` 处理)。
|
||||
pub(super) fn scenario() -> String {
|
||||
std::env::var("ULL_ACCOUNT_STATE")
|
||||
.unwrap_or_else(|_| "list".to_string())
|
||||
.trim()
|
||||
.to_lowercase()
|
||||
}
|
||||
|
||||
/// 场景对应的账户列表(`empty` 场景是空表 ⇒ 空态)。
|
||||
pub(super) fn accounts(scenario: &str) -> Vec<AccountView> {
|
||||
if scenario == "empty" {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![
|
||||
account(
|
||||
"account:mock-msa",
|
||||
"Steve",
|
||||
AccountKind::Microsoft,
|
||||
"8f2f1d3c4b5a69788796a5b4c3d2e1f0",
|
||||
"steve@outlook.com",
|
||||
"2026-10-28 20:12",
|
||||
true,
|
||||
"",
|
||||
),
|
||||
account(
|
||||
"account:mock-authlib",
|
||||
"Alex",
|
||||
AccountKind::Authlib,
|
||||
"0a1b2c3d4e5f60718293a4b5c6d7e8f9",
|
||||
"alex@example.com",
|
||||
"2026-10-30 09:40",
|
||||
false,
|
||||
"https://littleskin.cn/api/yggdrasil/",
|
||||
),
|
||||
account(
|
||||
"account:mock-offline",
|
||||
"Herobrine",
|
||||
AccountKind::Offline,
|
||||
"3c4d5e6f708192a3b4c5d6e7f8091a2b",
|
||||
"",
|
||||
"2026-10-31 21:05",
|
||||
false,
|
||||
"",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// 场景对应的登录面板状态(`None` = 没有面板)。
|
||||
pub(super) fn device_login(scenario: &str) -> Option<DeviceLoginView> {
|
||||
match scenario {
|
||||
"device" | "expired" => Some(DeviceLoginView::waiting(
|
||||
"ABCD-EFGH",
|
||||
"https://www.microsoft.com/link",
|
||||
900,
|
||||
"",
|
||||
)),
|
||||
"failed" => Some(DeviceLoginView::failed(
|
||||
"微软拒绝了这次登录:AADSTS7000218(HTTP 403)—— 应用白名单还没批准,或网络被拦截",
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn account(
|
||||
id: &str,
|
||||
name: &str,
|
||||
kind: AccountKind,
|
||||
profile_id: &str,
|
||||
login_name: &str,
|
||||
created: &str,
|
||||
active: bool,
|
||||
server_url: &str,
|
||||
) -> AccountView {
|
||||
AccountView {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
profile_id: profile_id.to_string(),
|
||||
login_name: login_name.to_string(),
|
||||
created: created.to_string(),
|
||||
active,
|
||||
server_url: server_url.to_string(),
|
||||
skin: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_empty_scenario_has_no_rows_and_the_list_scenario_covers_all_three_tracks() {
|
||||
assert!(accounts("empty").is_empty());
|
||||
let rows = accounts("list");
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert!(rows.iter().any(|row| row.kind == AccountKind::Microsoft));
|
||||
assert!(rows.iter().any(|row| row.kind == AccountKind::Authlib));
|
||||
assert!(rows.iter().any(|row| row.kind == AccountKind::Offline));
|
||||
assert_eq!(rows.iter().filter(|row| row.active).count(), 1);
|
||||
assert!(rows.iter().all(|row| row.skin.is_none()), "mock 不伪造皮肤");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_device_states_are_renderable() {
|
||||
assert!(device_login("device").is_some_and(|view| !view.user_code.is_empty()));
|
||||
assert!(device_login("failed")
|
||||
.is_some_and(|view| view.phase == crate::dto::DeviceLoginPhase::Failed));
|
||||
assert!(device_login("list").is_none());
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,11 @@ pub enum Route {
|
||||
Logs,
|
||||
/// G6 设置页
|
||||
Settings,
|
||||
/// G7 账户页(三轨登录:微软正版 / 第三方皮肤站 / 本地档案)
|
||||
///
|
||||
/// 一级页,但**不进主序列**:入口是导航轨底部的头像位(`shell/nav.rs`),
|
||||
/// 所以 [`Route::nav`] 对它返回 `None`(不点亮四个主项中的任何一个)。
|
||||
Accounts,
|
||||
/// 实例详情(G4):从磁贴点进来,返回时回到实例页
|
||||
Detail(InstanceId),
|
||||
/// AI 助手独立页(D16 双形态之一)
|
||||
@@ -46,7 +51,13 @@ impl Route {
|
||||
pub fn is_top_level(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Instances | Self::Download | Self::Content | Self::Logs | Self::Settings
|
||||
// M109 的 `Content` 与 M114 的 `Accounts` 都是一级页:两个都留。
|
||||
Self::Instances
|
||||
| Self::Download
|
||||
| Self::Content
|
||||
| Self::Logs
|
||||
| Self::Settings
|
||||
| Self::Accounts
|
||||
)
|
||||
}
|
||||
|
||||
@@ -57,7 +68,7 @@ impl Route {
|
||||
Self::Download | Self::Content => Some(NavSection::Download),
|
||||
Self::Logs => Some(NavSection::Logs),
|
||||
Self::Settings => Some(NavSection::Settings),
|
||||
Self::Agent => None,
|
||||
Self::Accounts | Self::Agent => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,11 @@
|
||||
use crate::agent::AgentRail;
|
||||
use crate::dialogs::DialogQueue;
|
||||
use crate::dto::{
|
||||
AccountView, AgentEvent, AppEvent, CoreEvent, DeviceLoginView, DiagnosisReport,
|
||||
InstallProgressView, InstanceRuntime, InstanceSummary, JavaPageView, LoaderKind, LogLine,
|
||||
LogSession, NoticeView, PackState, Progress, SettingGroupView, VersionSummary,
|
||||
// 主线(M105 的 `LoaderKind` / M113 的 `PackState`)与 M114 的 `AuthlibLoginView` 并集。
|
||||
AccountView, AgentEvent, AppEvent, AuthlibLoginView, CoreEvent, DeviceLoginView,
|
||||
DiagnosisReport, InstallProgressView, InstanceRuntime, InstanceSummary, JavaPageView,
|
||||
LoaderKind, LogLine, LogSession, NoticeView, PackState, Progress, SettingGroupView,
|
||||
VersionSummary,
|
||||
};
|
||||
use crate::prefs::UiPrefs;
|
||||
// 内容库的视图态与其 DTO 放一起(`dto/content.rs`),路径 `state::ContentState` 不变。
|
||||
@@ -17,6 +19,13 @@ use crate::router::{AiPanelMode, Route, Router};
|
||||
use crate::toast::{ToastCenter, ToastKind};
|
||||
use crate::wizard::WizardState;
|
||||
|
||||
// 账户/登录状态(倒计时、上屏前二次脱敏)拆在 `state/accounts.rs`,守 400 行硬线。
|
||||
//
|
||||
// `AiSession` 不再存在:M104 把它换成了 `crate::agent::AgentRail`(agent 栏的视图模型),
|
||||
// 所以这里没有 `mod ai;` / `pub use ai::AiSession;`——M114 r1 曾把旧结构搬到 `state/ai.rs`,
|
||||
// 该文件已随 rebase 删除,**以 main 的 agent 契约为准**。
|
||||
mod accounts;
|
||||
|
||||
/// 磁贴网格单元:位置由 [`grid_positions`] 算好,UI 侧只消费 row/col。
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TileCell<'a> {
|
||||
@@ -79,6 +88,10 @@ pub struct AppState {
|
||||
pub accounts: Vec<AccountView>,
|
||||
/// 微软登录状态
|
||||
pub device_login: DeviceLoginView,
|
||||
/// 第三方轨(authlib-injector)登录/校验状态
|
||||
pub authlib_login: AuthlibLoginView,
|
||||
/// 设备码等待态的开始时刻(倒计时;`None` = 没有在等)
|
||||
pub device_login_started: Option<std::time::Instant>,
|
||||
/// Java 页快照(发行版 / 回退链 / 运行时)
|
||||
pub java: JavaPageView,
|
||||
/// 安装进度(None = 没有安装任务)
|
||||
@@ -140,6 +153,8 @@ impl AppState {
|
||||
download_query: String::new(),
|
||||
accounts: Vec::new(),
|
||||
device_login: DeviceLoginView::new(),
|
||||
authlib_login: AuthlibLoginView::new(),
|
||||
device_login_started: None,
|
||||
java: JavaPageView::new(),
|
||||
install: None,
|
||||
install_cancelled: 0,
|
||||
@@ -237,16 +252,8 @@ impl AppState {
|
||||
}
|
||||
CoreEvent::DiagnosisReady(report) => self.diagnosis = Some(report),
|
||||
CoreEvent::AccountsChanged(accounts) => self.accounts = accounts,
|
||||
CoreEvent::DeviceLoginChanged(view) => {
|
||||
if view.phase == crate::dto::DeviceLoginPhase::Succeeded {
|
||||
self.toasts
|
||||
.push(ToastKind::Success, format!("已登录:{}", view.account_name));
|
||||
}
|
||||
if view.phase == crate::dto::DeviceLoginPhase::Failed {
|
||||
self.toasts.push(ToastKind::Error, view.message.clone());
|
||||
}
|
||||
self.device_login = view;
|
||||
}
|
||||
CoreEvent::DeviceLoginChanged(view) => self.apply_device_login(view),
|
||||
CoreEvent::AuthlibLoginChanged(view) => self.apply_authlib_login(view),
|
||||
CoreEvent::JavaChanged(page) => self.java = page,
|
||||
CoreEvent::InstallProgress(progress) => match progress {
|
||||
Some(progress) => {
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//! 账户/登录状态:事件落地(含**上屏前再脱敏**)、设备码倒计时、当前账户查询。
|
||||
//!
|
||||
//! 从 `state.rs` 拆出来守 400 行硬线;`AppState` 的字段仍在那个文件里,
|
||||
//! 这里只加它的 `impl`(同一个 crate 的固有 impl 可以拆在多个文件)。
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::dto::{AccountView, AuthlibLoginView, DeviceLoginPhase, DeviceLoginView, REDACTED};
|
||||
use crate::toast::ToastKind;
|
||||
|
||||
use super::AppState;
|
||||
|
||||
impl AppState {
|
||||
/// 微软登录状态落地。
|
||||
///
|
||||
/// **凭据红线(M114)**:这里对 `message` 再做一次形状脱敏。DTO 的构造器已经脱过一遍,
|
||||
/// 但状态层是**所有**事件都要过的唯一闸口——将来谁新加一个构造器忘了脱敏,也不会把
|
||||
/// 服务端回显的 token 画到面板上。脱敏是幂等的,重复做没有代价。
|
||||
pub fn apply_device_login(&mut self, mut view: DeviceLoginView) {
|
||||
view.message = crate::dto::redact(&view.message);
|
||||
view.account_name = crate::dto::redact(&view.account_name);
|
||||
match view.phase {
|
||||
DeviceLoginPhase::Succeeded => {
|
||||
self.toasts
|
||||
.push(ToastKind::Success, format!("已登录:{}", view.account_name));
|
||||
self.device_login_started = None;
|
||||
}
|
||||
DeviceLoginPhase::Failed => {
|
||||
self.toasts.push(ToastKind::Error, view.message.clone());
|
||||
self.device_login_started = None;
|
||||
}
|
||||
DeviceLoginPhase::Waiting => {
|
||||
// 每次进入等待态都重记起点:换流/重试之后倒计时必须从头算
|
||||
if self.device_login.phase != DeviceLoginPhase::Waiting
|
||||
|| self.device_login.user_code != view.user_code
|
||||
{
|
||||
self.device_login_started = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
DeviceLoginPhase::Idle | DeviceLoginPhase::Requesting => {
|
||||
self.device_login_started = None;
|
||||
}
|
||||
}
|
||||
self.device_login = view;
|
||||
}
|
||||
|
||||
/// 第三方轨登录状态落地(同样在状态层再脱敏一遍)。
|
||||
pub fn apply_authlib_login(&mut self, mut view: AuthlibLoginView) {
|
||||
view.message = crate::dto::redact(&view.message);
|
||||
view.server_name = crate::dto::redact(&view.server_name);
|
||||
match view.phase {
|
||||
DeviceLoginPhase::Succeeded => {
|
||||
self.toasts
|
||||
.push(ToastKind::Success, format!("已登录:{}", view.account_name));
|
||||
}
|
||||
DeviceLoginPhase::Failed => {
|
||||
self.toasts.push(ToastKind::Error, view.message.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.authlib_login = view;
|
||||
}
|
||||
|
||||
/// 设备码/授权码还剩几秒(`None` = 没有在等 / 不知道有效期)。
|
||||
///
|
||||
/// 纯计算 + 一个起点,UI 侧每秒重问一次就能画出倒计时——这也让「过期」成为**可观测**的
|
||||
/// 状态(任务要求:设备码不得只转圈,过期要显示「已过期,重试」)。
|
||||
pub fn device_code_remaining(&self) -> Option<u64> {
|
||||
self.device_code_remaining_at(Instant::now())
|
||||
}
|
||||
|
||||
/// [`Self::device_code_remaining`] 的可注入时钟版本(单测用)。
|
||||
pub fn device_code_remaining_at(&self, now: Instant) -> Option<u64> {
|
||||
if self.device_login.phase != DeviceLoginPhase::Waiting {
|
||||
return None;
|
||||
}
|
||||
let expires = self.device_login.expires_in;
|
||||
if expires == 0 {
|
||||
return None;
|
||||
}
|
||||
let started = self.device_login_started?;
|
||||
let elapsed = now.saturating_duration_since(started).as_secs();
|
||||
Some(expires.saturating_sub(elapsed))
|
||||
}
|
||||
|
||||
/// 当前启动账户(列表里 `active == true` 的那条)。
|
||||
pub fn active_account(&self) -> Option<&AccountView> {
|
||||
self.accounts.iter().find(|account| account.active)
|
||||
}
|
||||
|
||||
/// 面板要显示的脱敏占位符(守门测试用:值不该出现在任何可见文案里)。
|
||||
pub const REDACTED: &'static str = REDACTED;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const JWT: &str =
|
||||
"eyJhbGciOiJSUzI1NiIsIng1dCI6IkFCQyJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlLXZhbHVl";
|
||||
|
||||
fn state() -> AppState {
|
||||
AppState::new()
|
||||
}
|
||||
|
||||
/// 凭据红线:**绕过构造器**直接塞一个带 JWT 的事件,状态层必须把它抹掉。
|
||||
///
|
||||
/// 抓得住:`apply_device_login` / `apply_authlib_login` 里的脱敏被删(那是「最后一个闸口」)。
|
||||
/// 抓不住:恶意的 UI 层(如果有人绕过 `AppState` 直接画 DTO)。
|
||||
#[test]
|
||||
fn a_token_injected_into_events_never_reaches_the_state() {
|
||||
let mut state = state();
|
||||
state.apply_device_login(DeviceLoginView {
|
||||
phase: DeviceLoginPhase::Failed,
|
||||
message: format!("登录失败:accessToken={JWT}"),
|
||||
..DeviceLoginView::new()
|
||||
});
|
||||
assert!(
|
||||
!state.device_login.message.contains(JWT),
|
||||
"{}",
|
||||
state.device_login.message
|
||||
);
|
||||
assert!(state.device_login.message.contains(REDACTED));
|
||||
|
||||
state.apply_authlib_login(AuthlibLoginView {
|
||||
phase: DeviceLoginPhase::Failed,
|
||||
message: format!("服务器回包 {JWT}"),
|
||||
..AuthlibLoginView::new()
|
||||
});
|
||||
assert!(
|
||||
!state.authlib_login.message.contains(JWT),
|
||||
"{}",
|
||||
state.authlib_login.message
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_device_code_countdown_is_derived_from_a_start_instant() {
|
||||
let mut state = state();
|
||||
state.apply_device_login(DeviceLoginView::waiting(
|
||||
"ABCD-EFGH",
|
||||
"https://www.microsoft.com/link",
|
||||
900,
|
||||
"",
|
||||
));
|
||||
let started = state.device_login_started.expect("等待态要记起点");
|
||||
assert_eq!(state.device_code_remaining_at(started), Some(900));
|
||||
let later = started + std::time::Duration::from_secs(120);
|
||||
assert_eq!(state.device_code_remaining_at(later), Some(780));
|
||||
let expired = started + std::time::Duration::from_secs(901);
|
||||
assert_eq!(
|
||||
state.device_code_remaining_at(expired),
|
||||
Some(0),
|
||||
"过期后是 0,不是 None"
|
||||
);
|
||||
|
||||
// 没有在等的时候不画倒计时
|
||||
state.apply_device_login(DeviceLoginView::failed("网络超时"));
|
||||
assert_eq!(state.device_code_remaining_at(started), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_waiting_view_restarts_the_countdown() {
|
||||
let mut state = state();
|
||||
state.apply_device_login(DeviceLoginView::waiting("AAAA-AAAA", "https://a", 900, ""));
|
||||
let first = state.device_login_started.expect("起点");
|
||||
state.apply_device_login(DeviceLoginView::waiting("BBBB-BBBB", "https://a", 900, ""));
|
||||
let second = state.device_login_started.expect("起点");
|
||||
assert!(second >= first, "换了一个用户码就要重算倒计时");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_active_account_is_the_one_marked_active() {
|
||||
let mut state = state();
|
||||
state.accounts = vec![
|
||||
AccountView {
|
||||
id: "account:a".to_string(),
|
||||
name: "Steve".to_string(),
|
||||
kind: crate::dto::AccountKind::Microsoft,
|
||||
profile_id: "0f8f".to_string(),
|
||||
login_name: String::new(),
|
||||
created: String::new(),
|
||||
active: false,
|
||||
server_url: String::new(),
|
||||
skin: None,
|
||||
},
|
||||
AccountView {
|
||||
id: "account:b".to_string(),
|
||||
name: "Alex".to_string(),
|
||||
kind: crate::dto::AccountKind::Offline,
|
||||
profile_id: "1a2b".to_string(),
|
||||
login_name: String::new(),
|
||||
created: String::new(),
|
||||
active: true,
|
||||
server_url: String::new(),
|
||||
skin: None,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
state.active_account().map(|a| a.name.as_str()),
|
||||
Some("Alex")
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user