diff --git a/README.en.md b/README.en.md index 9317291..3ef4b54 100644 --- a/README.en.md +++ b/README.en.md @@ -212,6 +212,8 @@ Run inside your graphical session: Scan the code with the **NetEase UU Remote mobile app** and confirm. Credentials are stored only on this machine, in `~/.config/uuremote/config.json` (mode 0600). +A failed status query or the 60-second request timeout does not prove that the QR expired or that the phone confirmed login. The official-client refresh policy is unchanged: after a query error, click Refresh QR (Enter in a terminal; refresh after 60 seconds with neither a window nor a terminal). QR request diagnostics contain only the request phase, error category, elapsed time, HTTP/API status and last known scan state—not tickets, URLs or response content. A `connect` category alone does not identify a DNS, TLS or proxy cause. + ### 4. Run as a user service `~/.config/systemd/user/uuremote-native.service`: diff --git a/README.md b/README.md index aba0771..d4f815a 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,8 @@ cargo build --release --features wayland,portal # + GNOME/KDE Wayland 用手机上的 **网易 UU 远程 App** 扫码并确认即可。登录信息只保存在本机的 `~/.config/uuremote/config.json`(权限 0600)里。 +登录状态查询失败或达到 60 秒请求超时不代表二维码已过期,也不代表手机已经确认。程序保留官方客户端的刷新策略:查询出错后点击「刷新二维码」(终端按回车;无窗口且无终端时 60 秒后刷新)。二维码请求诊断只包含请求阶段、错误类别、耗时、HTTP/API 状态及最后已知扫码状态,不输出票据、URL 或响应内容;`connect` 类别本身不能确定是 DNS、TLS 还是代理问题。 + ### 4. 作为用户服务常驻 `~/.config/systemd/user/uuremote-native.service`: diff --git a/src/auth.rs b/src/auth.rs index 50f45fb..b0d40d2 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -91,6 +91,48 @@ pub struct UUAuthClient { guest_id: Option, } +/// QR failures are safe to display: never retain a URL, source error or response body. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QrRequestErrorKind { Timeout, Connect, Decode, Body, Request } +impl QrRequestErrorKind { + fn from_reqwest(error: &reqwest::Error) -> Self { + if error.is_timeout() { Self::Timeout } + else if error.is_connect() { Self::Connect } + else if error.is_decode() { Self::Decode } + else if error.is_body() { Self::Body } + else { Self::Request } + } + fn label(self) -> &'static str { + match self { Self::Timeout => "timeout", Self::Connect => "connect", Self::Decode => "decode", + Self::Body => "body", Self::Request => "request" } + } +} +#[derive(Debug)] +pub struct QrRequestError { + pub kind: QrRequestErrorKind, + phase: &'static str, + elapsed_ms: u128, + http_status: Option, +} +impl std::fmt::Display for QrRequestError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "phase={} kind={} elapsed_ms={} http_status={:?}", + self.phase, self.kind.label(), self.elapsed_ms, self.http_status) + } +} +impl QrRequestError { + pub fn response_received(&self) -> bool { self.http_status.is_some() } + fn new(kind: QrRequestErrorKind, phase: &'static str, started: std::time::Instant, http_status: Option) -> Self { + Self { kind, phase, elapsed_ms: started.elapsed().as_millis(), http_status } + } +} +async fn send_qr_request(request: reqwest::RequestBuilder, started: std::time::Instant) -> Result<(u16, serde_json::Value), QrRequestError> { + let resp = request.send().await.map_err(|e| QrRequestError::new(QrRequestErrorKind::from_reqwest(&e), "send", started, None))?; + let status = resp.status().as_u16(); + let value = resp.json().await.map_err(|e| QrRequestError::new(QrRequestErrorKind::from_reqwest(&e), "response", started, Some(status)))?; + Ok((status, value)) +} + /// Transport failures name only the outer request; the cause (certificate, proxy, DNS, /// timeout) lives in the source chain. URL user-info (proxy credentials) and query /// strings are removed before the chain is shown. @@ -253,13 +295,13 @@ impl UUAuthClient { /// Signed POST with an optional JSON body (None = empty body, like Moya `requestPlain`) and an /// explicit timeout. The official clients long-poll the QR status with a 60 s request timeout. - pub async fn post_with_timeout(&self, path: &str, body: Option<&serde_json::Value>, timeout: std::time::Duration) -> Result<(u16, serde_json::Value), String> { - let body_str = body.map(serde_json::to_string).transpose().map_err(|e| e.to_string())?.unwrap_or_default(); - let resp = self.http.post(format!("{}{}", BASE_URL, path)).timeout(timeout) - .headers(self.build_headers("POST", path, &body_str)).body(body_str) - .send().await.map_err(|e| format!("HTTP post {path} failed: {}", transport_error(&e)))?; - let status = resp.status().as_u16(); - Ok((status, resp.json().await.unwrap_or(serde_json::Value::Null))) + pub async fn post_with_timeout(&self, path: &str, body: Option<&serde_json::Value>, timeout: std::time::Duration) -> Result<(u16, serde_json::Value), QrRequestError> { + let started = std::time::Instant::now(); + let body_str = body.map(serde_json::to_string).transpose() + .map_err(|_| QrRequestError::new(QrRequestErrorKind::Request, "encode", started, None))?.unwrap_or_default(); + let request = self.http.post(format!("{}{}", BASE_URL, path)).timeout(timeout) + .headers(self.build_headers("POST", path, &body_str)).body(body_str); + send_qr_request(request, started).await } /// Signed JSON POST to another API host (the signature covers the path only). @@ -389,3 +431,58 @@ mod guest_tests { for value in ["", "0", "false", "no", "off", "2"] { assert!(!super::proxy_requested(value)); } } } + +#[cfg(test)] +mod qr_request_tests { + use super::*; + use std::time::{Duration, Instant}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + // Synthetic, loopback-only responses: no account, device, proxy or live login API. + async fn response(reply: &'static [u8], stall: bool) -> QrRequestError { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0u8; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket.write_all(reply).await.unwrap(); + if stall { std::future::pending::<()>().await; } + }); + let request = reqwest::Client::builder().no_proxy().build().unwrap() + .post(format!("http://fixture-user:fixture-password@{addr}/fixture-path?token=fixture-ticket")) + .timeout(Duration::from_secs(2)); + let error = send_qr_request(request, Instant::now()).await.unwrap_err(); + server.abort(); + let output = format!("{error} {error:?}"); + for secret in ["fixture-user", "fixture-password", "fixture-path", "fixture-ticket", "fixture-body", "127.0.0.1", "http://"] { + assert!(!output.contains(secret)); + } + error + } + + #[tokio::test] + async fn qr_request_distinguishes_send_timeout_body_timeout_and_bad_json_without_secrets() { + let error = response(b"", true).await; + assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Timeout, "send", None)); + assert!(!error.response_received()); + let error = response(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n", true).await; + assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Timeout, "response", Some(200))); + assert!(error.response_received()); + let error = response(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 12\r\n\r\nfixture-body", false).await; + assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Decode, "response", Some(502))); + assert!(error.response_received()); + } + + #[tokio::test] + async fn qr_connection_failure_is_not_a_timeout() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + drop(listener); + let request = reqwest::Client::builder().no_proxy().build().unwrap() + .post(format!("http://{addr}/fixture-ticket")).timeout(Duration::from_secs(2)); + let error = send_qr_request(request, Instant::now()).await.unwrap_err(); + assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Connect, "send", None)); + assert!(!format!("{error} {error:?}").contains("fixture-ticket")); + } +} diff --git a/src/login.rs b/src/login.rs index 2215927..7de6d72 100644 --- a/src/login.rs +++ b/src/login.rs @@ -8,7 +8,7 @@ //! (analysis/tools-fix-20261013/viewer-fieldmd.json). Results are written to the private //! config file (chmod 600). Tokens and tickets are never printed or logged. -use crate::auth::{Credentials, UUAuthClient}; +use crate::auth::{Credentials, QrRequestErrorKind, UUAuthClient}; use crate::login_ui::{LoginUi, Tone}; use serde_json::{json, Value}; use std::time::Duration; @@ -127,6 +127,35 @@ fn render_qr(content: &str) -> Result { /// API code for an expired login QR code. const QR_EXPIRED: i64 = 1190; +/// QR API errors must not echo server messages/validation fields: they may contain credentials. +fn qr_data<'a>(stage: &str, status: u16, body: &'a Value) -> Result<&'a Value, String> { + let code = body.get("code").and_then(Value::as_i64); + if status == 200 && code == Some(0) { return Ok(body.get("data").unwrap_or(&Value::Null)); } + Err(format!("{stage}: http_status={status} api_code={code:?}")) +} + +#[derive(Debug, PartialEq, Eq)] +enum QrPollAction { Wait(i64), Scanned, Confirmed, Refresh(Duration), Failed(&'static str) } + +/// Preserve the official refresh policy; a failed query says nothing about QR expiry. +fn qr_poll_action(last_status: i64, http_status: u16, body: &Value) -> QrPollAction { + if body.get("code").and_then(Value::as_i64) == Some(QR_EXPIRED) { + return QrPollAction::Failed("二维码已失效"); + } + let Ok(data) = qr_data("qrcode status", http_status, body) else { + return QrPollAction::Failed("二维码状态查询失败"); + }; + match data.get("status").and_then(Value::as_i64) { + Some(1) => QrPollAction::Wait(1), + Some(2) if last_status != 2 => QrPollAction::Scanned, + Some(2) => QrPollAction::Wait(2), + Some(0) => QrPollAction::Refresh(Duration::from_millis(350)), + Some(3) => QrPollAction::Refresh(Duration::ZERO), + Some(4) => QrPollAction::Confirmed, + _ => QrPollAction::Failed("二维码状态响应异常"), + } +} + /// QR modules as RGBA pixels: `scale` pixels per module, `quiet` light modules around the code. fn qr_rgba(content: &str, scale: usize, quiet: usize) -> Result<(Vec, usize), String> { let code = qrcode::QrCode::new(content.as_bytes()).map_err(|e| format!("QR encode failed: {e}"))?; @@ -276,8 +305,16 @@ pub(crate) async fn flow(ui: &LoginUi) -> Result { // every QR within seconds (#68). let timeout = Duration::from_secs(60); loop { - let (status, resp) = client.post_with_timeout("/api/v1/qrcode/gen/login", None, timeout).await?; - let d = match data("qrcode gen", status, &resp) { + let (status, resp) = match client.post_with_timeout("/api/v1/qrcode/gen/login", None, timeout).await { + Ok(r) => r, + Err(e) if e.response_received() => { + eprintln!("QR generation response failed: {e}"); + wait_for_refresh(ui, "二维码加载失败").await; + continue; + } + Err(e) => return Err(format!("QR generation failed: {e}")), + }; + let d = match qr_data("qrcode gen", status, &resp) { Ok(d) => d.clone(), Err(e) => { println!("QR code could not be loaded ({e})"); wait_for_refresh(ui, "二维码加载失败").await; continue; } }; @@ -303,24 +340,42 @@ pub(crate) async fn flow(ui: &LoginUi) -> Result { let query = json!({"token": ticket, "qrcode_jump_url": url, "login_status": login_status}); let (status, resp) = match client.post_with_timeout("/api/v1/qrcode/login/status", Some(&query), timeout).await { Ok(r) => r, - Err(_) => break "网络超时,二维码已停止刷新", + Err(e) => { + eprintln!("QR status query failed: {e}; last_status={login_status}"); + break match e.kind { + QrRequestErrorKind::Timeout => "二维码状态查询超时(不代表二维码已失效)", + _ => "二维码状态查询失败(不代表二维码已失效)", + }; + } }; - let code = resp.get("code").and_then(|c| c.as_i64()); - if code == Some(QR_EXPIRED) { break "二维码已失效"; } - let Ok(d) = data("qrcode status", status, &resp) else { break "二维码状态查询失败"; }; - let st = d.get("status").and_then(|v| v.as_i64()).unwrap_or(login_status); - match st { - 1 => {} - 2 => if login_status != 2 { + match qr_poll_action(login_status, status, &resp) { + QrPollAction::Wait(st) => { + if st == 1 && login_status != 1 { ui.status("等待扫码…", Tone::Info); } + login_status = st; + } + QrPollAction::Scanned => { + login_status = 2; println!("已扫码,请在手机上确认 (scanned, confirm on the phone)"); ui.status("已扫码,请在手机上确认登录", Tone::Ok); - }, - 3 => { println!("QR code expired; generating a new one"); break ""; } - 0 => { tokio::time::sleep(Duration::from_millis(350)).await; break ""; } - 4 => { + } + QrPollAction::Refresh(delay) => { + if delay.is_zero() { println!("QR code expired; generating a new one"); } + else { tokio::time::sleep(delay).await; } + break ""; + } + QrPollAction::Confirmed => { + println!("已确认,正在完成登录 (confirmed, completing login)"); + ui.status("已确认,正在完成登录…", Tone::Info); let body = json!({"token": ticket, "qrcode_jump_url": url}); - let (status, resp) = client.post_with_timeout("/api/v1/login/by_qrcode", Some(&body), timeout).await?; - let d = match data("qrcode login", status, &resp) { + let (status, resp) = match client.post_with_timeout("/api/v1/login/by_qrcode", Some(&body), timeout).await { + Ok(r) => r, + Err(e) if e.response_received() => { + eprintln!("QR login exchange response failed: {e}"); + break "登录失败"; + } + Err(e) => return Err(format!("QR login exchange failed: {e}")), + }; + let d = match qr_data("qrcode login", status, &resp) { Ok(d) => d, Err(e) => { println!("QR login not granted ({e})"); break "登录失败"; } }; @@ -339,9 +394,12 @@ pub(crate) async fn flow(ui: &LoginUi) -> Result { println!("Logged in as {} ({}); saved to {}", nickname, user, path.display()); return Ok(if nickname.is_empty() { user.to_string() } else { nickname.to_string() }); } - other => { println!("QR status: {other}"); break "二维码已失效"; } + QrPollAction::Failed(reason) => { + eprintln!("QR status query stopped: http_status={status} api_code={:?} status={:?} last_status={login_status}", + resp.get("code").and_then(Value::as_i64), resp.get("data").and_then(|d| d.get("status")).and_then(Value::as_i64)); + break reason; + } } - login_status = st; }; if !failure.is_empty() { wait_for_refresh(ui, failure).await; } } @@ -376,6 +434,37 @@ async fn wait_for_refresh(ui: &LoginUi, reason: &str) { #[cfg(test)] mod tests { use super::*; + #[test] + fn qr_poll_keeps_waiting_scanned_and_confirmed_distinct() { + let reply = |status| json!({"code": 0, "data": {"status": status}}); + assert_eq!(qr_poll_action(1, 200, &reply(1)), QrPollAction::Wait(1)); + assert_eq!(qr_poll_action(1, 200, &reply(2)), QrPollAction::Scanned); + assert_eq!(qr_poll_action(2, 200, &reply(2)), QrPollAction::Wait(2)); + assert_eq!(qr_poll_action(2, 200, &reply(4)), QrPollAction::Confirmed); + assert_eq!(qr_poll_action(1, 200, &reply(0)), QrPollAction::Refresh(Duration::from_millis(350))); + assert_eq!(qr_poll_action(2, 200, &reply(3)), QrPollAction::Refresh(Duration::ZERO)); + assert_eq!(qr_poll_action(2, 400, &json!({"code": 1190})), QrPollAction::Failed("二维码已失效")); + } + + #[test] + fn qr_poll_failures_do_not_imply_expiry_or_confirmation() { + for last in [1, 2] { + for body in [json!(null), json!({"code": 1}), json!({"code": 0, "data": {"status": 4}})] { + assert_eq!(qr_poll_action(last, 503, &body), QrPollAction::Failed("二维码状态查询失败")); + } + assert_eq!(qr_poll_action(last, 200, &json!({"code": 1})), QrPollAction::Failed("二维码状态查询失败")); + for data in [json!(null), json!({}), json!({"status": "4"}), json!({"status": 99}), json!({"status": -1})] { + assert_eq!(qr_poll_action(last, 200, &json!({"code": 0, "data": data})), QrPollAction::Failed("二维码状态响应异常")); + } + } + } + + #[test] + fn qr_api_errors_do_not_echo_server_content() { + let body = json!({"code": 1001, "msg": "fixture-token", "data": [{"loc": "fixture-ticket"}]}); + assert_eq!(qr_data("qrcode gen", 400, &body).unwrap_err(), "qrcode gen: http_status=400 api_code=Some(1001)"); + } + #[test] fn status_ticket_prefers_status_query_ticket() { assert_eq!(qr_ticket(&json!({"token": "old", "status_query_ticket": "new"})), Some("new"));