From 8db927ab0e16c9d0b41aa14c2bc46e65351745ad Mon Sep 17 00:00:00 2001 From: zhom <2717306+zhom@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:41:38 +0400 Subject: [PATCH] fix: renew refused token --- src-tauri/src/cloud_auth.rs | 116 +++++++++++++++++++++++++++++-- src-tauri/src/wayfern_manager.rs | 49 ++++++++++++- 2 files changed, 158 insertions(+), 7 deletions(-) diff --git a/src-tauri/src/cloud_auth.rs b/src-tauri/src/cloud_auth.rs index f5660a27..2900cb29 100644 --- a/src-tauri/src/cloud_auth.rs +++ b/src-tauri/src/cloud_auth.rs @@ -444,6 +444,9 @@ pub struct CloudAuthManager { /// device rule, until a token is acquired again. The engine reports a /// missing token as a plan problem; this is what lets MCP say the real one. wayfern_device_refusal: std::sync::Mutex>, + /// One replacement at a time for a token the browsers report refused, so a + /// refusal that every running browser logs costs one new token. + wayfern_token_renewal: Mutex<()>, } /// Tell what depends on the team seat that the signed-in account changed. @@ -475,6 +478,7 @@ impl CloudAuthManager { wayfern_token: Mutex::new(None), wayfern_token_minted_at: std::sync::Mutex::new(None), wayfern_device_refusal: std::sync::Mutex::new(None), + wayfern_token_renewal: Mutex::new(()), } } @@ -749,6 +753,9 @@ impl CloudAuthManager { wait.as_secs() )); } + // Held until the new refresh token is stored. It is read under the lock, + // so it is the newest one on disk. + let _other_processes = Self::lock_refresh_across_processes().await; let refresh_token = Self::load_refresh_token()?.ok_or_else(|| "No refresh token stored".to_string())?; @@ -787,6 +794,41 @@ impl CloudAuthManager { Ok(()) } + /// Lock the refresh-token rotation against the other Donut processes on this + /// data directory, such as a version an update left running. Each rotation + /// revokes the token it was given, and the server reads a token older than + /// the previous rotation as stolen: it signs the account out everywhere and + /// revokes every Wayfern token. None after 30 seconds or on an I/O error; + /// the rotation then goes ahead unlocked. + async fn lock_refresh_across_processes() -> Option { + let path = Self::get_settings_dir().join("cloud_refresh.lock"); + let locked = tokio::task::spawn_blocking(move || { + let file = fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .map_err(|e| e.to_string())?; + let deadline = Instant::now() + Duration::from_secs(30); + loop { + match file.try_lock() { + Ok(()) => return Ok(file), + Err(fs::TryLockError::WouldBlock) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(100)); + } + Err(fs::TryLockError::WouldBlock) => return Err("held for 30s".to_string()), + Err(fs::TryLockError::Error(e)) => return Err(e.to_string()), + } + } + }) + .await + .map_err(|e| e.to_string()) + .and_then(|locked| locked); + locked + .inspect_err(|e| log::warn!("Token refresh not locked against other processes err=\"{e}\"")) + .ok() + } + fn refresh_deferral(&self) -> Option { let until = (*self .refresh_deferred_until @@ -1786,18 +1828,46 @@ impl CloudAuthManager { } } - /// Whether the cached Wayfern token is old enough to replace, by the clock on - /// the wall: a computer that slept through the night kept the app's timers - /// still while the server's day ran out. - fn wayfern_token_due(&self, now: u64) -> bool { + /// When the cached Wayfern token was minted, unix seconds. + fn wayfern_token_minted_at(&self) -> Option { self .wayfern_token_minted_at .lock() .ok() .and_then(|minted_at| *minted_at) + } + + /// Whether the cached Wayfern token is old enough to replace, by the clock on + /// the wall: a computer that slept through the night kept the app's timers + /// still while the server's day ran out. + fn wayfern_token_due(&self, now: u64) -> bool { + self + .wayfern_token_minted_at() .is_some_and(|minted_at| wayfern_token_stale(minted_at, now)) } + /// Replace a Wayfern token a browser reports refused, while new launches + /// still get it. The server revokes a token on a sign-out or a plan change, + /// and the cached copy does not know. Every browser launched with a refused + /// token tells the engine the account has no plan, and the engine then + /// limits all browsers on this machine to the free number. + pub async fn renew_refused_wayfern_token(&self, refused: &str) { + let _one_at_a_time = self.wayfern_token_renewal.lock().await; + if self.wayfern_token.lock().await.as_deref() != Some(refused) { + return; + } + let renewable = self + .wayfern_token_minted_at() + .is_none_or(|minted_at| wayfern_token_renewable(minted_at, crate::proxy_manager::now_secs())); + if !renewable { + return; + } + match self.request_wayfern_token().await { + Ok(()) => log::info!("Wayfern token replaced after a browser was refused its plan"), + Err(e) => log::warn!("Wayfern token not replaced after a browser refusal err=\"{e}\""), + } + } + /// A fresh Wayfern token after the engine refused the cached one for a /// feature this plan includes. The server drops a token on a plan change /// and after a day; the cached copy does not know. @@ -2158,6 +2228,15 @@ fn wayfern_token_stale(minted_at: u64, now: u64) -> bool { now.saturating_sub(minted_at) >= WAYFERN_TOKEN_REFRESH_SECS } +/// How old a refused Wayfern token must be before a refusal replaces it. A +/// refusal a new token cannot fix, such as the server's verify throttle, then +/// costs one token in this time, not one per browser report. +const WAYFERN_TOKEN_RENEWAL_SECS: u64 = 10 * 60; + +fn wayfern_token_renewable(minted_at: u64, now: u64) -> bool { + now.saturating_sub(minted_at) >= WAYFERN_TOKEN_RENEWAL_SECS +} + #[tauri::command] pub async fn cloud_refresh_wayfern_token() -> Result, String> { CLOUD_AUTH.request_wayfern_token().await?; @@ -2698,6 +2777,35 @@ mod tests { assert!(wayfern_token_stale(minted, minted + 20 * 60 * 60)); } + #[test] + fn a_refused_wayfern_token_is_replaced_at_most_once_in_ten_minutes() { + let minted = 1_800_000_000; + assert!(!wayfern_token_renewable(minted, minted)); + assert!(!wayfern_token_renewable( + minted, + minted + WAYFERN_TOKEN_RENEWAL_SECS - 1 + )); + assert!(wayfern_token_renewable( + minted, + minted + WAYFERN_TOKEN_RENEWAL_SECS + )); + } + + #[test] + fn a_refresh_reads_the_refresh_token_under_the_cross_process_lock() { + let source = include_str!("cloud_auth.rs"); + let body = source + .split("async fn refresh_while_locked(&self)") + .nth(1) + .expect("refresh_while_locked must exist"); + let body = &body[..body.find("\n }").unwrap_or(body.len())]; + let locked = body + .find("lock_refresh_across_processes()") + .expect("the rotation must lock out other processes"); + assert!(locked < body.find("load_refresh_token()").unwrap()); + assert!(locked < body.find("store_refresh_token(").unwrap()); + } + #[test] fn retry_after_accepts_seconds_and_http_dates() { let now = chrono::DateTime::parse_from_rfc3339("2026-09-27T10:00:00Z") diff --git a/src-tauri/src/wayfern_manager.rs b/src-tauri/src/wayfern_manager.rs index 80bff4d8..1d5bd4be 100644 --- a/src-tauri/src/wayfern_manager.rs +++ b/src-tauri/src/wayfern_manager.rs @@ -1093,6 +1093,13 @@ fn browser_line_level(line: &str) -> Option { None } +/// Whether a browser line says the engine holds no plan for the browser's +/// token: the server denied the token, or the launch met the browser cap that +/// a denied token sets for every browser on the machine. +fn says_plan_refused(line: &str) -> bool { + line.contains("VerifyTokenForPlan: plan=free ") || line.contains("Wayfern instance limit reached") +} + /// One `os_crypt` line per profile a minute: a browser that cannot open its /// key says so for every cookie. static OS_CRYPT_LINES: crate::log_streak::Throttle = @@ -1100,8 +1107,14 @@ static OS_CRYPT_LINES: crate::log_streak::Throttle = /// Keep reading the browser's stderr for its lifetime, keeping only what it /// says about Wayfern. Reading it all is what keeps the pipe from filling. -/// `owner` is `key=value` text naming whose browser this is. -fn tap_browser_stderr(stderr: tokio::process::ChildStderr, tap: BrowserLogTap, owner: String) { +/// `owner` is `key=value` text naming whose browser this is, and `token` the +/// Wayfern token it was launched with: a refusal of it gets a new one. +fn tap_browser_stderr( + stderr: tokio::process::ChildStderr, + tap: BrowserLogTap, + owner: String, + token: Option, +) { tauri::async_runtime::spawn(async move { use tokio::io::{AsyncBufReadExt, BufReader}; let mut lines = BufReader::new(stderr).lines(); @@ -1109,6 +1122,13 @@ fn tap_browser_stderr(stderr: tokio::process::ChildStderr, tap: BrowserLogTap, o let Some(level) = browser_line_level(&line) else { continue; }; + if let Some(refused) = token.clone().filter(|_| says_plan_refused(&line)) { + tauri::async_runtime::spawn(async move { + crate::cloud_auth::CLOUD_AUTH + .renew_refused_wayfern_token(&refused) + .await; + }); + } let text = crate::log_redaction::text(&line); if level == log::Level::Warn { let key = owner.split_whitespace().next().unwrap_or_default(); @@ -1245,7 +1265,12 @@ impl HeadlessWayfern { }; let log = BrowserLogTap::default(); if let Some(stderr) = child.stderr.take() { - tap_browser_stderr(stderr, log.clone(), label.to_string()); + tap_browser_stderr( + stderr, + log.clone(), + label.to_string(), + token.map(str::to_string), + ); } let mut session = Self { @@ -3652,6 +3677,7 @@ impl WayfernManager { profile.id, process_id.unwrap_or_default() ), + wayfern_token.clone(), ); } @@ -4797,6 +4823,23 @@ mod tests { ); } + #[test] + fn a_denied_token_and_the_cap_it_sets_read_as_a_plan_refusal() { + use super::{browser_line_level, says_plan_refused}; + let denied = "[1:2:1119/1:INFO:wayfern_handler.cc:7] WayfernHandler::VerifyTokenForPlan: plan=free (expires in 120s)"; + let capped = "Wayfern instance limit reached: 4 browsers are already running on this plan."; + for line in [denied, capped] { + assert!(browser_line_level(line).is_some(), "{line}"); + assert!(says_plan_refused(line), "{line}"); + } + assert!(!says_plan_refused( + "[1:2:1119/1:INFO:wayfern_handler.cc:7] WayfernHandler::VerifyTokenForPlan: plan=pro (expires in 43200s)" + )); + assert!(!says_plan_refused( + "[1:2:1119/1:INFO:wayfern_handler.cc:7] Wayfern entitlement cache: using signed response (expires in 300s)" + )); + } + #[test] fn identity_location_carries_the_exit_for_create_identity() { let geo = crate::geolocation::Geolocation {