Files
Thing/src-tauri/src/music/decrypt/qq_credentials.rs
T
2026-09-28 00:21:12 +08:00

286 lines
9.5 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! QQ音乐本机凭据读取(`uin` + `authst`)。
//!
//! ## 为什么要读进程内存
//!
//! Windows 版 QQ 音乐**没有持久化 `authst`**:`uin` 能从
//! `%APPDATA%\Tencent\QQMusic\QQMusicServiceConfig.ini` 明文读到,但 `authst`
//! 只作为 JSON 字符串存在于运行中的 `QQMusic.exe` 内存里(有效期约 22.3 小时)。
//! 所以「在线取 ekey」的前置条件是:**QQ 音乐正在运行且已登录**。
//!
//! 这里只做**只读**内存访问(`OpenProcess` + `VirtualQueryEx` + `ReadProcessMemory`),
//! 不注入、不改写任何东西——这是它与 Frida 兜底方案的本质区别,
//! 也是它通常不会被安全软件拦截的原因。
//!
//! ## 结构
//!
//! - [`parse_ini_uin`]:纯函数,可跨平台单测;
//! - [`find_authst`]:纯函数,在给定字节里找 `"authst":"<token>"`,可单测;
//! - [`read_credentials`]:平台相关的胶水(Windows 实现 / 其他平台的空实现)。
/// 从 QQ 音乐的 INI 文本里取 `[Account] Uin`。
///
/// 该文件很小(实测 27 字节)且是**纯文本**,格式固定:
///
/// ```ini
/// [Account]
/// Uin=1154027699
/// ```
///
/// 解析上刻意宽松:允许前导空白、大小写不敏感、允许 `Uin` 出现在任意段里
/// (不同版本段名可能变),但**只认第一处**出现的非空 Uin。
pub fn parse_ini_uin(text: &str) -> Option<String> {
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with(';') || line.starts_with('#') {
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
if !key.trim().eq_ignore_ascii_case("uin") {
continue;
}
let v = value.trim().trim_matches('"');
// 必须是纯数字(QQ 号),排除 `Uin=` 之类的空值或占位
if !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()) {
return Some(v.to_string());
}
}
None
}
/// `authst` 在内存里的 JSON 形态:`"authst":"<base64url-ish>"`。
const AUTHST_KEY: &[u8] = b"\"authst\":\"";
/// 在一段内存字节里查找 `authst` 的值(从 0 开始)。
///
/// 生产路径用 [`find_authst_from`](分块扫描需要偏移),这个薄封装给测试用。
#[cfg_attr(not(test), allow(dead_code))]
pub fn find_authst(haystack: &[u8]) -> Option<String> {
find_authst_from(haystack, 0)
}
/// 从 `start` 起查找(供分块扫描时避免重复命中同一处)
pub fn find_authst_from(haystack: &[u8], start: usize) -> Option<String> {
let mut pos = start;
while pos + AUTHST_KEY.len() <= haystack.len() {
let Some(rel) = find_subslice(&haystack[pos..], AUTHST_KEY) else {
return None;
};
let val_start = pos + rel + AUTHST_KEY.len();
// token 到下一个双引号结束
let Some(end_rel) = haystack[val_start..].iter().position(|&b| b == b'"') else {
return None;
};
let token = &haystack[val_start..val_start + end_rel];
if is_plausible_token(token) {
return Some(String::from_utf8_lossy(token).to_string());
}
// 命中但是假阳性:从下一个字节继续找
pos = val_start;
}
None
}
fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || haystack.len() < needle.len() {
return None;
}
haystack.windows(needle.len()).position(|w| w == needle)
}
fn is_plausible_token(token: &[u8]) -> bool {
token.len() >= 16
&& token.iter().all(|&b| {
b.is_ascii_alphanumeric()
|| b == b'-'
|| b == b'_'
|| b == b'='
|| b == b'+'
|| b == b'/'
})
}
/// 凭据读取结果
#[derive(Debug, Clone, Default)]
pub struct QqCredentials {
/// QQ 号(来自 INI)
pub uin: Option<String>,
/// 运行期认证令牌(来自进程内存)
pub authst: Option<String>,
}
impl QqCredentials {
/// 是否可用于调用 `GetEVkey`
pub fn usable(&self) -> bool {
self.uin.is_some() && self.authst.is_some()
}
/// 给 UI 的简短状态(三态,供状态卡渲染)
pub fn status_text(&self) -> &'static str {
match (self.uin.is_some(), self.authst.is_some()) {
(true, true) => "已就绪",
(true, false) => "QQ 音乐未运行或未登录",
(false, _) => "未找到本机 QQ 音乐账号",
}
}
}
/// `QQMusic.exe` 的进程名(枚举时用大小写不敏感的子串匹配)
pub const QQ_PROCESS_HINT: &str = "qqmusic";
/// QQ 音乐配置 INI 的路径(Windows)
#[cfg(windows)]
pub fn config_ini_path() -> Option<std::path::PathBuf> {
let appdata = std::env::var_os("APPDATA")?;
Some(
std::path::PathBuf::from(appdata)
.join("Tencent")
.join("QQMusic")
.join("QQMusicServiceConfig.ini"),
)
}
#[cfg(not(windows))]
pub fn config_ini_path() -> Option<std::path::PathBuf> {
None
}
/// 读凭据:`uin` 从 INI,`authst` 扫进程内存。
///
/// 任何一步失败都只是 `None`(并记日志),不返回错误——调用方据
/// [`QqCredentials::usable`] 决定是走在线取 ekey 还是给出引导。
pub fn read_credentials() -> QqCredentials {
let uin = config_ini_path()
.and_then(|p| std::fs::read_to_string(&p).ok())
.and_then(|t| parse_ini_uin(&t))
.or_else(|| {
// 兜底:文件读不到时,从进程内存里找 "uin":"..." 形态
scan_authst_in_process().1
});
let (authst, uin_from_mem) = match uin {
// 有 uin 时只需要 authst
Some(_) => (scan_authst_in_process().0, None),
// 没 uin 时一次扫描同时拿两者
None => {
let (a, u) = scan_authst_in_process();
(a, u)
}
};
QqCredentials {
uin: uin.or(uin_from_mem),
authst,
}
}
#[cfg(windows)]
fn scan_authst_in_process() -> (Option<String>, Option<String>) {
match crate::music::decrypt::qq_memscan::scan_qq_process() {
Ok(found) => (found.authst, found.uin),
Err(e) => {
crate::logger::log_warn("music-decrypt", &format!("扫描 QQ 音乐进程内存失败:{e}"));
(None, None)
}
}
}
#[cfg(not(windows))]
fn scan_authst_in_process() -> (Option<String>, Option<String>) {
(None, None)
}
#[cfg(test)]
mod tests {
use super::*;
// ============ INI 解析 ============
#[test]
fn parses_real_ini_shape() {
// 本机实测就是这个形状(27 字节)
let text = "[Account]\r\nUin=1154027699\r\n";
assert_eq!(parse_ini_uin(text).as_deref(), Some("1154027699"));
}
#[test]
fn parses_ini_leniently() {
// 大小写、空白、引号、注释、其他段
let text = "\u{feff}; comment\r\n[Other]\r\nx=1\r\n\r\n uin = \"123456\" \r\n";
assert_eq!(parse_ini_uin(text).as_deref(), Some("123456"));
}
#[test]
fn ignores_non_numeric_or_empty_uin() {
assert!(parse_ini_uin("Uin=\r\n").is_none());
assert!(parse_ini_uin("Uin=abc\r\n").is_none());
assert!(parse_ini_uin("Uin=12a45\r\n").is_none());
assert!(parse_ini_uin("").is_none());
assert!(parse_ini_uin("[Account]\nFoo=1\n").is_none());
}
// ============ authst 提取 ============
#[test]
fn finds_authst_in_memory_blob() {
let token = "AbCd_-1234567890AbCd_-1234567890";
let blob = format!("junk{{\"uin\":\"1154027699\",\"authst\":\"{token}\",\"other\":1}}tail");
assert_eq!(find_authst(blob.as_bytes()).as_deref(), Some(token));
}
#[test]
fn rejects_implausible_authst() {
// 太短
assert!(find_authst(b"\"authst\":\"short\"").is_none());
// 含非法字符(像模板/日志)
assert!(find_authst(b"\"authst\":\"this is not a token at all\"").is_none());
// 没有值
assert!(find_authst(b"\"authst\":\"\"").is_none());
// 完全没有
assert!(find_authst(b"nothing here").is_none());
}
/// 第一处是假阳性时,应继续往后找真 token
#[test]
fn skips_false_positive_and_keeps_searching() {
let token = "RealToken_1234567890abcdef";
let blob = format!("\"authst\":\"x\"...\"authst\":\"{token}\"");
assert_eq!(find_authst(blob.as_bytes()).as_deref(), Some(token));
}
/// 跨缓冲区边界不会误判(分块扫描用 find_authst_from)
#[test]
fn find_from_offset_advances() {
let blob = b"aaaa\"authst\":\"AAAAAAAAAAAAAAAA\"";
let first = find_authst_from(blob, 0).unwrap();
assert_eq!(first, "AAAAAAAAAAAAAAAA");
// 从命中处之后继续找应该没有第二个
let key_at = 4 + AUTHST_KEY.len();
assert!(find_authst_from(blob, key_at).is_none());
}
// ============ 状态文案 ============
#[test]
fn credentials_status_text_covers_three_states() {
let none = QqCredentials::default();
assert!(!none.usable());
assert!(none.status_text().contains("未找到"));
let uin_only = QqCredentials {
uin: Some("1".into()),
authst: None,
};
assert!(!uin_only.usable());
assert!(uin_only.status_text().contains("未运行"));
let full = QqCredentials {
uin: Some("1".into()),
authst: Some("t".into()),
};
assert!(full.usable());
assert_eq!(full.status_text(), "已就绪");
}
}