From 4e4cf80554530e34d31d75ba438d0a287651c6a7 Mon Sep 17 00:00:00 2001 From: innateessence Date: Sun, 15 Nov 2026 13:38:41 -0800 Subject: [PATCH 1/8] Add Google Drive as a cloud save provider --- docs/FAQ.md | 2 +- docs/GOOGLE-DRIVE.md | 100 ++++ docs/LAUNCHER-API.md | 4 + docs/TROUBLESHOOTING.md | 9 +- src-tauri/Cargo.lock | 1 + src-tauri/Cargo.toml | 1 + src-tauri/build.rs | 3 + src-tauri/src/cloud.rs | 327 ++++++++--- src-tauri/src/drive.rs | 1007 ++++++++++++++++++++++++++++++++ src-tauri/src/lib.rs | 4 +- src-tauri/src/save_provider.rs | 104 ++++ src-tauri/src/saves.rs | 153 ++++- src-tauri/src/secret.rs | 46 ++ src-tauri/src/win.rs | 21 +- tests/google-drive.test.cjs | 70 +++ ui/account.js | 118 +++- ui/tv.js | 15 +- 17 files changed, 1903 insertions(+), 82 deletions(-) create mode 100644 docs/GOOGLE-DRIVE.md create mode 100644 src-tauri/src/drive.rs create mode 100644 src-tauri/src/save_provider.rs create mode 100644 tests/google-drive.test.cjs diff --git a/docs/FAQ.md b/docs/FAQ.md index e87dffd7..aab215a4 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -22,7 +22,7 @@ No. The launcher is free and open source under the GPL v3, and so is every recom ## Do I need an account? -No. Everything works without one. A free account adds cloud saves, so the same save follows you between your PC, your TV PC and a handheld, and keeps your library in sync. +No. Everything works without one. A free RecompStore account adds cloud saves and keeps your library in sync. You can also connect your own Google Drive for game saves without a RecompStore account, in builds configured for Google sign-in. See [Google Drive saves](GOOGLE-DRIVE.md). ## Where does it keep my files? diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md new file mode 100644 index 00000000..f5225d86 --- /dev/null +++ b/docs/GOOGLE-DRIVE.md @@ -0,0 +1,100 @@ +# Google Drive saves + +Open **Settings → Account → Save destination → Connect Google Drive**. Choose your Google +account in the browser and approve access. Then choose **Use Google Drive** and enable cloud +saves on each game's **Saves** tab. A RecompStore account is not required for Drive saves. + +The launcher creates a visible **RecompLauncher/Saves** folder in My Drive. Copies are ZIP +archives using the same `rlsave.json` format as local backups. The launcher requests only +`drive.file`: access to files it creates or the user explicitly opens with it. It does not +request access to the rest of your Drive. Files and credentials travel directly to Google; +RecompLauncher servers do not receive them. + +Before play, the launcher checks for another PC's saves. After play it makes a local backup +and uploads changed saves. **Sync Now** checks immediately. Offline saves wait on this PC +and retry later, including after restarting the launcher. Connect the same Google account +on each PC and enable the same games there. + +When both PCs changed their saves, choose which to use. Simultaneous uploads are tracked by +snapshot ancestry, rather than assuming the PC with the later clock has the right save. +The other copies remain available in the Saves tab. The newest five ordinary cloud copies +are kept; unresolved branches retain their history until resolved. Removed old copies go +to Drive's Trash, which still uses Google storage until emptied. Local backups retain their +existing limit of ten copies per game. The upload limit remains 95 MiB per archive, along +with the existing save discovery and file limits. + +Switching providers or connecting a different Google account requires enabling games again. +Existing copies are not moved between providers. **Disconnect** stops this PC's Drive sync +and removes its Google credentials; local saves and remote copies remain. You can separately +remove RecompLauncher's access in your Google account's connected-app settings. Google's +revocation can disconnect other PCs too. + +Big Picture has the same connection, provider selection, per-game switch and sync controls. +It normally opens the browser on the same PC. Approved limited-input builds can offer a +Google device code and QR code for a phone. A phone cannot finish a desktop loopback callback. + +## Configuring a release build + +The project maintainer must configure one Google Cloud project, enable the Drive API, configure +Google Auth branding/audience/data access, and register a **Desktop app** OAuth client. Ordinary +players only connect their Google account; they do not create a Cloud project or paste credentials. + +Set these environment variables when building the launcher: + +```sh +export RL_GOOGLE_CLIENT_ID='your-desktop-client.apps.googleusercontent.com' +export RL_GOOGLE_CLIENT_SECRET='the-desktop-client-secret' +npm run build +``` + +These are installed-app client credentials, which are distributed with the binary and cannot +be treated as confidential. Keep development and production projects separate. Use the same +production Google project across platforms so the application can discover the same files. +The launcher embeds these build variables; changing them requires rebuilding. Without a desktop +client ID, desktop connection controls explain that this build has not configured Drive. + +Publish the OAuth application for external users and complete Google's applicable branding and +verification requirements before releasing it. In Google's Testing status, Drive refresh tokens +expire after seven days. Test denied consent, revoked access, and the production consent screen +before shipping. + +Only if the application qualifies for Google's TV/limited-input flow, register an additional +**TVs and Limited Input devices** client in that same project and set: + +```sh +export RL_GOOGLE_DEVICE_CLIENT_ID='your-approved-device-client.apps.googleusercontent.com' +export RL_GOOGLE_DEVICE_CLIENT_SECRET='the-device-client-secret' +``` + +Big Picture uses that client when configured and respects Google's polling interval and slow-down +responses. Without it, Big Picture uses the desktop browser flow. Do not register a desktop +application as a limited-input device merely to avoid browser sign-in. + +Google refresh tokens use a separate Windows Credential Manager entry. On Linux and macOS they +follow the launcher's existing convention: an atomically replaced file readable only by its owner +in the launcher data directory. Tokens and upload-session URLs are not sent to the UI or logged. +Native keychain integration on Linux/macOS is not included. Upload-session state stays in the +launcher data directory and is scoped to the Google account and game, even when the local backup +folder is on a synchronized drive. + +No `recomplauncher.json` changes are needed. Existing `saves` paths and managed-input exclusions +apply to Drive backups too. Downloads are checked against the archive manifest and individual +file hashes before restoration, and archive destinations must match this PC's known save folders +(or the folders the player explicitly picked). + +## Validation before a public release + +Run `cargo test --manifest-path src-tauri/Cargo.toml` and `node --test tests/*.test.cjs`. +With the production OAuth configuration, test two real installations on Windows and Linux/Steam +Deck: connect the same account, upload, restore, play offline and reconnect, interrupt an upload, +create simultaneous changes, resolve both choices, switch accounts, and disconnect. Also check +a full Drive, a manually damaged ZIP, expired/revoked authorization, and Big Picture controls. +Automated tests do not replace this live Google authorization and storage check. + +Google documentation: + +- [Desktop OAuth, PKCE and loopback redirects](https://developers.google.com/identity/protocols/oauth2/native-app) +- [Drive scopes](https://developers.google.com/workspace/drive/api/guides/api-specific-auth) +- [Resumable uploads](https://developers.google.com/workspace/drive/api/guides/manage-uploads) +- [Device authorization and supported scopes](https://developers.google.com/identity/protocols/oauth2/limited-input-device) +- [Refresh token expiration](https://developers.google.com/identity/protocols/oauth2#expiration) diff --git a/docs/LAUNCHER-API.md b/docs/LAUNCHER-API.md index 79873b61..f6897587 100644 --- a/docs/LAUNCHER-API.md +++ b/docs/LAUNCHER-API.md @@ -20,6 +20,10 @@ was signed out (from the account page, or the account is gone): the launcher for ## Cloud saves +This section describes RecompStore storage. Players can instead choose their own Google Drive +in Settings → Account; those saves go directly to Google and do not use the endpoints below. +See [Google Drive saves](GOOGLE-DRIVE.md) for connection, storage and release configuration. + | Call | | | --- | --- | | `GET ?a=me` | The account, and `saves: {used, quota}` | diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 66e099c2..e7423e85 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -82,7 +82,14 @@ It only needs the internet for the game list, updates, accounts and cloud saves. ## Cloud saves aren't syncing -Make sure you're signed in and cloud saves are on for that game in its **Saves** tab. If a sync fails, the launcher tries again by itself and shows when the next try is. +Check the selected provider in **Settings → Account → Save destination**, and make sure cloud saves +are on for that game in its **Saves** tab. If a sync fails, the launcher tries again by itself and +shows when the next try is. + +For Google Drive, reconnect there if Google access expired or was revoked. If Drive is full, +free space (including its Trash), then press **Sync Now**. Switching providers or Google accounts +requires enabling games again. A build that says Drive is not configured needs the maintainer's +Google OAuth configuration. See [Google Drive saves](GOOGLE-DRIVE.md). ## Resetting the launcher diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 28579ac4..238ef350 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4712,6 +4712,7 @@ dependencies = [ "flate2", "fs2", "futures-util", + "getrandom 0.2.17", "hex", "image", "lz4_flex", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 87fdd341..c1da9e94 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -31,6 +31,7 @@ aes = "0.8" lzxd = "0.2" hex = "0.4" base64 = "0.22" +getrandom = "0.2" zip = { version = "2", default-features = false, features = ["deflate", "bzip2", "zstd", "time"] } sevenz-rust = "0.6" # Plain copies of compressed game images (convert.rs): GameCube and Wii formats, CHD, CSO and ZSO. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 3ac87581..255ba4d0 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,4 +1,7 @@ fn main() { + for name in ["RL_GOOGLE_CLIENT_ID", "RL_GOOGLE_CLIENT_SECRET", "RL_GOOGLE_DEVICE_CLIENT_ID", "RL_GOOGLE_DEVICE_CLIENT_SECRET"] { + println!("cargo:rerun-if-env-changed={name}"); + } pack(); // Cross-building for Windows with MinGW: unrar's C++ is built without a C++ library, so // libstdc++ goes in statically (the program needs no MinGW DLLs), with the Windows libraries diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index 01698400..48d6ec56 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -159,6 +159,10 @@ fn still_signed_in_as(dir: &Path, a: &Account, id: &str) -> bool { same } +pub(crate) fn account_scope(dir: &Path) -> String { + account_uid(dir) +} + /// The website said this PC's token is no good any more (signed out from the website). fn forget(app: &AppHandle) { let st = app.state::(); @@ -225,6 +229,21 @@ fn is_full(e: &Error) -> bool { e.to_string().contains("cloud saves are full") } +fn using_drive(dir: &Path) -> bool { + crate::save_provider::current(dir) == crate::save_provider::Provider::GoogleDrive +} + +fn transport_drive_error() -> Error { + Error::Msg("Google Drive couldn't be reached. Your saves stay on this PC and will retry.".into()) +} + +pub(crate) fn reset_provider_status() { + PAUSED.store(false, std::sync::atomic::Ordering::Relaxed); + FULL_TOLD.store(false, std::sync::atomic::Ordering::Relaxed); + *FULL.lock().unwrap() = None; + *TRIES.lock().unwrap() = None; +} + /// A copy that didn't go up whole (cut off, too slow, "didn't arrive whole"): tried again after 1, /// 5, 15 and then 60 minutes, so at most a few tries an hour, whatever else asks for it. static TRIES: Mutex>> = Mutex::new(None); @@ -498,7 +517,7 @@ pub struct LinkStart { expires: u64, } -fn qr_svg(text: &str) -> String { +pub(crate) fn qr_svg(text: &str) -> String { qrcode::QrCode::new(text.as_bytes()) .map(|q| { q.render::() @@ -683,7 +702,7 @@ pub fn shown_root(st: &App) -> PathBuf { } /// One game's saves at the same time: two backups of one game never overlap. -static BUSY: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +pub(crate) static BUSY: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); /// Waits its turn for the saves, but not forever: something else that's stuck can't keep a /// backup spinning. @@ -710,9 +729,18 @@ pub struct CloudCopy { pub device: String, #[serde(default)] pub played: u64, + #[serde(default)] + pub conflict: bool, + #[serde(default)] + pub revision: String, + #[serde(default)] + pub head: bool, } async fn cloud_list(app: &AppHandle, id: &str) -> Res<(Vec, Value)> { + if using_drive(&app.state::().dir) { + return crate::drive::list(app, id).await; + } let v = get(app, &[("a", "saves"), ("game", id)]).await?; let list: Vec = serde_json::from_value(v.get("versions").cloned().unwrap_or(json!([]))).unwrap_or_default(); let mut list = list; @@ -723,7 +751,7 @@ async fn cloud_list(app: &AppHandle, id: &str) -> Res<(Vec, Value)> { Ok((list, json!({"used": v.get("used"), "quota": v.get("quota")}))) } -const SYNC_CONFLICT: &str = "Both save copies changed. Choose one in Saves → Sync Now."; +pub(crate) const SYNC_CONFLICT: &str = "Both save copies changed. Choose one in Saves → Sync Now."; /// Before Play, the cloud's newer save couldn't be put in place (a save folder that's read-only /// on this PC, say). Why goes on the line under it. @@ -839,19 +867,24 @@ async fn upload(app: &AppHandle, id: &str, name: &str) -> Res<()> { async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { let st = app.state::(); - // One account from the note to the request: a switch meanwhile must not send this note's - // copy with the next account's token. - let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; + if game(&st, id)?.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Err(Error::Msg("Turn on cloud saves for this game first.".into())); + } + let scope = crate::save_provider::scope(&st.dir); + let a = if using_drive(&st.dir) { None } else { Some(load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?) }; let mut state = saves::state(&st.dir, id); // Signed in to another account just now: this note isn't that account's to send (the log // says so). The copy stays on this PC and goes up with the new account's own sync. - if !still_signed_in_as(&st.dir, &a, id) { + if crate::save_provider::scope(&st.dir) != scope { return Ok(()); } let copy = saves::manifest(&copies_dir(&st, id).join(name)) .ok_or_else(|| Error::Msg("That copy is gone.".into()))?; let (list, _) = cloud_list(app, id).await?; - let Some(top) = list.first() else { return upload_copy(app, id, name, 0, &a).await }; + let Some(top) = list.first() else { return upload_copy(app, id, name, 0, None, a.as_ref()).await }; + if top.conflict { + return Err(Error::Msg(SYNC_CONFLICT.into())); + } if top.hash == copy.hash { state.mark_synced(©.hash, top.made, &top.device); if state.pending.as_deref() == Some(name) { @@ -865,13 +898,29 @@ async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { saves::set_state(&st.dir, id, &state); return Err(Error::Msg(SYNC_CONFLICT.into())); } - upload_copy(app, id, name, top.made.saturating_add(1), &a).await + upload_copy(app, id, name, top.made.saturating_add(1), None, a.as_ref()).await } -async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, a: &Account) -> Res<()> { +async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, resolution: Option<&str>, account: Option<&Account>) -> Res<()> { let st = app.state::(); let path = copies_dir(&st, id).join(name); let man = saves::manifest(&path).ok_or_else(|| Error::Msg("That copy is gone.".into()))?; + if using_drive(&st.dir) { + if !crate::net::forced() && copy_wait_left(id, name).is_some() { + return Err(Error::Net("Google Drive upload is waiting to retry.".into())); + } + if let Err(e) = crate::drive::upload(app, id, &path, resolution).await { + if matches!(e, Error::Net(_)) { copy_failed(id, name, "Google Drive unavailable"); } + return Err(e); + } + copy_went_up(id, name); + let mut state = saves::state(&st.dir, id); + state.synced_hash = man.hash; + state.pending = None; + saves::set_state(&st.dir, id, &state); + return Ok(()); + } + let a = account.cloned().or_else(|| load(&st.dir)).ok_or_else(|| Error::Msg("Sign in first.".into()))?; if paused() { return Err(Error::Msg(PAUSED_TEXT.into())); } @@ -994,7 +1043,8 @@ fn pending_ids(st: &App) -> Vec { pub async fn upload_pending(app: &AppHandle) { let st = app.state::(); let forced = crate::net::forced(); - if !signed_in(&st.dir) || (!forced && (crate::net::resting(&save_url("save-put"), false) || full_now())) || paused() { + let website = !using_drive(&st.dir); + if !crate::save_provider::ready(&st.dir) || (website && ((!forced && (crate::net::resting(&save_url("save-put"), false) || full_now())) || paused())) { return; } let ids = pending_ids(&st); @@ -1010,11 +1060,11 @@ pub async fn upload_pending(app: &AppHandle) { match upload(app, &id, &name).await { Ok(()) => {} // Paused on the site: the rest wait for the next start. - Err(_) if paused() => break, + Err(_) if !using_drive(&st.dir) && paused() => break, // Full: none of them go until there's room. Err(e) if is_full(&e) => break, // The site isn't answering for saves at all: the rest wait, and go when it does. - Err(Error::Net(_)) if crate::net::resting(&save_url("save-put"), false) => { + Err(Error::Net(_)) if using_drive(&st.dir) || crate::net::resting(&save_url("save-put"), false) => { no_answer = true; break; } @@ -1049,11 +1099,12 @@ fn retry_pending_later(app: &AppHandle) { let app = app.clone(); tauri::async_runtime::spawn(async move { // The site's own rest, or the soonest a copy that failed may be tried again. - let wait = crate::net::wait_left(&save_url("save-put")).max(next_copy_try().unwrap_or((30u64 << n).min(3600))); + let url = if using_drive(&app.state::().dir) { "https://www.googleapis.com/drive/v3/files".into() } else { save_url("save-put") }; + let wait = crate::net::wait_left(&url).max(next_copy_try().unwrap_or((30u64 << n).min(3600))); crate::trail::note(format!("Cloud saves: waiting uploads tried again in {wait}s")); tokio::time::sleep(crate::net::spread(wait, 0.3)).await; RETRY_PLANNED.store(false, std::sync::atomic::Ordering::SeqCst); - if paused() { + if !using_drive(&app.state::().dir) && paused() { return; } Box::pin(upload_pending(&app)).await; @@ -1071,7 +1122,7 @@ pub async fn after_session(app: &AppHandle, id: &str) -> Res let (dir, id2, g2) = (st.dir.clone(), id.to_string(), g.clone()); // The copy ends the session's wait (saves::backup); one that fails to go up is kept as pending. let copy = blocking(move || saves::backup(&dir, &id2, &spots, &g2)).await??; - if g.cloud == Some(true) && signed_in(&st.dir) { + if g.cloud == Some(true) && crate::save_provider::ready(&st.dir) { if let Some(l) = newest_unsent(&st.dir, id, &g) { if let Err(e) = upload(app, id, &l.name).await { let too_big = e.to_string().starts_with("This save is too big"); @@ -1167,21 +1218,26 @@ fn open_sessions(saves_dir: &Path) -> Vec { /// this cloud save themselves, over whatever is there. async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&str>) -> Res { let st = app.state::(); - let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; + let scope = crate::save_provider::scope(&st.dir); let _working = working(app, id, "down"); - let url = api(); - let req = st - .http - .get(&url) - .query(&[("a", "save-get"), ("game", id), ("v", &c.v)]) - .bearer_auth(&a.token).header("X-RL-Token", a.token.as_str()) - .timeout(std::time::Duration::from_secs(300)); - let r = crate::net::send(req, &save_url("save-get"), true).await?; - if r.status().as_u16() != 200 { - answer(app, r).await?; - return Err(Error::Msg("That cloud save couldn't be downloaded.".into())); - } - let bytes = r.bytes().await.map_err(net)?; + let bytes = if using_drive(&st.dir) { + crate::drive::download(app, id, c).await? + } else { + let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; + let url = api(); + let req = st + .http + .get(&url) + .query(&[("a", "save-get"), ("game", id), ("v", &c.v)]) + .bearer_auth(&a.token).header("X-RL-Token", a.token.as_str()) + .timeout(std::time::Duration::from_secs(300)); + let r = crate::net::send(req, &save_url("save-get"), true).await?; + if r.status().as_u16() != 200 { + answer(app, r).await?; + return Err(Error::Msg("That cloud save couldn't be downloaded.".into())); + } + r.bytes().await.map_err(net)?.to_vec() + }; let g = game(&st, id)?; // Checked after the download too: a big save takes a while, and the game can be opened // from its folder meanwhile. @@ -1196,15 +1252,20 @@ async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&s let spots = spots_of(&st, id, &g); let (dir, id2, t2) = (st.dir.clone(), id.to_string(), tmp.clone()); let checked = checked.map(String::from); - let n = blocking(move || match checked { - Some(h) => saves::restore_if_unchanged(&dir, &id2, &t2, &spots, &g, &h), - None => saves::restore(&dir, &id2, &t2, &spots, &g), + let hash = c.hash.clone(); + let drive = using_drive(&st.dir); + let n = blocking(move || { + if drive { saves::validate_cloud_copy(&t2, &id2, &hash, &spots)?; } + match checked { + Some(h) => saves::restore_if_unchanged(&dir, &id2, &t2, &spots, &g, &h), + None => saves::restore(&dir, &id2, &t2, &spots, &g), + } }).await; let _ = tokio::fs::remove_file(&tmp).await; let n = n??; let mut s = saves::state(&st.dir, id); // The save is in place either way; only the new account's notes must not claim it as synced. - if !still_signed_in_as(&st.dir, &a, id) { + if crate::save_provider::scope(&st.dir) != scope { s.last_hash = c.hash.clone(); saves::set_state(&st.dir, id, &s); return Ok(n); @@ -1230,6 +1291,12 @@ fn incoming<'a>(s: &saves::State, list: &'a [CloudCopy]) -> Option<&'a CloudCopy should_restore(&s.last_hash, &s.synced_hash, &top.hash, false).then_some(top) } +fn current_copy<'a>(list: &'a [CloudCopy], local: &str) -> Option<&'a CloudCopy> { + let top = list.first()?; + if !top.conflict { return Some(top); } + list.iter().find(|c| c.head && c.hash != local).or(Some(top)) +} + /// Whether the cloud copy can be put in place without replacing locally changed saves. fn should_restore(local: &str, synced: &str, cloud: &str, empty: bool) -> bool { if cloud == local { @@ -1264,7 +1331,7 @@ fn reserve_sync(st: &App, id: &str) -> Res { } /// Upload the checked live save, even if a different save is still in the backup history. -async fn upload_current(app: &AppHandle, id: &str, g: Installed, spots: Vec, hash: String, after: u64) -> Res<()> { +async fn upload_current(app: &AppHandle, id: &str, g: Installed, spots: Vec, hash: String, after: u64, resolution: Option<&str>) -> Res<()> { let dir = app.state::().dir.clone(); let id2 = id.to_string(); let copy = blocking(move || { @@ -1273,8 +1340,9 @@ async fn upload_current(app: &AppHandle, id: &str, g: Installed, spots: Vec().dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; - let r = upload_copy(app, id, ©.name, after.saturating_add(1), &a).await; + let st = app.state::(); + let a = if using_drive(&st.dir) { None } else { Some(load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?) }; + let r = upload_copy(app, id, ©.name, after.saturating_add(1), resolution, a.as_ref()).await; if let Err(e) = &r { note_failure(&app.state::().dir, id, e); } @@ -1305,16 +1373,28 @@ pub async fn saves_check(app: AppHandle, id: String, manual: Option) -> Re check_saves(app, id, false).await } +async fn prepare_sync(st: &App, id: &str) -> Res, Installed)>> { + let g = game(st, id)?; + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Ok(None); + } + let guard = busy().await?; + // Consent or the connected account may have changed while another save operation finished. + let g = game(st, id)?; + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Ok(None); + } + Ok(Some((guard, g))) +} + async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { let st = app.state::(); - let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) { + let Some((_busy, g)) = prepare_sync(&st, &id).await? else { if manual { return Err(Error::Msg("Turn on cloud saves for this game first.".into())); } return Ok(json!({"action": "play"})); - } - let _busy = busy().await?; + }; let _reserved = reserve_sync(&st, &id)?; let _working = working(&app, &id, "check"); let (list, _) = match cloud_list(&app, &id).await { @@ -1355,14 +1435,14 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { } note_folder_too_big(&st.dir, &id, None); let s = saves::state(&st.dir, &id); - let Some(top) = top else { + let Some(top) = current_copy(&list, &local) else { if local.is_empty() { return Ok(json!({"action": "play"})); } - upload_current(&app, &id, g, spots, local, 0).await?; + upload_current(&app, &id, g, spots, local, 0, None).await?; return Ok(json!({"action": "uploaded"})); }; - if top.hash == local { + if !top.conflict && top.hash == local { // Already the same: a conflict or a problem noted before is over too. let stale = s.synced_hash != local || s.pending.is_some() || s.conflict.is_some() || s.problem.is_some(); if stale { @@ -1373,7 +1453,7 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { } return Ok(json!({"action": "play"})); } - if should_restore(&local, &s.synced_hash, &top.hash, entries.is_empty()) { + if !top.conflict && should_restore(&local, &s.synced_hash, &top.hash, entries.is_empty()) { // Before Play it doesn't stop the game: the program may be a mod tool, not the game. The // player is asked whether to play with this PC's save, as when a restore fails. if let Some(program) = open_outside(&id, &g).await? { @@ -1394,9 +1474,9 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { let n = taken?; return Ok(json!({"action": "restored", "files": n, "cloud": top})); } - if top.hash == s.synced_hash { + if !top.conflict && top.hash == s.synced_hash { if manual { - upload_current(&app, &id, g, spots, local, top.made).await?; + upload_current(&app, &id, g, spots, local, top.made, None).await?; return Ok(json!({"action": "uploaded"})); } // After Play, the local changes go up at the end of the session. @@ -1460,18 +1540,23 @@ pub async fn sync_quiet(app: &AppHandle, id: &str) -> Res<()> { /// The player's pick after a conflict: keep this PC's save (it goes up as the newest), or the /// cloud's (this PC's is kept as a local copy first). #[tauri::command] -pub async fn saves_pick(app: AppHandle, id: String, keep: String, local_hash: String, cloud_version: String) -> Res<()> { +pub async fn saves_pick(app: AppHandle, id: String, keep: String, local_hash: String, cloud_version: String, cloud_revision: Option) -> Res<()> { let _busy = busy().await?; let st = app.state::(); let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) { + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { return Err(Error::Msg("Turn on cloud saves for this game first.".into())); } let _reserved = reserve_sync(&st, &id)?; crate::net::now(async { let changed = || Error::Msg("The saves changed. Try syncing again.".into()); let (list, _) = cloud_list(&app, &id).await?; - let top = list.first().filter(|c| c.v == cloud_version).ok_or_else(changed)?; + let top = if using_drive(&st.dir) { + list.iter().find(|c| c.v == cloud_version && c.head) + } else { + list.first().filter(|c| c.v == cloud_version) + }.ok_or_else(changed)?; + if using_drive(&st.dir) && cloud_revision.as_deref() != Some(top.revision.as_str()) { return Err(changed()); } let spots = spots_of(&st, &id, &g); let (g2, spots2) = (g.clone(), spots.clone()); let (entries, infos, hash, _) = blocking(move || saves::current(&spots2, &g2)).await?; @@ -1479,8 +1564,14 @@ pub async fn saves_pick(app: AppHandle, id: String, keep: String, local_hash: St return Err(changed()); } match keep.as_str() { - "cloud" => take_cloud(&app, &id, top, Some(&hash)).await.map(|_| ()), - "local" => upload_current(&app, &id, g, spots, hash, top.made).await, + "cloud" => { + take_cloud(&app, &id, top, Some(&hash)).await?; + if using_drive(&st.dir) && top.conflict { + return upload_current(&app, &id, g, spots, top.hash.clone(), top.made, Some(&top.revision)).await; + } + Ok(()) + } + "local" => upload_current(&app, &id, g, spots, hash, top.made, Some(&top.revision)).await, _ => Err(Error::Msg("Choose this PC or the cloud.".into())), } }).await @@ -1506,6 +1597,7 @@ fn follow_every_game(l: &mut crate::library::Library) { /// already has something newer, which the next Play sorts out). #[tauri::command] pub async fn saves_cloud(app: AppHandle, id: String, on: bool) -> Res { + let _busy = busy().await?; let st = app.state::(); let g = { let mut l = st.lib.lock().unwrap(); @@ -1515,12 +1607,18 @@ pub async fn saves_cloud(app: AppHandle, id: String, on: bool) -> Res let _ = l.save(&st.dir); g }; - if on && signed_in(&st.dir) { + if on && crate::save_provider::ready(&st.dir) { let app2 = app.clone(); let id2 = id.clone(); tauri::async_runtime::spawn(async move { - let has_cloud = cloud_list(&app2, &id2).await.map(|(l, _)| !l.is_empty()).unwrap_or(true); + let has_cloud = { + let _busy = BUSY.lock().await; + let st = app2.state::(); + if !crate::save_provider::ready(&st.dir) || game(&st, &id2).map(|g| g.cloud != Some(true)).unwrap_or(true) { return; } + cloud_list(&app2, &id2).await.map(|(l, _)| !l.is_empty()).unwrap_or(true) + }; if !has_cloud { + // after_session takes BUSY itself, and rechecks consent before uploading. let _ = after_session(&app2, &id2).await; let _ = app2.emit("saves", json!({"id": id2})); } @@ -1540,6 +1638,7 @@ pub struct SpotInfo { /// Everything the Saves tab shows. #[tauri::command] pub async fn saves_info(app: AppHandle, id: String) -> Res { + let _busy = busy().await?; let st = app.state::(); let g = game(&st, &id)?; let spots: Vec = spots_of(&st, &id, &g) @@ -1557,7 +1656,8 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res { let mut space = Value::Null; let mut offline = false; let mut next = Value::Null; - if g.cloud == Some(true) && signed_in(&st.dir) { + let mut cloud_error = String::new(); + if g.cloud == Some(true) && crate::save_provider::ready(&st.dir) { match cloud_list(&app, &id).await { Ok((l, sp)) => { next = incoming(&state, &l).map(|c| json!(c)).unwrap_or(Value::Null); @@ -1566,15 +1666,17 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res { cloud = serde_json::to_value(l).unwrap_or(Value::Null); space = sp; } - Err(Error::Net(_)) => offline = true, - Err(_) => {} + Err(e) => { + offline = matches!(e, Error::Net(_)); + cloud_error = e.to_string(); + } } } let waiting = waiting_copies(&local, &state); Ok(json!({ - "spots": spots, "local": local, "cloud": cloud, "space": space, "offline": offline, - "cloudOn": g.cloud, "signedIn": signed_in(&st.dir), "synced": state.synced_hash, "pending": state.pending.is_some(), - "waiting": waiting, "status": STATUS_PAGE, + "spots": spots, "local": local, "cloud": cloud, "space": space, "offline": offline, "cloudError": cloud_error, + "provider": crate::save_provider::name(&st.dir), "cloudOn": g.cloud, "signedIn": crate::save_provider::ready(&st.dir), "synced": state.synced_hash, "pending": state.pending.is_some(), + "waiting": waiting, "status": if using_drive(&st.dir) { "" } else { STATUS_PAGE }, // The save in the game's folder now (the last copy made or put back), and this PC's name: // the tab marks the copy that's current and the ones another PC made. "current": state.last_hash, "here": saves::device_name(), @@ -1582,7 +1684,7 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res { "incoming": next, // Seconds until a copy that didn't get through is tried again, and whether the account's // cloud saves are full (no uploads until there's room). - "retryIn": state.pending.as_deref().and_then(|p| copy_wait_left(&id, p)), "full": full_now(), + "retryIn": state.pending.as_deref().and_then(|p| copy_wait_left(&id, p)), "full": !using_drive(&st.dir) && full_now(), "override": swap, })) } @@ -1717,13 +1819,17 @@ pub async fn saves_upload_now(app: AppHandle, id: String) -> Res { let st = app.state::(); folder_free(&st, &id)?; let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) { + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { return Err(Error::Msg("Turn on cloud saves for this game first.".into())); } let running = st.running.lock().unwrap().contains_key(&id); let r: Res<()> = crate::net::now(async { { let _busy = busy().await?; + let g = game(&st, &id)?; + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) { + return Err(Error::Msg("Turn on cloud saves for this game first.".into())); + } // A fresh copy of what's there now (a running game's saves wait until it closes). if !running { let spots = spots_of(&st, &id, &g); @@ -1753,6 +1859,7 @@ pub async fn saves_upload_now(app: AppHandle, id: String) -> Res { } match r { Ok(()) => crate::net::now(saves_info(app.clone(), id)).await, + Err(Error::Net(_)) if using_drive(&st.dir) => Err(transport_drive_error()), Err(Error::Net(_)) => Err(Error::Msg(format!("The website still can't be reached. Your saves are safe on this PC and go up when it's back. See {STATUS_PAGE} for whether it's on our side."))), Err(e) => Err(e), } @@ -1763,14 +1870,12 @@ pub async fn saves_upload_now(app: AppHandle, id: String) -> Res { #[tauri::command] pub async fn cloud_retry(app: AppHandle, id: Option) -> Res { let st = app.state::(); - if !signed_in(&st.dir) { + if !crate::save_provider::ready(&st.dir) { return Err(Error::Msg("Sign in first.".into())); } let r = crate::net::now(async { - let v = get(&app, &[("a", "me")]).await; - if let Err(Error::Net(e)) = v { - return Err(Error::Net(e)); - } + let v = if using_drive(&st.dir) { crate::drive::space(&app).await } else { get(&app, &[("a", "me")]).await }; + v?; upload_pending(&app).await; Ok(()) }) @@ -1780,6 +1885,7 @@ pub async fn cloud_retry(app: AppHandle, id: Option) -> Res { Some(id) => crate::net::now(saves_info(app.clone(), id)).await, None => Ok(json!({"ok": true})), }, + Err(e) if using_drive(&st.dir) => Err(e), Err(_) => Err(Error::Msg(format!("The website still can't be reached. Your saves are safe on this PC and go up when it's back. See {STATUS_PAGE} for whether it's on our side."))), } } @@ -1799,7 +1905,7 @@ fn overview(app: &AppHandle) -> Value { // Copies made beside the games while the player's folder was away go to it now that it's back. let installed: Vec = games.iter().map(|(_, g)| g.clone()).collect(); saves::gather(&st.dir, &installed); - let signed = signed_in(&st.dir); + let signed = crate::save_provider::ready(&st.dir); let mut out = Vec::new(); for (id, g) in games { let local = saves::list(&st.dir, &id, &g); @@ -1912,6 +2018,7 @@ pub async fn saves_restore(app: AppHandle, id: String, name: Option, v: } folder_free(&st, &id)?; let _busy = BUSY.lock().await; + let _reserved = reserve_sync(&st, &id)?; if let Some(v) = v { let (list, _) = cloud_list(&app, &id).await?; let c = list.into_iter().find(|c| c.v == v).ok_or_else(|| Error::Msg("That cloud save is gone.".into()))?; @@ -2307,6 +2414,66 @@ mod child_retry_tests { assert!(folder_free(st, "series--first").is_ok()); } + #[tokio::test] + async fn local_only_games_do_not_wait_for_another_save_operation() { + let fixture = Fixture::new(games()); + fixture.0.lib.lock().unwrap().installed.get_mut("series").unwrap().cloud = Some(false); + let _busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(matches!(futures_util::poll!(&mut check), std::task::Poll::Ready(Ok(None)))); + } + + #[tokio::test] + async fn games_without_cloud_consent_do_not_wait_for_another_save_operation() { + let fixture = Fixture::new(games()); + fixture.0.lib.lock().unwrap().installed.get_mut("series").unwrap().cloud = None; + let _busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(matches!(futures_util::poll!(&mut check), std::task::Poll::Ready(Ok(None)))); + } + + #[tokio::test] + async fn games_without_a_connected_provider_do_not_wait_for_another_save_operation() { + let fixture = Fixture::new(games()); + std::fs::write(fixture.0.dir.join("save-provider.json"), b"\"disabled\"").unwrap(); + let _busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(matches!(futures_util::poll!(&mut check), std::task::Poll::Ready(Ok(None)))); + } + + #[cfg(not(windows))] + #[tokio::test] + async fn a_waiting_sync_rechecks_cloud_consent() { + let fixture = Fixture::new(games()); + let account = Account { token: "test-token".into(), ..Default::default() }; + store(&fixture.0.dir, Some(&account)); + let busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(futures_util::poll!(&mut check).is_pending()); + fixture.0.lib.lock().unwrap().installed.get_mut("series").unwrap().cloud = Some(false); + drop(busy); + assert!(check.await.unwrap().is_none()); + } + + #[cfg(not(windows))] + #[tokio::test] + async fn a_waiting_sync_rechecks_the_connected_provider() { + let fixture = Fixture::new(games()); + let account = Account { token: "test-token".into(), ..Default::default() }; + store(&fixture.0.dir, Some(&account)); + let busy = BUSY.lock().await; + let check = prepare_sync(&fixture.0, "series"); + tokio::pin!(check); + assert!(futures_util::poll!(&mut check).is_pending()); + std::fs::write(fixture.0.dir.join("save-provider.json"), b"\"disabled\"").unwrap(); + drop(busy); + assert!(check.await.unwrap().is_none()); + } + #[tokio::test] async fn retries_find_each_games_queued_save_under_its_full_id() { let fixture = Fixture::new(games()); @@ -2911,3 +3078,27 @@ mod home_tests { assert!(!home_ok(&json!({"v": 1, "error": "Try again in a moment."}))); } } + +#[cfg(test)] +mod provider_conflict_tests { + use super::*; + + #[test] + fn a_drive_conflict_offers_the_other_devices_save() { + let list = vec![ + CloudCopy { v: "pc".into(), hash: "pc-save".into(), head: true, conflict: true, ..Default::default() }, + CloudCopy { v: "deck".into(), hash: "deck-save".into(), head: true, conflict: true, ..Default::default() }, + ]; + assert_eq!(current_copy(&list, "pc-save").unwrap().v, "deck"); + } + + #[test] + fn old_history_is_not_offered_as_an_unresolved_branch() { + let list = vec![ + CloudCopy { v: "pc".into(), hash: "pc-save".into(), head: true, conflict: true, ..Default::default() }, + CloudCopy { v: "old".into(), hash: "old-save".into(), head: false, conflict: true, ..Default::default() }, + CloudCopy { v: "deck".into(), hash: "deck-save".into(), head: true, conflict: true, ..Default::default() }, + ]; + assert_eq!(current_copy(&list, "pc-save").unwrap().v, "deck"); + } +} diff --git a/src-tauri/src/drive.rs b/src-tauri/src/drive.rs new file mode 100644 index 00000000..21d63e49 --- /dev/null +++ b/src-tauri/src/drive.rs @@ -0,0 +1,1007 @@ +//! Direct Google Drive storage. Immutable snapshots retain their parents so simultaneous uploads +//! remain visible as conflicts, even when the PCs disagree about the time. + +use crate::{cloud, save_provider, saves, App, Error}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Mutex, OnceLock, +}; +use std::time::{Duration, Instant}; +use tauri::{AppHandle, Manager}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +type Res = Result; +const API: &str = "https://www.googleapis.com/drive/v3"; +const TOKEN: &str = "https://oauth2.googleapis.com/token"; +const SCOPE: &str = "https://www.googleapis.com/auth/drive.file"; +pub const MAX_ARCHIVE: usize = 95 * 1024 * 1024; +const CREDENTIAL: &str = "google-drive"; +static NEEDS_RECONNECT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +const RECONNECT: &str = "Google Drive needs you to connect again in Settings → Account."; +static GENERATION: AtomicU64 = AtomicU64::new(0); +static CONNECT: Mutex> = Mutex::new(None); +static ACCESS: tokio::sync::Mutex> = tokio::sync::Mutex::const_new(None); + +#[derive(Clone, Serialize, Deserialize)] +struct Account { + id: String, + email: String, + refresh: String, + client_id: String, + client_secret: String, +} + +struct Access { + account: String, + token: String, + until: Instant, +} + +struct Connection { + generation: u64, + task: Option, + result: Value, +} + +fn client() -> &'static reqwest::Client { + static CLIENT: OnceLock = OnceLock::new(); + CLIENT.get_or_init(|| { + reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(300)) + .build() + .expect("Google HTTP client") + }) +} + +fn load(dir: &Path) -> Option { + serde_json::from_slice(&crate::secret::load_named(dir, CREDENTIAL)?).ok() +} + +fn store(dir: &Path, account: &Account) -> Res<()> { + crate::secret::save_named( + dir, + CREDENTIAL, + &serde_json::to_vec(account).map_err(|_| Error::Msg("Couldn't save the Google sign-in.".into()))?, + )?; + Ok(()) +} + +pub fn identity(dir: &Path) -> String { + load(dir).map(|a| a.id).unwrap_or_default() +} + +pub fn connected(dir: &Path) -> bool { + load(dir).is_some() +} + +fn desktop_credentials() -> (&'static str, &'static str) { + (option_env!("RL_GOOGLE_CLIENT_ID").unwrap_or(""), option_env!("RL_GOOGLE_CLIENT_SECRET").unwrap_or("")) +} + +fn device_credentials() -> (&'static str, &'static str) { + (option_env!("RL_GOOGLE_DEVICE_CLIENT_ID").unwrap_or(""), option_env!("RL_GOOGLE_DEVICE_CLIENT_SECRET").unwrap_or("")) +} + +pub fn state(dir: &Path) -> Value { + let a = load(dir); + json!({"connected": a.is_some(), "email": a.map(|a| a.email), "configured": !desktop_credentials().0.is_empty(), "deviceConfigured": !device_credentials().0.is_empty(), "needsReconnect": NEEDS_RECONNECT.load(Ordering::Relaxed)}) +} + +fn transport(_: reqwest::Error) -> Error { + // Upload session URLs and OAuth responses may contain credentials. Never put them in logs. + Error::Net("Google Drive couldn't be reached. Your saves stay on this PC and will retry.".into()) +} + +async fn token_form(form: &[(&str, &str)]) -> Res { + let r = client().post(TOKEN).form(form).timeout(Duration::from_secs(20)).send().await.map_err(transport)?; + let status = r.status().as_u16(); + let value: Value = r.json().await.map_err(transport)?; + if status == 429 || status >= 500 { + return Err(Error::Net("Google sign-in is busy. Try again later.".into())); + } + if status >= 400 || value.get("error").is_some() { + return Err(Error::Msg(RECONNECT.into())); + } + Ok(value) +} + +async fn access(app: &AppHandle, force: bool) -> Res { + let mut cached = ACCESS.lock().await; + let st = app.state::(); + let mut a = load(&st.dir).ok_or_else(|| Error::Msg(RECONNECT.into()))?; + if !force { + if let Some(c) = cached.as_ref().filter(|c| c.account == a.id && c.until > Instant::now()) { + return Ok(c.token.clone()); + } + } + let refreshed = token_form(&[ + ("client_id", &a.client_id), + ("client_secret", &a.client_secret), + ("refresh_token", &a.refresh), + ("grant_type", "refresh_token"), + ]) + .await; + if matches!(&refreshed, Err(Error::Msg(message)) if message == RECONNECT) { + NEEDS_RECONNECT.store(true, Ordering::Relaxed); + } + let v = refreshed?; + NEEDS_RECONNECT.store(false, Ordering::Relaxed); + let token = v["access_token"].as_str().filter(|s| !s.is_empty()).ok_or_else(|| Error::Msg(RECONNECT.into()))?.to_string(); + if let Some(refresh) = v["refresh_token"].as_str().filter(|s| !s.is_empty()) { + a.refresh = refresh.to_string(); + store(&st.dir, &a)?; + } + let seconds = v["expires_in"].as_u64().unwrap_or(3600).saturating_sub(60).min(3600); + *cached = Some(Access { account: a.id, token: token.clone(), until: Instant::now() + Duration::from_secs(seconds) }); + Ok(token) +} + +fn api_error(status: u16, body: &Value) -> Error { + let reason = body.pointer("/error/errors/0/reason").and_then(Value::as_str).unwrap_or(""); + if reason == "storageQuotaExceeded" { + return Error::Msg("Google Drive storage is full. Free space in Drive, then press Sync Now. Your saves stay on this PC.".into()); + } + if status == 401 { + return Error::Msg(RECONNECT.into()); + } + if status == 429 || status >= 500 || matches!(reason, "rateLimitExceeded" | "userRateLimitExceeded") { + return Error::Net("Google Drive is busy. Your saves stay on this PC and will retry.".into()); + } + Error::Msg(format!("Google Drive refused the request ({status}). Check its connection in Settings → Account.")) +} + +async fn send(app: &AppHandle, request: reqwest::RequestBuilder) -> Res { + let url = request + .try_clone() + .ok_or_else(|| Error::Msg("Couldn't prepare the Drive request.".into()))? + .build() + .map_err(transport)? + .url() + .to_string(); + let token = access(app, false).await?; + let retry = request.try_clone(); + let mut r = crate::net::send(request.bearer_auth(token), &url, true).await.map_err(|_| transport_error())?; + if r.status().as_u16() == 401 { + let token = access(app, true).await?; + let request = retry.ok_or_else(|| Error::Msg(RECONNECT.into()))?; + r = request.bearer_auth(token).send().await.map_err(transport)?; + } + let status = r.status().as_u16(); + if status < 400 { + return Ok(r); + } + let body = r.json().await.unwrap_or(Value::Null); + Err(api_error(status, &body)) +} + +fn transport_error() -> Error { + Error::Net("Google Drive couldn't be reached. Your saves stay on this PC and will retry.".into()) +} + +async fn json_response(r: reqwest::Response) -> Res { + r.json().await.map_err(transport) +} + +async fn about_token(token: &str) -> Res { + let r = client() + .get(format!("{API}/about")) + .query(&[("fields", "user(permissionId,emailAddress),storageQuota")]) + .bearer_auth(token) + .send() + .await + .map_err(transport)?; + let status = r.status().as_u16(); + let v = r.json().await.map_err(transport)?; + if status >= 400 { + return Err(api_error(status, &v)); + } + Ok(v) +} + +pub async fn space(app: &AppHandle) -> Res { + let request = client().get(format!("{API}/about")).query(&[("fields", "storageQuota")]).timeout(Duration::from_secs(20)); + let v = json_response(send(app, request).await?).await?; + let number = |key: &str| v.pointer(key).and_then(Value::as_str).and_then(|s| s.parse::().ok()); + Ok(json!({"used": number("/storageQuota/usage"), "quota": number("/storageQuota/limit")})) +} + +fn random_text() -> Res { + let mut bytes = [0u8; 32]; + getrandom::getrandom(&mut bytes).map_err(|_| Error::Msg("Couldn't start Google sign-in securely.".into()))?; + Ok(URL_SAFE_NO_PAD.encode(bytes)) +} + +fn callback(request: &str, state: &str) -> Res> { + let target = request.lines().next().and_then(|line| line.strip_prefix("GET ")).and_then(|line| line.strip_suffix(" HTTP/1.1")); + let Some(target) = target else { return Ok(None) }; + let url = reqwest::Url::parse(&format!("http://127.0.0.1{target}")).map_err(|_| Error::Msg("Invalid Google callback.".into()))?; + if url.path() != "/oauth2callback" { + return Ok(None); + } + let pairs: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); + if pairs.get("state").map(String::as_str) != Some(state) { + return Ok(None); + } + if pairs.contains_key("error") { + return Err(Error::Msg("Google Drive connection was declined.".into())); + } + Ok(pairs.get("code").filter(|c| !c.is_empty()).cloned()) +} + +async fn browser_code(listener: tokio::net::TcpListener, state: String) -> Res { + loop { + let (mut stream, _) = listener.accept().await?; + let request = tokio::time::timeout(Duration::from_secs(5), async { + let mut bytes = Vec::new(); + let mut buffer = [0u8; 1024]; + while bytes.len() < 8192 { + let n = stream.read(&mut buffer).await?; + if n == 0 { + break; + } + bytes.extend_from_slice(&buffer[..n]); + if bytes.windows(4).any(|s| s == b"\r\n\r\n") { + break; + } + } + Ok::<_, std::io::Error>(String::from_utf8_lossy(&bytes).to_string()) + }) + .await; + let Ok(Ok(request)) = request else { continue }; + let result = callback(&request, &state); + let accepted = !matches!(&result, Ok(None)); + let body = if accepted { + "Return to RecompLauncher to finish connecting Google Drive. You can close this page." + } else { + "This isn't the Google sign-in this launcher is waiting for." + }; + let status = if accepted { "200 OK" } else { "400 Bad Request" }; + let response = format!( + "HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = tokio::time::timeout(Duration::from_secs(2), stream.write_all(response.as_bytes())).await; + if let Some(code) = result? { + return Ok(code); + } + } +} + +async fn finish(app: &AppHandle, generation: u64, tokens: Value, client_id: String, client_secret: String) -> Res<()> { + let token = tokens["access_token"].as_str().ok_or_else(|| Error::Msg("Google didn't return a sign-in token.".into()))?; + let refresh = tokens["refresh_token"] + .as_str() + .filter(|s| !s.is_empty()) + .ok_or_else(|| Error::Msg("Google didn't grant offline access. Connect again and approve access to Drive.".into()))?; + let about = about_token(token).await?; + let id = about + .pointer("/user/permissionId") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .ok_or_else(|| Error::Msg("Google didn't identify the connected account.".into()))?; + let email = about.pointer("/user/emailAddress").and_then(Value::as_str).unwrap_or("Google Drive"); + let _busy = cloud::BUSY.lock().await; + let st = app.state::(); + save_provider::ensure_idle(&st)?; + *ACCESS.lock().await = None; + let connection = CONNECT.lock().unwrap(); + if connection.as_ref().map(|c| c.generation) != Some(generation) { + return Err(Error::Msg("Google sign-in was cancelled.".into())); + } + if identity(&st.dir) != id && save_provider::current(&st.dir) == save_provider::Provider::GoogleDrive { + save_provider::clear_consent(&st)?; + } + store(&st.dir, &Account { id: id.into(), email: email.into(), refresh: refresh.into(), client_id, client_secret })?; + NEEDS_RECONNECT.store(false, Ordering::Relaxed); + Ok(()) +} + +fn launch_connection( + app: AppHandle, + generation: u64, + future: impl std::future::Future> + Send + 'static, +) { + let task = tauri::async_runtime::spawn(async move { + let result = match tokio::time::timeout(Duration::from_secs(600), future).await { + Ok(Ok((tokens, id, secret))) => finish(&app, generation, tokens, id, secret).await, + Ok(Err(e)) => Err(e), + Err(_) => Err(Error::Msg("Google sign-in expired. Try connecting again.".into())), + }; + { + let mut current = CONNECT.lock().unwrap(); + if let Some(c) = current.as_mut().filter(|c| c.generation == generation) { + c.result = match result { + Ok(()) => json!({"status": "ok"}), + Err(e) => json!({"status": "error", "error": e.to_string()}), + }; + c.task = None; + } + } + save_provider::emit(&app); + cloud::upload_pending(&app).await; + }); + // Tauri's handle supports cancellation without keeping this command open. + let mut current = CONNECT.lock().unwrap(); + if let Some(c) = current.as_mut().filter(|c| c.generation == generation && c.result["status"] == "pending") { + c.task = Some(task.inner().abort_handle()); + } +} + +#[tauri::command] +pub fn drive_connect_cancel() { + GENERATION.fetch_add(1, Ordering::SeqCst); + let mut current = CONNECT.lock().unwrap(); + if let Some(c) = current.take() { + if let Some(task) = c.task { + task.abort(); + } + } +} + +#[tauri::command] +pub fn drive_connect_poll() -> Value { + CONNECT.lock().unwrap().as_ref().map(|c| c.result.clone()).unwrap_or(json!({"status": "cancelled"})) +} + +#[tauri::command] +pub async fn drive_connect_start(app: AppHandle, tv: bool) -> Res { + save_provider::ensure_idle(&app.state::())?; + drive_connect_cancel(); + let generation = GENERATION.fetch_add(1, Ordering::SeqCst) + 1; + if tv && !device_credentials().0.is_empty() { + return start_device(app, generation).await; + } + let (id, secret) = desktop_credentials(); + if id.is_empty() { + return Err(Error::Msg("Google Drive isn't configured in this launcher build.".into())); + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let redirect = format!("http://127.0.0.1:{}/oauth2callback", listener.local_addr()?.port()); + let state = random_text()?; + let verifier = random_text()?; + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + let mut url = reqwest::Url::parse("https://accounts.google.com/o/oauth2/v2/auth").unwrap(); + url.query_pairs_mut().extend_pairs(&[ + ("client_id", id), + ("redirect_uri", &redirect), + ("response_type", "code"), + ("scope", SCOPE), + ("state", &state), + ("code_challenge", &challenge), + ("code_challenge_method", "S256"), + ("access_type", "offline"), + ("prompt", "consent select_account"), + ]); + { + let mut current = CONNECT.lock().unwrap(); + if GENERATION.load(Ordering::SeqCst) != generation { + return Err(Error::Msg("Google sign-in was cancelled.".into())); + } + *current = Some(Connection { generation, task: None, result: json!({"status": "pending"}) }); + } + launch_connection(app, generation, async move { + let code = browser_code(listener, state).await?; + let tokens = token_form(&[ + ("client_id", id), + ("client_secret", secret), + ("code", &code), + ("code_verifier", &verifier), + ("redirect_uri", &redirect), + ("grant_type", "authorization_code"), + ]) + .await?; + Ok((tokens, id.into(), secret.into())) + }); + Ok(json!({"url": url.as_str(), "device": false, "expires": 600})) +} + +async fn start_device(app: AppHandle, generation: u64) -> Res { + let (id, secret) = device_credentials(); + let r = client() + .post("https://oauth2.googleapis.com/device/code") + .form(&[("client_id", id), ("scope", SCOPE)]) + .timeout(Duration::from_secs(20)) + .send() + .await + .map_err(transport)?; + let status = r.status().as_u16(); + let value: Value = r.json().await.map_err(transport)?; + if status >= 400 { + return Err(Error::Msg("Google couldn't start device sign-in. Use the browser on this PC.".into())); + } + let code = value["device_code"].as_str().ok_or_else(|| Error::Msg("Google didn't return a device code.".into()))?.to_string(); + let url = value["verification_url"].as_str().unwrap_or("https://www.google.com/device"); + let mut interval = value["interval"].as_u64().unwrap_or(5).clamp(5, 60); + let expires = value["expires_in"].as_u64().unwrap_or(600).min(600); + let end = Instant::now() + Duration::from_secs(expires); + { + let mut current = CONNECT.lock().unwrap(); + if GENERATION.load(Ordering::SeqCst) != generation { + return Err(Error::Msg("Google sign-in was cancelled.".into())); + } + *current = Some(Connection { generation, task: None, result: json!({"status": "pending"}) }); + } + launch_connection(app, generation, async move { + while Instant::now() < end { + tokio::time::sleep(Duration::from_secs(interval)).await; + let r = client() + .post(TOKEN) + .form(&[ + ("client_id", id), + ("client_secret", secret), + ("device_code", &code), + ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), + ]) + .timeout(Duration::from_secs(20)) + .send() + .await + .map_err(transport)?; + let v: Value = r.json().await.map_err(transport)?; + match v["error"].as_str() { + Some("authorization_pending") => continue, + Some("slow_down") => { + interval = (interval + 5).min(60); + continue; + } + Some(_) => return Err(Error::Msg("Google device sign-in was declined or expired. Try again.".into())), + None => return Ok((v, id.into(), secret.into())), + } + } + Err(Error::Msg("Google device sign-in expired. Try again.".into())) + }); + Ok(json!({"url": url, "code": value["user_code"], "qr": cloud::qr_svg(url), "device": true, "expires": expires})) +} + +#[tauri::command] +pub async fn drive_disconnect(app: AppHandle) -> Res { + drive_connect_cancel(); + let _busy = cloud::BUSY.lock().await; + let st = app.state::(); + save_provider::ensure_idle(&st)?; + if save_provider::current(&st.dir) == save_provider::Provider::GoogleDrive { + save_provider::clear_consent(&st)?; + } + crate::secret::forget_named(&st.dir, CREDENTIAL)?; + *ACCESS.lock().await = None; + NEEDS_RECONNECT.store(false, Ordering::Relaxed); + save_provider::emit(&app); + Ok(json!({"state": save_provider::state(&app), "installed": st.lib.lock().unwrap().installed})) +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct Snapshot { + format: u32, + game: String, + hash: String, + made: u64, + device: String, + played: u64, + generation: u64, + parents: Vec, +} + +#[derive(Clone)] +struct Remote { + id: String, + size: u64, + snapshot: Snapshot, +} + +fn heads(files: &[Remote]) -> Vec<&Remote> { + let parents: HashSet<&str> = files.iter().flat_map(|f| f.snapshot.parents.iter().map(String::as_str)).collect(); + files.iter().filter(|f| !parents.contains(f.id.as_str())).collect() +} + +fn revision(files: &[Remote]) -> String { + let mut ids: Vec<_> = heads(files).iter().map(|f| f.id.as_str()).collect(); + ids.sort(); + hex::encode(Sha256::digest(ids.join("\n").as_bytes())) +} + +fn copies(files: &[Remote]) -> Vec { + let heads = heads(files); + let hashes: HashSet<&str> = heads.iter().map(|f| f.snapshot.hash.as_str()).collect(); + let conflict = hashes.len() > 1; + let head_ids: HashSet<&str> = heads.iter().map(|f| f.id.as_str()).collect(); + let mut ordered: Vec<_> = files.iter().collect(); + ordered.sort_by(|a, b| { + head_ids + .contains(b.id.as_str()) + .cmp(&head_ids.contains(a.id.as_str())) + .then_with(|| b.snapshot.generation.cmp(&a.snapshot.generation)) + .then_with(|| a.id.cmp(&b.id)) + }); + ordered + .into_iter() + .map(|f| cloud::CloudCopy { + v: f.id.clone(), + hash: f.snapshot.hash.clone(), + size: f.size, + made: f.snapshot.made, + device: f.snapshot.device.clone(), + played: f.snapshot.played, + conflict, + revision: revision(files), + head: head_ids.contains(f.id.as_str()), + }) + .collect() +} + +fn game_key(id: &str) -> String { + hex::encode(Sha256::digest(id.as_bytes())) +} + +async fn query(app: &AppHandle, q: &str) -> Res> { + let mut page = String::new(); + let mut out = Vec::new(); + loop { + let request = client().get(format!("{API}/files")).timeout(Duration::from_secs(20)).query(&[ + ("q", q), + ("fields", "nextPageToken,incompleteSearch,files(id,size,description)"), + ("pageSize", "1000"), + ("pageToken", &page), + ]); + let value = json_response(send(app, request).await?).await?; + if value["incompleteSearch"] == true { + return Err(Error::Msg("Google Drive returned an incomplete save list. Try again later.".into())); + } + let files = value["files"].as_array().ok_or_else(|| Error::Msg("Google Drive returned an incomplete save list.".into()))?; + out.extend(files.iter().cloned()); + if out.len() > 20_000 { + return Err(Error::Msg("Too many Drive snapshots to sync safely. Review your Drive save folder.".into())); + } + page = value["nextPageToken"].as_str().unwrap_or("").to_string(); + if page.is_empty() { + return Ok(out); + } + } +} + +async fn remote(app: &AppHandle, id: &str) -> Res> { + let key = game_key(id); + let q = format!( + "trashed = false and appProperties has {{ key='rl' and value='save-v1' }} and appProperties has {{ key='game' and value='{key}' }}" + ); + let values = query(app, &q).await?; + let mut files = Vec::new(); + for value in values { + let snapshot: Snapshot = value["description"] + .as_str() + .and_then(|s| serde_json::from_str(s).ok()) + .ok_or_else(|| Error::Msg("A Google Drive save has invalid metadata. Review its save folder before syncing.".into()))?; + if snapshot.format != 1 || snapshot.game != id || snapshot.hash.len() != 64 { + return Err(Error::Msg("A Google Drive save has incompatible metadata.".into())); + } + let file_id = value["id"].as_str().filter(|s| valid_id(s)).ok_or_else(|| Error::Msg("Invalid Google Drive file ID.".into()))?; + let size = + value["size"].as_str().and_then(|s| s.parse::().ok()).ok_or_else(|| Error::Msg("Incomplete Google Drive save.".into()))?; + files.push(Remote { id: file_id.into(), size, snapshot }); + } + let generations: std::collections::HashMap<_, _> = files.iter().map(|f| (f.id.as_str(), f.snapshot.generation)).collect(); + for file in &files { + let snapshot = &file.snapshot; + let bad_parent = snapshot + .parents + .iter() + .any(|p| !valid_id(p) || p == &file.id || generations.get(p.as_str()).map(|&n| n >= snapshot.generation).unwrap_or(false)); + if snapshot.generation == 0 || bad_parent { + return Err(Error::Msg("Google Drive save history is inconsistent. Review its save folder before syncing.".into())); + } + } + if !files.is_empty() && heads(&files).is_empty() { + return Err(Error::Msg("Google Drive save history is inconsistent. Review its save folder before syncing.".into())); + } + Ok(files) +} + +pub async fn list(app: &AppHandle, id: &str) -> Res<(Vec, Value)> { + Ok((copies(&remote(app, id).await?), space(app).await?)) +} + +fn valid_id(id: &str) -> bool { + !id.is_empty() && id.len() <= 200 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +async fn folder(app: &AppHandle, kind: &str, name: &str, parent: Option<&str>) -> Res { + let q = format!( + "trashed = false and mimeType = 'application/vnd.google-apps.folder' and appProperties has {{ key='rl' and value='{kind}' }}" + ); + let mut files = query(app, &q).await?; + files.sort_by(|a, b| a["id"].as_str().cmp(&b["id"].as_str())); + if let Some(id) = files.first().and_then(|v| v["id"].as_str()).filter(|s| valid_id(s)) { + return Ok(id.into()); + } + let mut metadata = json!({"name": name, "mimeType": "application/vnd.google-apps.folder", "appProperties": {"rl": kind}}); + if let Some(parent) = parent { + metadata["parents"] = json!([parent]); + } + let value = + json_response(send(app, client().post(format!("{API}/files")).timeout(Duration::from_secs(20)).json(&metadata)).await?).await?; + value["id"] + .as_str() + .filter(|s| valid_id(s)) + .map(String::from) + .ok_or_else(|| Error::Msg("Google couldn't create the save folder.".into())) +} + +#[derive(Serialize, Deserialize)] +struct Ticket { + id: String, + archive_hash: String, + snapshot: Snapshot, + url: Option, +} + +fn ticket_path(dir: &Path, id: &str) -> PathBuf { + dir.join("drive-uploads").join(game_key(&format!("{}:{id}", identity(dir)))) +} + +fn save_ticket(path: &Path, ticket: &Ticket) -> Res<()> { + std::fs::create_dir_all(path.parent().unwrap())?; + let temp = path.with_extension("tmp"); + crate::secret::write_private(&temp, &serde_json::to_vec(ticket).unwrap())?; + std::fs::rename(temp, path)?; + Ok(()) +} + +fn valid_session(url: &str) -> bool { + let Ok(url) = reqwest::Url::parse(url) else { return false }; + url.scheme() == "https" + && url.host_str() == Some("www.googleapis.com") + && url.port_or_known_default() == Some(443) + && url.username().is_empty() + && url.password().is_none() + && url.path() == "/upload/drive/v3/files" +} + +async fn complete(app: &AppHandle, ticket: &Ticket, size: usize) -> Res { + let token = access(app, false).await?; + let r = client() + .get(format!("{API}/files/{}", ticket.id)) + .timeout(Duration::from_secs(20)) + .query(&[("fields", "id,size,sha256Checksum")]) + .bearer_auth(token) + .send() + .await + .map_err(transport)?; + if r.status().as_u16() == 404 { + return Ok(false); + } + let status = r.status().as_u16(); + let v: Value = r.json().await.map_err(transport)?; + if status >= 400 { + return Err(api_error(status, &v)); + } + Ok(v["size"].as_str().and_then(|s| s.parse::().ok()) == Some(size) && v["sha256Checksum"].as_str() == Some(&ticket.archive_hash)) +} + +async fn upload_bytes(app: &AppHandle, ticket_path: &Path, ticket: &mut Ticket, bytes: Vec) -> Res<()> { + if complete(app, ticket, bytes.len()).await? { + return Ok(()); + } + let mut offset = 0; + if let Some(url) = ticket.url.as_deref().filter(|u| valid_session(u)) { + let token = access(app, false).await?; + let r = client() + .put(url) + .timeout(Duration::from_secs(20)) + .bearer_auth(token) + .header("Content-Length", "0") + .header("Content-Range", format!("bytes */{}", bytes.len())) + .send() + .await + .map_err(transport)?; + match r.status().as_u16() { + 200 | 201 => { + return if complete(app, ticket, bytes.len()).await? { Ok(()) } else { Err(transport_error()) }; + } + 308 => offset = resume_offset(r.headers(), bytes.len())?, + 404 | 410 => ticket.url = None, + status => return Err(api_error(status, &r.json().await.unwrap_or(Value::Null))), + } + } else { + ticket.url = None; + } + if ticket.url.is_none() { + let root = folder(app, "root-v1", "RecompLauncher", None).await?; + let parent = folder(app, "saves-v1", "Saves", Some(&root)).await?; + let metadata = json!({"id": ticket.id, "name": format!("{}-{}.zip", crate::library::folder_name(&ticket.snapshot.game), ticket.snapshot.made), "parents": [parent], "mimeType": "application/zip", "description": serde_json::to_string(&ticket.snapshot).unwrap(), "appProperties": {"rl": "save-v1", "game": game_key(&ticket.snapshot.game)}}); + let request = client() + .post("https://www.googleapis.com/upload/drive/v3/files") + .query(&[("uploadType", "resumable")]) + .header("X-Upload-Content-Type", "application/zip") + .header("X-Upload-Content-Length", bytes.len()) + .json(&metadata); + let r = send(app, request).await?; + let url = r + .headers() + .get("Location") + .and_then(|v| v.to_str().ok()) + .filter(|u| valid_session(u)) + .ok_or_else(|| Error::Msg("Google returned an invalid upload session.".into()))?; + ticket.url = Some(url.into()); + save_ticket(ticket_path, ticket)?; + } + if offset >= bytes.len() { + return Err(transport_error()); + } + let total = bytes.len(); + let request = client() + .put(ticket.url.as_ref().unwrap()) + .header("Content-Type", "application/zip") + .header("Content-Range", format!("bytes {offset}-{}/{total}", total - 1)) + .body(bytes[offset..].to_vec()); + let r = send(app, request).await?; + if !r.status().is_success() { + return Err(transport_error()); + } + if !complete(app, ticket, total).await? { + return Err(Error::Msg("Google Drive's uploaded copy didn't match. Your local save is kept.".into())); + } + Ok(()) +} + +fn resume_offset(headers: &reqwest::header::HeaderMap, total: usize) -> Res { + let Some(range) = headers.get("Range") else { return Ok(0) }; + let last = range.to_str().ok().and_then(|s| s.strip_prefix("bytes=0-")).and_then(|s| s.parse::().ok()); + let offset = last.and_then(|n| n.checked_add(1)).filter(|&n| n <= total); + offset.ok_or_else(|| Error::Msg("Google returned an invalid upload position.".into())) +} + +pub async fn upload(app: &AppHandle, id: &str, path: &Path, resolution: Option<&str>) -> Res<()> { + let bytes = tokio::fs::read(path).await?; + if bytes.len() > MAX_ARCHIVE { + return Err(Error::Msg("This save is too big for cloud saves (over 95 MB). It's kept on this PC.".into())); + } + let man = saves::manifest(path).ok_or_else(|| Error::Msg("That save copy is gone.".into()))?; + let files = remote(app, id).await?; + let path = ticket_path(&app.state::().dir, id); + let archive_hash = hex::encode(Sha256::digest(&bytes)); + let old: Option = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()); + if resolution.map(|expected| revision(&files) != expected).unwrap_or(false) { + return Err(Error::Msg("The saves changed. Try syncing again.".into())); + } + let current_heads: HashSet<_> = heads(&files).iter().map(|f| f.id.as_str()).collect(); + let mut ticket = match old.filter(|t| { + let parents: HashSet<_> = t.snapshot.parents.iter().map(String::as_str).collect(); + let reusable = + resolution.is_none() || parents == current_heads || (current_heads.len() == 1 && current_heads.contains(t.id.as_str())); + t.archive_hash == archive_hash && valid_id(&t.id) && reusable + }) { + Some(ticket) => ticket, + None => { + let value = json_response( + send( + app, + client() + .get(format!("{API}/files/generateIds")) + .timeout(Duration::from_secs(20)) + .query(&[("count", "1"), ("space", "drive")]), + ) + .await?, + ) + .await?; + let file_id = value["ids"][0] + .as_str() + .filter(|s| valid_id(s)) + .ok_or_else(|| Error::Msg("Google couldn't allocate a save copy.".into()))?; + let parents = heads(&files).iter().map(|f| f.id.clone()).collect(); + let generation = files.iter().map(|f| f.snapshot.generation).max().unwrap_or(0).saturating_add(1); + let snapshot = Snapshot { + format: 1, + game: id.into(), + hash: man.hash, + made: man.made, + device: man.device, + played: man.played, + generation, + parents, + }; + Ticket { id: file_id.into(), archive_hash, snapshot, url: None } + } + }; + let synced = saves::state(&app.state::().dir, id).synced_hash; + if resolution.is_none() && heads(&files).iter().any(|f| f.snapshot.hash != synced && f.snapshot.hash != ticket.snapshot.hash) { + return Err(Error::Msg(cloud::SYNC_CONFLICT.into())); + } + save_ticket(&path, &ticket)?; + upload_bytes(app, &path, &mut ticket, bytes).await?; + let current = remote(app, id).await?; + if copies(¤t).first().map(|c| c.conflict).unwrap_or(false) { + return Err(Error::Msg(cloud::SYNC_CONFLICT.into())); + } + let _ = std::fs::remove_file(&path); + prune(app, ¤t).await; + Ok(()) +} + +async fn prune(app: &AppHandle, files: &[Remote]) { + // Conflicting branches and their ancestry are retained until the player resolves them. + if heads(files).len() != 1 { + return; + } + let mut ordered: Vec<_> = files.iter().collect(); + ordered.sort_by_key(|f| std::cmp::Reverse(f.snapshot.generation)); + for file in ordered.into_iter().skip(5) { + let request = client().patch(format!("{API}/files/{}", file.id)).timeout(Duration::from_secs(20)).json(&json!({"trashed": true})); + if send(app, request).await.is_err() { + break; + } + } +} + +pub async fn download(app: &AppHandle, id: &str, copy: &cloud::CloudCopy) -> Res> { + if !valid_id(©.v) || copy.size > MAX_ARCHIVE as u64 { + return Err(Error::Msg("That Google Drive save is too large or invalid.".into())); + } + let files = remote(app, id).await?; + if !files.iter().any(|f| f.id == copy.v && f.snapshot.hash == copy.hash) { + return Err(Error::Msg("The saves changed. Try syncing again.".into())); + } + let mut r = send(app, client().get(format!("{API}/files/{}", copy.v)).query(&[("alt", "media")])).await?; + let mut bytes = Vec::new(); + while let Some(chunk) = r.chunk().await.map_err(transport)? { + if bytes.len().saturating_add(chunk.len()) > MAX_ARCHIVE { + return Err(Error::Msg("That Google Drive save is too large.".into())); + } + bytes.extend_from_slice(&chunk); + } + if bytes.len() as u64 != copy.size { + return Err(Error::Msg("The Google Drive save didn't arrive whole.".into())); + } + Ok(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(id: &str, hash: &str, generation: u64, parents: &[&str]) -> Remote { + Remote { + id: id.into(), + size: 32, + snapshot: Snapshot { + format: 1, + game: "game".into(), + hash: hash.into(), + made: 100, + device: id.into(), + played: 60, + generation, + parents: parents.iter().map(|p| p.to_string()).collect(), + }, + } + } + + #[test] + fn simultaneous_saves_are_conflicts_even_with_equal_times() { + let files = vec![file("base", "old", 1, &[]), file("pc", "pc-save", 2, &["base"]), file("deck", "deck-save", 2, &["base"])]; + assert_eq!(heads(&files).len(), 2); + assert!(copies(&files).iter().all(|c| c.conflict)); + } + + #[test] + fn resolution_covers_both_branches() { + let files = vec![ + file("pc", "pc-save", 2, &["base"]), + file("deck", "deck-save", 2, &["base"]), + file("resolved", "pc-save", 3, &["pc", "deck"]), + ]; + let copies = copies(&files); + assert_eq!(copies[0].v, "resolved"); + assert!(!copies[0].conflict); + } + + #[test] + fn identical_saves_from_two_devices_do_not_conflict() { + let files = vec![file("pc", "same", 2, &["base"]), file("deck", "same", 2, &["base"])]; + assert!(!copies(&files)[0].conflict); + } + + #[test] + fn clock_skew_cannot_make_an_ancestor_current() { + let mut old = file("old", "old", 1, &[]); + old.snapshot.made = u64::MAX; + let files = vec![old, file("new", "new", 2, &["old"])]; + assert_eq!(copies(&files)[0].v, "new"); + } + + #[test] + fn trimming_old_ancestors_keeps_the_current_head() { + let files = vec![file("four", "four", 4, &["three"]), file("five", "five", 5, &["four"])]; + assert_eq!(heads(&files).len(), 1); + assert_eq!(copies(&files)[0].v, "five"); + } + + #[test] + fn revision_changes_when_another_device_uploads() { + let files = vec![file("pc", "one", 2, &["base"])]; + let mut next = files.clone(); + next.push(file("deck", "two", 2, &["base"])); + assert_ne!(revision(&files), revision(&next)); + } + + #[test] + fn revisions_ignore_listing_order() { + let files = vec![file("pc", "one", 2, &["base"]), file("deck", "two", 2, &["base"])]; + let mut reordered = files.clone(); + reordered.reverse(); + assert_eq!(revision(&files), revision(&reordered)); + } + + #[test] + fn callback_requires_the_original_state() { + assert_eq!(callback("GET /oauth2callback?code=secret&state=other HTTP/1.1\r\n\r\n", "expected").unwrap(), None); + } + + #[test] + fn callback_requires_the_expected_path() { + assert_eq!(callback("GET /favicon.ico?code=secret&state=expected HTTP/1.1\r\n\r\n", "expected").unwrap(), None); + } + + #[test] + fn callback_decodes_the_authorization_code() { + let result = callback("GET /oauth2callback?code=abc%2Fdef&state=expected HTTP/1.1\r\n\r\n", "expected").unwrap(); + assert_eq!(result.as_deref(), Some("abc/def")); + } + + #[test] + fn consent_denial_does_not_return_a_code() { + assert!(callback("GET /oauth2callback?error=access_denied&state=expected HTTP/1.1\r\n\r\n", "expected").is_err()); + } + + #[tokio::test] + async fn browser_sign_in_accepts_the_loopback_callback() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(browser_code(listener, "expected".into())); + let mut stream = tokio::net::TcpStream::connect(address).await.unwrap(); + stream.write_all(b"GET /oauth2callback?code=approved&state=expected HTTP/1.1\r\nHost: localhost\r\n\r\n").await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + assert!(response.starts_with("HTTP/1.1 200 OK")); + assert_eq!(server.await.unwrap().unwrap(), "approved"); + } + + #[test] + fn resumable_upload_continues_after_the_last_received_byte() { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert("Range", "bytes=0-262143".parse().unwrap()); + assert_eq!(resume_offset(&headers, 524288).unwrap(), 262144); + } + + #[test] + fn resumable_upload_rejects_an_offset_past_the_archive() { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert("Range", "bytes=0-999999".parse().unwrap()); + assert!(resume_offset(&headers, 100).is_err()); + } + + #[test] + fn upload_sessions_cannot_send_tokens_to_another_host() { + assert!(valid_session("https://www.googleapis.com/upload/drive/v3/files?upload_id=abc")); + assert!(!valid_session("https://www.googleapis.com.attacker.example/upload/drive/v3/files")); + assert!(!valid_session("http://www.googleapis.com/upload/drive/v3/files")); + assert!(!valid_session("https://www.googleapis.com:444/upload/drive/v3/files")); + } + + #[test] + fn rate_limit_errors_retry_without_pausing_the_website() { + let e = api_error(403, &json!({"error": {"errors": [{"reason": "userRateLimitExceeded"}]}})); + assert!(matches!(e, Error::Net(_))); + } + + #[test] + fn full_drive_gives_a_storage_error() { + let e = api_error(403, &json!({"error": {"errors": [{"reason": "storageQuotaExceeded"}]}})); + assert!(e.to_string().contains("Google Drive storage is full")); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c133cbd1..9a70ca5e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -16,6 +16,8 @@ pub mod assets; pub mod boot; pub mod catalog; pub mod cloud; +mod drive; +mod save_provider; pub mod devtools; pub mod display; pub mod dllcheck; @@ -10722,7 +10724,7 @@ pub fn run() { convert_plan, convert_copy, convert_cancel, looks_info, set_look, look_picture, ui_data, - reset_settings, tray::tray_words, tray::quit_launcher, ach::ach_access, ach::ach_status, ach::ach_apply, ach::ach_profile, ach::ach_games, ach::ach_board, ach::ach_game_web, ach::ach_report, ach::ach_tracker_get, ach::ach_game, ach::ach_set_disc, ach::ach_set_folder, ach::ach_sound, ach::ach_log, ach::ach_peek, ach::ach_rule, ach::ach_reset, ach::ach_test_toast, ach::ach_toast_take, ach::ach_toast_done, cloud::account_start, cloud::account_poll, cloud::account_cancel, cloud::account_state, cloud::account_signout, + reset_settings, tray::tray_words, tray::quit_launcher, ach::ach_access, ach::ach_status, ach::ach_apply, ach::ach_profile, ach::ach_games, ach::ach_board, ach::ach_game_web, ach::ach_report, ach::ach_tracker_get, ach::ach_game, ach::ach_set_disc, ach::ach_set_folder, ach::ach_sound, ach::ach_log, ach::ach_peek, ach::ach_rule, ach::ach_reset, ach::ach_test_toast, ach::ach_toast_take, ach::ach_toast_done, save_provider::save_provider_state, save_provider::save_provider_set, drive::drive_connect_start, drive::drive_connect_poll, drive::drive_connect_cancel, drive::drive_disconnect, cloud::account_start, cloud::account_poll, cloud::account_cancel, cloud::account_state, cloud::account_signout, cloud::saves_check, cloud::saves_pick, cloud::saves_play_without_cloud, cloud::saves_cloud, cloud::saves_cloud_follow_all, download_history, report_counts, play_reports, want_count, cloud::saves_info, cloud::saves_status, cloud::saves_peek, cloud::saves_upload_now, cloud::cloud_retry, cloud::saves_overview, cloud::saves_backup, cloud::saves_restore, cloud::saves_cloud_delete, cloud::saves_share, cloud::saves_set_place, cloud::saves_set_override, cloud::saves_add_place, cloud::saves_remove_place, cloud::saves_open, saves_set_root, saves_open_root, missing_files, missing_made, dll_check, dll_aside, gpu_choice, prefer_fast_gpu, copy_check, wine_tools, deck_scores, latest_counts, team_notes, trending, ig_info, ig_view, usage::pc_specs, usage::recomp_request, adopt::adopt_scan, adopt::migrate_scan, adopt::migrate_pick, adopt::adopt_pick, adopt::adopt_add, adopt::adopt_check, adopt::set_project, usage::usage_hello, usage::usage_event, usage::data_ids, usage::reset_ids, ping::usage_open, ping::usage_mode, usage::run_report, cloud::inbox, cloud::inbox_done, cloud::betas, cloud::beta_join, cloud::beta_leave, launcher_notes, scan_info, devtools::dev_add, devtools::add_any, devtools::dev_check, devtools::dev_starter, fs_places, fs_list, fs_extract, gb_mods, gb_mod, gb_install ]) diff --git a/src-tauri/src/save_provider.rs b/src-tauri/src/save_provider.rs new file mode 100644 index 00000000..2b4c053d --- /dev/null +++ b/src-tauri/src/save_provider.rs @@ -0,0 +1,104 @@ +//! The save destination is independent of the RecompStore account used by other launcher features. + +use crate::{cloud, drive, App, Error}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::path::Path; +use tauri::{AppHandle, Emitter, Manager}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Provider { + #[default] + Recompstore, + GoogleDrive, + Disabled, +} + +pub fn current(dir: &Path) -> Provider { + match std::fs::read(dir.join("save-provider.json")) { + Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or(Provider::Disabled), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Provider::Recompstore, + Err(_) => Provider::Disabled, + } +} + +pub fn ready(dir: &Path) -> bool { + match current(dir) { + Provider::Recompstore => cloud::signed_in(dir), + Provider::GoogleDrive => drive::connected(dir), + Provider::Disabled => false, + } +} + +pub fn scope(dir: &Path) -> String { + match current(dir) { + Provider::Recompstore => format!("recompstore:{}", cloud::account_scope(dir)), + Provider::GoogleDrive => format!("google_drive:{}", drive::identity(dir)), + Provider::Disabled => "disabled".into(), + } +} + +pub fn name(dir: &Path) -> &'static str { + match current(dir) { + Provider::Recompstore => "RecompStore", + Provider::GoogleDrive => "Google Drive", + Provider::Disabled => "Unavailable", + } +} + +pub fn state(app: &AppHandle) -> Value { + let st = app.state::(); + json!({"provider": current(&st.dir), "name": name(&st.dir), "connected": ready(&st.dir), "google": drive::state(&st.dir)}) +} + +#[tauri::command] +pub fn save_provider_state(app: AppHandle) -> Value { + state(&app) +} + +pub fn emit(app: &AppHandle) { + let st = app.state::(); + let _ = app.emit("save-provider", json!({"state": state(app), "installed": st.lib.lock().unwrap().installed})); +} + +pub fn ensure_idle(st: &App) -> Result<(), Error> { + if !st.running.lock().unwrap().is_empty() || !st.pids.lock().unwrap().is_empty() || !crate::STARTING.lock().unwrap().is_empty() { + return Err(Error::Msg("Close your games before changing the cloud save account or provider.".into())); + } + Ok(()) +} + +/// A destination change needs fresh consent for each game. Local backups and remote history stay. +pub fn clear_consent(st: &App) -> Result<(), Error> { + let mut library = st.lib.lock().unwrap(); + let mut next = library.clone(); + for game in next.installed.values_mut() { + game.cloud = None; + } + next.save(&st.dir)?; + *library = next; + cloud::reset_provider_status(); + Ok(()) +} + +#[tauri::command] +pub async fn save_provider_set(app: AppHandle, provider: Provider) -> Result { + if provider == Provider::Disabled { + return Err(Error::Msg("Choose RecompStore or Google Drive.".into())); + } + let _guard = cloud::BUSY.lock().await; + let st = app.state::(); + ensure_idle(&st)?; + if provider == Provider::GoogleDrive && !drive::connected(&st.dir) { + return Err(Error::Msg("Connect Google Drive first.".into())); + } + if current(&st.dir) != provider { + clear_consent(&st)?; + let temp = st.dir.join("save-provider.json.tmp"); + crate::secret::write_private(&temp, &serde_json::to_vec(&provider).unwrap())?; + std::fs::rename(temp, st.dir.join("save-provider.json"))?; + } + emit(&app); + Ok(json!({"state": state(&app), "installed": st.lib.lock().unwrap().installed})) +} diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index 7ae17092..70a7d343 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -875,7 +875,7 @@ const SCOPE_KEY: &str = "cloud_scope"; /// The sign-in a note's cloud fields are written under now. Read from account.json without /// opening the sealed token, so it costs no trip to Windows' Credential Manager. fn scope_now(app_dir: &Path) -> String { - format!("recompstore:{}", crate::cloud::account_uid(app_dir)) + crate::save_provider::scope(app_dir) } /// A scope with no account id after the colon is nobody's: nothing in the cloud belongs to it. @@ -901,7 +901,9 @@ fn write_note(app_dir: &Path, id: &str, s: &State, scope: &str) { } let mut value = serde_json::to_value(s).unwrap_or_default(); value[SCOPE_KEY] = scope.into(); - let _ = fs::write(f, serde_json::to_vec_pretty(&value).unwrap_or_default()); + let temp = f.with_extension("json.tmp"); + let result = fs::write(&temp, serde_json::to_vec_pretty(&value).unwrap_or_default()).and_then(|_| fs::rename(&temp, &f)); + if result.is_err() { let _ = fs::remove_file(temp); } } /// What this PC knows about a game's saves, for whoever is signed in now. The cloud fields only @@ -1125,6 +1127,61 @@ fn not_written(path: &Path, e: io::Error) -> Error { Error::Msg(format!("{SAVE_NOT_WRITTEN}\n{}: {e}", path.display())) } +/// Drive files can be edited outside the launcher. Check every byte before changing live saves, +/// and only allow destinations this PC already knows belong to the game. +pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot]) -> Result<(), Error> { + let invalid = || Error::Msg("That cloud save is damaged or doesn't match this game's save folders. Nothing was restored.".into()); + let mut zip = zip::ZipArchive::new(fs::File::open(path)?).map_err(|_| invalid())?; + if zip.len() > MAX_FILES + 1 { return Err(invalid()); } + let man: Manifest = { + let mut entry = zip.by_name("rlsave.json").map_err(|_| invalid())?; + if entry.size() > 8 * 1024 * 1024 { return Err(invalid()); } + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes)?; + serde_json::from_slice(&bytes).map_err(|_| invalid())? + }; + if man.format != 1 || man.game != id || man.hash != hash || set_hash(&man.files) != hash || man.files.is_empty() { + return Err(invalid()); + } + let picked = !spots.is_empty() && spots.iter().all(|s| s.from == "player"); + if man.spots.len() != spots.len() || (!picked && man.spots.iter().zip(spots).any(|(a, b)| a != &b.template)) { + return Err(invalid()); + } + let mut expected = HashMap::new(); + let mut total = 0u64; + for file in &man.files { + let unsafe_name = file.rel.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p.contains(['\\', ':'])); + if file.spot >= spots.len() || file.size > MAX_FILE || unsafe_name { return Err(invalid()); } + total = total.checked_add(file.size).ok_or_else(invalid)?; + if total > SPOT_MAX { return Err(invalid()); } + let name = format!("{}/{}", file.spot, file.rel); + if expected.insert(name, file).is_some() { return Err(invalid()); } + } + if zip.len() != expected.len() + 1 { return Err(invalid()); } + let mut seen = HashSet::new(); + for index in 0..zip.len() { + let mut entry = zip.by_index(index).map_err(|_| invalid())?; + let name = entry.name().to_string(); + if !seen.insert(name.clone()) { return Err(invalid()); } + if name == "rlsave.json" { continue; } + let file = expected.get(&name).ok_or_else(invalid)?; + let symlink = entry.unix_mode().map(|m| m & 0o170000 == 0o120000).unwrap_or(false); + if entry.size() != file.size || symlink { return Err(invalid()); } + let mut sha = Sha256::new(); + let mut buffer = [0u8; 64 * 1024]; + let mut count = 0u64; + loop { + let n = entry.read(&mut buffer)?; + if n == 0 { break; } + count += n as u64; + if count > file.size { return Err(invalid()); } + sha.update(&buffer[..n]); + } + if count != file.size || hex::encode(sha.finalize()) != file.sha256 { return Err(invalid()); } + } + Ok(()) +} + /// Puts a copy's files back where the game reads them, on this PC. Saves that are there now and /// aren't in the copy are taken away, so the game sees exactly what was copied; what was there is /// kept as a copy first, so this can be undone. @@ -1497,6 +1554,98 @@ pub fn share_save(app_dir: &Path, id: &str, spot: &Spot, g: &Installed, source: #[cfg(test)] mod tests { + fn cloud_archive(dir: &Path, template: &str, data: &[u8], actual: &[u8]) -> (PathBuf, String) { + let files = vec![FileInfo { spot: 0, rel: "slot.sav".into(), size: data.len() as u64, sha256: hex::encode(Sha256::digest(data)) }]; + let hash = set_hash(&files); + let manifest = Manifest { format: 1, game: "g".into(), hash: hash.clone(), spots: vec![template.into()], files, ..Default::default() }; + let path = dir.join("cloud.zip"); + let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("rlsave.json", options).unwrap(); + zip.write_all(&serde_json::to_vec(&manifest).unwrap()).unwrap(); + zip.start_file("0/slot.sav", options).unwrap(); + zip.write_all(actual).unwrap(); + zip.finish().unwrap(); + (path, hash) + } + + #[test] + fn cloud_copy_checks_every_file_before_restore() { + let dir = tmp("cloud-valid"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_ok()); + } + + #[test] + fn cloud_copy_rejects_changed_file_contents() { + let dir = tmp("cloud-changed"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"evil"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_err()); + } + + #[test] + fn cloud_copy_cannot_redirect_a_save_to_another_folder() { + let dir = tmp("cloud-redirect"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, "{home}/Documents", b"save", b"save"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_err()); + } + + #[test] + fn cloud_copy_accepts_a_different_folder_the_player_picked_on_this_pc() { + let dir = tmp("cloud-player-folder"); + let spots = vec![Spot { template: "{home}/my-saves".into(), from: "player" }]; + let (path, hash) = cloud_archive(&dir, "{home}/other-pc-saves", b"save", b"save"); + assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_ok()); + } + + #[test] + fn cloud_copy_rejects_another_games_archive() { + let dir = tmp("cloud-game"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert!(validate_cloud_copy(&path, "another-game", &hash, &spots).is_err()); + } + + #[test] + fn provider_changes_discard_the_sync_baseline_and_queue() { + let dir = tmp("cloud-provider"); + let state = State { last_hash: "local".into(), synced_hash: "cloud".into(), pending: Some("123.zip".into()) }; + set_state(&dir, "g", &state); + fs::write(dir.join("save-provider.json"), b"\"google_drive\"").unwrap(); + let read = super::state(&dir, "g"); + assert_eq!(read.last_hash, "local"); + assert!(read.synced_hash.is_empty()); + assert!(read.pending.is_none()); + } + + #[test] + fn account_changes_discard_the_sync_baseline_and_queue() { + let dir = tmp("cloud-account"); + let value = serde_json::json!({"last_hash": "local", "synced_hash": "cloud", "pending": "123.zip", "cloud_scope": "google_drive:another-account"}); + fs::create_dir_all(dir.join("saves/g")).unwrap(); + fs::write(state_file(&dir, "g"), serde_json::to_vec(&value).unwrap()).unwrap(); + let read = super::state(&dir, "g"); + assert_eq!(read.last_hash, "local"); + assert!(read.synced_hash.is_empty()); + assert!(read.pending.is_none()); + } + + #[test] + fn legacy_website_sync_state_is_migrated() { + let dir = tmp("cloud-legacy"); + let value = serde_json::json!({"last_hash": "local", "synced_hash": "cloud", "pending": "123.zip"}); + fs::create_dir_all(dir.join("saves/g")).unwrap(); + fs::write(state_file(&dir, "g"), serde_json::to_vec(&value).unwrap()).unwrap(); + let read = super::state(&dir, "g"); + assert_eq!(read.synced_hash, "cloud"); + assert_eq!(read.pending.as_deref(), Some("123.zip")); + let migrated: serde_json::Value = serde_json::from_slice(&fs::read(state_file(&dir, "g")).unwrap()).unwrap(); + assert!(migrated["cloud_scope"].as_str().unwrap().starts_with("recompstore:")); + } + #[test] fn several_save_folders_the_player_picked() { let d = std::env::temp_dir().join(format!("rl-saves-many-{}", std::process::id())); diff --git a/src-tauri/src/secret.rs b/src-tauri/src/secret.rs index bab4df78..70f483cb 100644 --- a/src-tauri/src/secret.rs +++ b/src-tauri/src/secret.rs @@ -2,6 +2,52 @@ //! Windows user only; account.json then just says so. Elsewhere the file it's in is readable by //! its owner only. +/// Separate providers must never replace or remove each other's credentials. +pub fn save_named(dir: &std::path::Path, name: &str, plain: &[u8]) -> std::io::Result<()> { + #[cfg(windows)] + { + let _ = dir; + let text = std::str::from_utf8(plain).map_err(std::io::Error::other)?; + if !crate::win::cred_write_named(&format!("RecompLauncher/{name}"), text) { + return Err(std::io::Error::other("Couldn't save the Google sign-in in Credential Manager.")); + } + return Ok(()); + } + #[cfg(not(windows))] + { + let path = dir.join(format!("{name}.json")); + let temp = dir.join(format!("{name}.json.tmp")); + write_private(&temp, plain)?; + std::fs::rename(temp, path) + } +} + +pub fn load_named(dir: &std::path::Path, name: &str) -> Option> { + #[cfg(windows)] + { + let _ = dir; + crate::win::cred_read_named(&format!("RecompLauncher/{name}")).map(String::into_bytes) + } + #[cfg(not(windows))] + std::fs::read(dir.join(format!("{name}.json"))).ok() +} + +pub fn forget_named(dir: &std::path::Path, name: &str) -> std::io::Result<()> { + #[cfg(windows)] + { + let _ = dir; + if !crate::win::cred_delete_named(&format!("RecompLauncher/{name}")) { + return Err(std::io::Error::other("Couldn't remove the Google sign-in from Credential Manager.")); + } + Ok(()) + } + #[cfg(not(windows))] + match std::fs::remove_file(dir.join(format!("{name}.json"))) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + result => result, + } +} + /// Where account.json says the token is kept. #[cfg(windows)] const IN_WINDOWS: &str = "credential-manager"; diff --git a/src-tauri/src/win.rs b/src-tauri/src/win.rs index 9381fe1b..891b0913 100644 --- a/src-tauri/src/win.rs +++ b/src-tauri/src/win.rs @@ -400,8 +400,12 @@ mod imp { /// Keeps a secret in Windows' Credential Manager, for this Windows user only. pub fn cred_write(secret: &str) -> bool { + cred_write_named(CRED, secret) + } + + pub fn cred_write_named(name: &str, secret: &str) -> bool { use windows::Win32::Security::Credentials::{CredWriteW, CREDENTIALW, CRED_PERSIST_LOCAL_MACHINE, CRED_TYPE_GENERIC}; - let mut target: Vec = CRED.encode_utf16().chain([0]).collect(); + let mut target: Vec = name.encode_utf16().chain([0]).collect(); let mut user: Vec = "RecompLauncher".encode_utf16().chain([0]).collect(); let mut blob = secret.as_bytes().to_vec(); let c = CREDENTIALW { @@ -417,9 +421,13 @@ mod imp { } pub fn cred_read() -> Option { + cred_read_named(CRED) + } + + pub fn cred_read_named(name: &str) -> Option { use windows::Win32::Security::Credentials::{CredFree, CredReadW, CREDENTIALW, CRED_TYPE_GENERIC}; let mut p: *mut CREDENTIALW = std::ptr::null_mut(); - unsafe { CredReadW(&HSTRING::from(CRED), CRED_TYPE_GENERIC, None, &mut p) }.ok()?; + unsafe { CredReadW(&HSTRING::from(name), CRED_TYPE_GENERIC, None, &mut p) }.ok()?; if p.is_null() { return None; } @@ -433,8 +441,15 @@ mod imp { } pub fn cred_delete() { + cred_delete_named(CRED); + } + + pub fn cred_delete_named(name: &str) -> bool { use windows::Win32::Security::Credentials::{CredDeleteW, CRED_TYPE_GENERIC}; - let _ = unsafe { CredDeleteW(&HSTRING::from(CRED), CRED_TYPE_GENERIC, None) }; + match unsafe { CredDeleteW(&HSTRING::from(name), CRED_TYPE_GENERIC, None) } { + Ok(()) => true, + Err(e) => e.code() == windows::core::HRESULT::from_win32(windows::Win32::Foundation::ERROR_NOT_FOUND.0), + } } // ---------- the administrator prompt ---------- diff --git a/tests/google-drive.test.cjs b/tests/google-drive.test.cjs new file mode 100644 index 00000000..4ed33a36 --- /dev/null +++ b/tests/google-drive.test.cjs @@ -0,0 +1,70 @@ +const assert = require('node:assert/strict'); +const { readFileSync } = require('node:fs'); +const { join } = require('node:path'); +const test = require('node:test'); +const { runInNewContext } = require('node:vm'); + +const account = readFileSync(join(__dirname, '../ui/account.js'), 'utf8'); +const providerHelpers = account.slice(account.indexOf('S.saveProvider ='), account.indexOf('async function loadAccount(')); + +function providerSetup(picked) { + const S = { library: { game: { cloud: true } }, saves: {}, savesAll: {} }; + const calls = []; + const helpers = runInNewContext(providerHelpers + '\n({chooseSaveProvider, cloudReady})', { + S, window: {}, t: String, tf: String, tn: String, esc: String, + ask: async () => picked, + invoke: async (command, args) => { + calls.push([command, { ...args }]); + return { state: { provider: args.provider, connected: true }, installed: { game: { cloud: null } } }; + }, + renderAccountBits() {}, + }); + return { S, calls, ...helpers }; +} + +test('cancelling a provider change keeps the existing game consent', async () => { + const { chooseSaveProvider, calls, S } = providerSetup(false); + await chooseSaveProvider('google_drive'); + assert.deepEqual(calls, []); + assert.equal(S.library.game.cloud, true); +}); + +test('confirming a provider change uses the new consent returned by the backend', async () => { + const { chooseSaveProvider, calls, S } = providerSetup(true); + await chooseSaveProvider('google_drive'); + assert.deepEqual(calls, [['save_provider_set', { provider: 'google_drive' }]]); + assert.equal(S.library.game.cloud, null); + assert.equal(S.saveProvider.provider, 'google_drive'); +}); + +test('selecting the current provider does not reset consent', async () => { + const { chooseSaveProvider, calls, S } = providerSetup(true); + await chooseSaveProvider('recompstore'); + assert.deepEqual(calls, []); + assert.equal(S.library.game.cloud, true); +}); + +test('Drive sync before play does not need a RecompStore sign-in', async () => { + const source = account.slice(account.indexOf('async function beforeCloudPlay('), account.indexOf('async function pickCloudSave(')); + const calls = []; + const play = runInNewContext(source + '\nbeforeCloudPlay', { + S: { account: { signedIn: false }, library: { game: { cloud: true } } }, + cloudReady: () => true, + invoke: async (command, args) => { calls.push([command, { ...args }]); return { action: 'play' }; }, + savesChanged() {}, toast() {}, fail: assert.fail, + }); + assert.equal(await play('game'), true); + assert.deepEqual(calls, [['saves_check', { id: 'game' }]]); +}); + +test('Drive conflict choices submit the revision the player reviewed', async () => { + const source = account.slice(account.indexOf('async function pickCloudSave('), account.indexOf('// ---------- actions ----------')); + const calls = []; + const pick = runInNewContext(source + '\npickCloudSave', { + invoke: async (command, args) => calls.push([command, { ...args }]), + ask: async () => 'local', + t: String, tf: String, esc: String, whenText: String, fmtTime: String, toast() {}, + }); + await pick('game', { local: { hash: 'local', when: 100 }, cloud: { v: 'file', revision: 'both-heads', made: 200 } }); + assert.deepEqual(calls, [['saves_pick', { id: 'game', keep: 'local', localHash: 'local', cloudVersion: 'file', cloudRevision: 'both-heads' }]]); +}); diff --git a/ui/account.js b/ui/account.js index efe95dea..13868ef7 100644 --- a/ui/account.js +++ b/ui/account.js @@ -16,11 +16,105 @@ const whenText = (ts) => (ts ? new Date(ts * 1000).toLocaleString(curLocale(), t const avatar = (u, size = 28) => (u && u.avatar ? `` : `${esc(((u && u.username) || '?').slice(0, 1).toUpperCase())}`); const inTV = () => document.body.classList.contains('tv-on'); +S.saveProvider = { provider: 'recompstore', name: 'RecompStore', connected: false, google: {} }; +const cloudReady = () => !!S.saveProvider?.connected; + +function applySaveProvider(result) { + S.saveProvider = result.state || result; + if (result.installed) S.library = result.installed; + S.saves = {}; S.savesAll = null; + if (window.tvSavesReset) window.tvSavesReset(); +} + +async function loadSaveProvider() { + try { applySaveProvider(await invoke('save_provider_state')); } catch (_) { /* The previous state stays until the next refresh. */ } +} + +async function chooseSaveProvider(provider) { + if (S.saveProvider.provider === provider) return; + const name = provider === 'google_drive' ? 'Google Drive' : 'RecompStore'; + const count = Object.values(S.library || {}).filter((g) => g.cloud === true).length; + const message = tf('Use {name} for cloud saves? Enable each game again on its Saves tab. Existing local backups and cloud copies are kept.', { name }); + const picked = await ask(t('Change save destination?'), `

${esc(message)}

`, [ + { label: t('Cancel'), v: false, focus: true }, + { label: tf('Use {name}', { name }), sub: message + ' ' + tn(count, '1 game currently syncs', '{n} games currently sync'), v: true }, + ]); + if (!picked) return; + applySaveProvider(await invoke('save_provider_set', { provider })); + renderAccountBits(); +} + +async function connectDrive() { + let start; + try { start = await invoke('drive_connect_start', { tv: inTV() }); } catch (e) { return fail(e); } + const hint = start.device + ? tf('Open {url} on your phone and enter this code:', { url: start.url }) + : t('Finish connecting Google Drive in the browser on this PC. Return here when you have approved access.'); + let closed = false, timer, box, tv; + const cancel = () => { closed = true; clearTimeout(timer); invoke('drive_connect_cancel').catch(() => {}); }; + if (inTV() && window.tvSignIn) { + tv = window.tvSignIn({ title: t('Connect Google Drive'), hint, qr: start.qr || '', code: start.code || '', onClose: cancel }); + } else { + box = modal(`

${esc(t('Connect Google Drive'))}

${esc(hint)}

${esc(t('Waiting for Google…'))}

`, (el, close) => { + if (el.dataset.x === 'open') return invoke('open_url', { url: start.url }).catch(fail); + cancel(); close(); + }, t('Connect Google Drive')); + new MutationObserver((_m, observer) => { if (!box.isConnected) { observer.disconnect(); if (!closed) cancel(); } }).observe(document.body, { childList: true }); + } + if (!start.device) invoke('open_url', { url: start.url }).catch(fail); + const until = Date.now() + start.expires * 1000; + const poll = async () => { + if (closed) return; + let result; + try { result = await invoke('drive_connect_poll'); } catch (e) { result = { status: 'error', error: String(e) }; } + if (closed) return; + if (result.status === 'pending' && Date.now() < until) { timer = setTimeout(poll, 1000); return; } + closed = true; + if (tv) tv.close(true); + if (box) box.remove(); + if (result.status !== 'ok') { cancel(); return fail(result.error || t('Google sign-in expired. Try connecting again.')); } + await loadSaveProvider(); + // The backend may have cleared consent when a different Google account replaced the old one. + const current = await invoke('save_provider_set', { provider: S.saveProvider.provider }); + applySaveProvider(current); + renderAccountBits(); + toast(t('Google Drive connected.')); + await chooseSaveProvider('google_drive'); + }; + timer = setTimeout(() => poll().catch((e) => { cancel(); fail(e); }), 1000); +} + +async function disconnectDrive() { + const message = t('Stop Google Drive sync on this PC? Local saves and copies already in Drive are kept.'); + const picked = await ask(t('Disconnect Google Drive?'), `

${esc(message)}

`, [ + { label: t('Cancel'), v: false, focus: true }, { label: t('Disconnect'), sub: message, v: true }, + ]); + if (!picked) return; + applySaveProvider(await invoke('drive_disconnect')); + renderAccountBits(); +} +window.connectDrive = connectDrive; +window.chooseSaveProvider = chooseSaveProvider; +window.disconnectDrive = disconnectDrive; + +function saveProviderSection(group, row) { + const p = S.saveProvider, google = p.google || {}; + const button = (label, act, disabled = false) => ``; + const info = tf('Current destination: {name}. Enable cloud saves separately for each game.', { name: p.name }); + const googleHelp = google.needsReconnect ? t('Google Drive needs you to connect again.') : google.connected ? google.email : google.configured ? t('Connect your Google account. Save copies go directly to your Drive.') : t('Google Drive is not configured in this launcher build.'); + return group(t('Save destination'), `

${esc(info)}

` + + row('RecompStore', t('Use your RecompStore account for game saves.'), button(p.provider === 'recompstore' ? 'Selected' : 'Use RecompStore', 'provider-recompstore', p.provider === 'recompstore')) + + row('Google Drive', googleHelp, `${google.connected ? button('Reconnect', 'drive-connect') + button('Disconnect', 'drive-disconnect') + button(p.provider === 'google_drive' ? 'Selected' : 'Use Google Drive', 'provider-google', p.provider === 'google_drive') : button('Connect Google Drive', 'drive-connect', !google.configured)}`) + + row(t('Ask for Each New Game'), t('Ask before enabling cloud saves for a game.'), ``) + + deviceNameRow()); +} + async function loadAccount(fresh) { const was = !!(S.account && S.account.signedIn); try { S.account = await invoke('account_state', { fresh: !!fresh }); } catch (e) { S.account = S.account || { signedIn: false }; } // Signed in (or out) just now: what each game's Saves tab knew is out of date. if (was !== !!S.account.signedIn) { S.saves = {}; S.savesAll = null; S.myReports = null; forgetSaveStatus(); } + await loadSaveProvider(); renderAccountBits(); if (S.account.signedIn && !S.myReports && !S.account.offline) loadMyReports(); // The saved list, kept with the account. @@ -136,6 +230,9 @@ async function signOut() { // ---------- Settings > Account ---------- function accountSection(group, row) { + return saveProviderSection(group, row) + recompAccountSection(group, row); +} +function recompAccountSection(group, row) { const a = S.account || {}; if (!a.signedIn) { return group(t('Account'), `
${CLOUD_ICON}
${esc(t('Keep your saves safe'))}${esc(t('With a RecompStore account, your saves go to the cloud after you play and are there on any PC. It\'s free, and the launcher works the same without one.'))}
@@ -812,7 +909,7 @@ function rootCard(o) { function pageSaves() { const o = S.savesAll; if (!o) { loadSavesAll(); return `
${esc(t('Loading…'))}
`; } - const acc = S.account || {}; + const acc = S.saveProvider.provider === 'google_drive' ? { signedIn: cloudReady(), drive: true } : S.account || {}; const games = (o.games || []).map((x) => ({ ...x, g: S.library[x.id] || {}, a: byId(x.id) })).filter((x) => x.g.name || x.a); const withSaves = games.filter((x) => x.copies).sort((a, b) => (b.newest?.when || 0) - (a.newest?.when || 0)); const none = games.filter((x) => !x.copies).sort((a, b) => (a.g.name || '').localeCompare(b.g.name || '')); @@ -822,7 +919,9 @@ function pageSaves() { const pcCard = `
${CARD_ICON}
${esc(t('On this PC'))}${esc(tn(withSaves.length, '1 game with saves', '{n} games with saves'))}
${esc(fmtB(size) || '0 KB')}
${blocks(withSaves.length ? withSaves.length / Math.max(games.length, 1) : 0)}

${esc(tn(copies, '1 copy kept', '{n} copies kept'))} · ${esc(t('The newest ten of each game'))}

`; - const cloudCard = acc.signedIn + const cloudCard = acc.drive && acc.signedIn + ? `
${CLOUD_ICON}
Google Drive${esc(S.saveProvider.google?.email || '')}

${esc(tn(cloudGames, '1 game syncs to Drive', '{n} games sync to Drive'))}

` + : acc.signedIn ? `
${CLOUD_ICON}
${esc(t('Cloud saves'))}${esc(tn(cloudGames, '1 game backs up to your account', '{n} games back up to your account'))}
${esc(fmtB(used) || '0 KB')}
${blocks(used / quota)}

${esc(tf('{used} of {quota} used', { used: fmtB(used) || '0 KB', quota: fmtB(quota) }))}

` @@ -988,7 +1087,7 @@ async function beforePlay(id) { // whether a game's saves go up was picked once for every game (askCloudAll), or in its Manage tab. async function beforeCloudPlay(id) { const g = S.library[id]; - if (!g || !(S.account && S.account.signedIn)) return true; + if (!g || !cloudReady()) return true; if (!cloudOn(g)) return true; let r; try { r = await invoke('saves_check', { id }); } catch (e) { fail(e); return false; } @@ -1022,7 +1121,7 @@ async function playWithoutCloud(id, r) { async function pickCloudSave(id, { local, cloud }) { const v = await chooseSave(local, cloud); if (v !== 'local' && v !== 'cloud') return false; - await invoke('saves_pick', { id, keep: v, localHash: local.hash, cloudVersion: cloud.v }); + await invoke('saves_pick', { id, keep: v, localHash: local.hash, cloudVersion: cloud.v, ...(cloud.revision ? { cloudRevision: cloud.revision } : {}) }); toast(t(v === 'cloud' ? 'The cloud save is in place.' : 'Your save is in the cloud.')); return true; } @@ -1063,6 +1162,11 @@ async function syncCloudNow(id) { window.accountAct = async (act, el) => { const id = el.dataset.id; switch (act) { + case 'acc-save-settings': S.setTab = 'account'; return go('settings'); + case 'acc-drive-connect': return connectDrive().catch(fail); + case 'acc-drive-disconnect': return disconnectDrive().catch(fail); + case 'acc-provider-google': return chooseSaveProvider('google_drive').catch(fail); + case 'acc-provider-recompstore': return chooseSaveProvider('recompstore').catch(fail); case 'acc-signin': return signIn(false); case 'acc-create': return signIn(true); case 'acc-signout': return signOut(); @@ -1210,7 +1314,11 @@ window.accountAct = async (act, el) => { return null; }; -T.event.listen('account', ({ payload }) => { if (payload && payload.signedIn === false) { S.account = { signedIn: false }; S.saves = {}; forgetSaveStatus(); renderAccountBits(); } else loadAccount(true); }); +T.event.listen('save-provider', async ({ payload }) => { + applySaveProvider(payload); + renderAccountBits(); +}); +T.event.listen('account', async ({ payload }) => { if (payload && payload.signedIn === false) { S.account = { signedIn: false }; S.saves = {}; forgetSaveStatus(); await loadSaveProvider(); renderAccountBits(); } else loadAccount(true); }); T.event.listen('saves', ({ payload }) => { if (S.view === 'saves') loadSavesAll(); if (payload && payload.id) { delete S.saves[payload.id]; loadSaveStatus(payload.id); if (S.view === 'game' && S.arg === payload.id && S.tab === 'saves') loadSaves(payload.id); } }); // A check, upload or download for a game started or ended: the badge says so, and asks for the // outcome once it's over. diff --git a/ui/tv.js b/ui/tv.js index a29d4f3a..19ab3dad 100644 --- a/ui/tv.js +++ b/ui/tv.js @@ -1396,6 +1396,11 @@ ${S.account && S.account.signedIn ? `` : ``} + ${head(t('Save destination'))} + + + ${S.saveProvider?.google?.connected ? `` : ''} + ${head(t('Display'))} ${(() => { const m = window.monitorPicked(S.monitors, S.settings.tv_monitor); @@ -2148,7 +2153,7 @@ TV.sheet = { items: [{ label: t('Cancel') }], prev: (focused() || {}).dataset?.key, onClose: () => s.onClose && s.onClose() }; const el = document.createElement('div'); el.className = 'tv-sheet tv-signin'; - el.innerHTML = `

${esc(t('Sign in with your phone'))}

+ el.innerHTML = `

${esc(s.title || t('Sign in with your phone'))}

`; stage().append(el); focus($('[data-sheet="0"]', el), true); @@ -2682,6 +2687,7 @@ const cls = `tv-ambient m-${m}`; if (el.className !== cls) { el.className = cls; el.innerHTML = m === 'grid' ? '' : m === 'drift' ? '' : ''; } } + window.tvSavesReset = () => { TV.saves = {}; TV.savesAll = null; }; window.tvRefresh = () => soon(); // A game moved to another id (one added by link, now on the official list): the page on and // the pages behind it follow. @@ -3164,6 +3170,13 @@ // Asking for a review after a long session, as Settings > Reviews has it on the desktop. case 'reviewask': sfx('select'); await window.setReviewAsk(!window.reviewAskOn()); return draw(true); case 'lang': sfx('open'); return pickLang(); + case 'drive-connect': return window.connectDrive().catch(fail); + case 'drive-disconnect': return window.disconnectDrive().catch(fail); + case 'cloud-ask': await saveUi({ cloud_ask: (S.settings.ui || {}).cloud_ask === false }); return draw(true); + case 'save-provider': return sheet(t('Save destination'), [ + { label: 'RecompStore', sub: t('Enable each game again after changing providers'), run: () => window.chooseSaveProvider('recompstore').catch(fail) }, + { label: 'Google Drive', sub: t('Connect Google Drive first; enable each game again after changing providers'), run: () => S.saveProvider?.google?.connected ? window.chooseSaveProvider('google_drive').catch(fail) : window.connectDrive().catch(fail) }, + ]); case 'account': sfx('open'); if (!(S.account && S.account.signedIn)) return window.signIn && window.signIn(false); From 0f9424f416fb79671e5587fff381df5819dadbb9 Mon Sep 17 00:00:00 2001 From: innateessence Date: Sun, 15 Nov 2026 16:20:04 -0800 Subject: [PATCH 2/8] Fix Drive connection races and add browser smoke checks --- docs/GOOGLE-DRIVE.md | 21 ++++ docs/images/google-drive-big-picture.webp | Bin 0 -> 47740 bytes docs/images/google-drive-desktop.webp | Bin 0 -> 46134 bytes src-tauri/src/drive.rs | 43 +++++++- src-tauri/src/save_provider.rs | 8 +- tests/google-drive.test.cjs | 62 +++++++++++ tools/check-google-drive-ui.cjs | 124 ++++++++++++++++++++++ ui/account.js | 18 ++-- ui/tv.js | 8 +- 9 files changed, 265 insertions(+), 19 deletions(-) create mode 100644 docs/images/google-drive-big-picture.webp create mode 100644 docs/images/google-drive-desktop.webp create mode 100644 tools/check-google-drive-ui.cjs diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md index f5225d86..1c00110b 100644 --- a/docs/GOOGLE-DRIVE.md +++ b/docs/GOOGLE-DRIVE.md @@ -33,6 +33,12 @@ Big Picture has the same connection, provider selection, per-game switch and syn It normally opens the browser on the same PC. Approved limited-input builds can offer a Google device code and QR code for a phone. A phone cannot finish a desktop loopback callback. +The save destination controls in desktop and Big Picture: + +![Desktop save destination settings](images/google-drive-desktop.webp) + +![Google Drive selected in Big Picture](images/google-drive-big-picture.webp) + ## Configuring a release build The project maintainer must configure one Google Cloud project, enable the Drive API, configure @@ -82,6 +88,21 @@ apply to Drive backups too. Downloads are checked against the archive manifest a file hashes before restoration, and archive destinations must match this PC's known save folders (or the folders the player explicitly picked). +## Reviewing the UI without a Google account + +On Linux with Google Chrome installed, run: + +```sh +node tools/check-google-drive-ui.cjs +``` + +Set `RL_UI_CHROME` to another Chrome executable if needed. An optional directory argument chooses +where the check writes its screenshots and results; otherwise it uses a new temporary directory. +It exercises the shipped desktop and Big Picture UI with simulated Tauri responses, including +connection cancellation, missing OAuth configuration, connected account controls, and keyboard navigation. +It never signs into Google or changes your launcher data. The screenshots above use this simulated +state and a sample account address. Native launcher and live Google validation are separate checks. + ## Validation before a public release Run `cargo test --manifest-path src-tauri/Cargo.toml` and `node --test tests/*.test.cjs`. diff --git a/docs/images/google-drive-big-picture.webp b/docs/images/google-drive-big-picture.webp new file mode 100644 index 0000000000000000000000000000000000000000..ff5ef463d5a3eb99cc9f71770af37d26976a6856 GIT binary patch literal 47740 zcmaI5W0Ow}d)l^bbK16T+dXaDwr$(?v~A-#^X`3p-#$OiImwl}S1RjH zs#1R{iISw4m~#gJpe8D$psK*34hsMP2>-QQ2*3##KvGy(VGQJ77XUK$9|_I?0NB_% zJ1U6_5vprw5<=|(K>pSLDh5VQ_WzCkkMbYudF8*ki?sho#{XLhV{GDN^pA4;uaP+Z zTl}9*X#X&p*?(h-|6s%a#ytPQZqD}3|2PW&!H&vG!vC=GKTKivzhT4w4I9}z{)hkP zABV@r+T}lM{ipoLJ2(?tmEZrq(El1PzzLuP5C;hT$Nzu*f5ol<0N{860Knq@M`xH0 z0JMex06#bWM@Nze03Zef04=lsqx+vdu{Uru_^;`}|4C3&Qvl$;6aawN002{u{#mXP4c-Y6h?dm;eX?k^ozP5rFO=VgfJ#7y)emB1{rqBk!B<F5ipZ!axgP z=11x+-UmAHL`&^zcNbXiD+5$}lied<_iOo{^D}?kz4J@+o&PHRjD3&2_WJ;?0)d~M zAMBsC5BO?dRr1Zsc40^98}J!;{;Wx-)HYh@3!yChr<`tXX`irgWe^d5Purb0GRuY`bB<4|8E|k z4*~FN!uQ?}2%Nti{)h(xzuhgS^)&=R+uB;-Bqtz1MwW0ekVA{uIx&#LK@rt46a+w; zr)$$bF&&7*njqjMY2W|q08V&D32+HRyL=X6Cc)h&T`HtcGHN*jNqkEyUkm5+^Iw7KPz#lJ+* z9awYSsdscikaCO;5UNi&HbT~L(Zx%jZ@cZ_`{}WI2Y?%*Q9HBW^hMx1i8HProO)@` zJYI&@f90ga6O}ke5G*mD`6D?v;V9oIT05fiP6Q$f*2K#oWi4yXR8a=A<5Z^o%KO7W zcz;OKl;$>@JU00QV8=}pYl)M{oCCh>_BGJR(xMFl*LI9aZQ;|P-#6{a1P?!XKSWCZ zwM!~h;j(SSvfC=StEO9>tU==A6)p`C>QxLfX4kuk6W-1Q@+T};qy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I%{062_poZQ5B?c!#y?H3^P3Qtd(H~0PRJc8p~LjXMbd9z1MEubQj%% zcUW*6!Eue?bm7X66(EXC_Xhw#08cae=o^jw(y58t7xJ=>4-*5ES~U=tPEuE9(;L~f zUK!C4qRu2bY>CcCx}4mZd*6R?Des@bp#Q5KaK3N-UY~l~HC9yFbTLnir6TqUw7d96 z(uAg0+w1++tYRxwZ0iAcQ=EvWOuoNvAq2u3oHhj5wn*c0NWzu!dMpl!PQFTqO*nHR z-vAM3$2L8g+2cJ^@GH97;gxSwTXWp>i*YU}@1of%xi_YAovG&z z)R;+|QUl_M{aEStzW;|}XpJV=r!49AlUSj`^z=$lcX#HLMIU8nuQ; zcN_1e-TrFI#dk5Rc>$u@(iK)%W6a4VS$DsM-V%gGuNcfT^m0k0( zdE;D&?g{}(5bq3TuNq5WzZZq5vT)ix8=6TjS30A>Uj8+6$|*`>ZXK!{<2Ft2(++-$ z)8ypc_;nxGD!ki-8SBfMVQYO@u;-e`z)dk3jX9AM)pWBLLw4I#SjZc(g>wLjr?T@a zc8E?egH!0g*9%IhLf&$ErgKE3IS2mf3l*Qnwax8_e`{ZU(-A2<5f@X%??=;?(C@Bk z?w5MOadKhJ^Hix=aAS?HAr`ABLt|sjl}w)tIuIW+{5#Z&IiTbAX2IG4rz_VGludy+ zU;(qwWQBsJUa07S?*hH9;1_1o)Ru=P#*pauiKq>_M5Lsr_mqcb{}D1`qL(QO&;QDK zKXga3K?Jcm|9(Rd@&>s`ttW@_tnBg*E%l>B{qAuf8Y)M!NUxLQZMXL6bL7VXz^bX> zPFE;8#APd^_MiBN6^n!CJ~^UGa1>%rSS~+Rh$XFX4n8W#ECGax%d&=-oRd=W+?^yg zH+goqcvCiX6B}ekliNDg Res { if save_provider::current(&st.dir) == save_provider::Provider::GoogleDrive { save_provider::clear_consent(&st)?; } - crate::secret::forget_named(&st.dir, CREDENTIAL)?; - *ACCESS.lock().await = None; - NEEDS_RECONNECT.store(false, Ordering::Relaxed); + disconnect_account(&st.dir).await?; save_provider::emit(&app); - Ok(json!({"state": save_provider::state(&app), "installed": st.lib.lock().unwrap().installed})) + Ok(save_provider::save_provider_state(app.clone())) +} + +async fn disconnect_account(dir: &Path) -> Res<()> { + // A refresh may replace the stored token. Let it finish before removing the credentials. + let mut cached = ACCESS.lock().await; + crate::secret::forget_named(dir, CREDENTIAL)?; + *cached = None; + NEEDS_RECONNECT.store(false, Ordering::Relaxed); + Ok(()) } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -864,6 +871,34 @@ pub async fn download(app: &AppHandle, id: &str, copy: &cloud::CloudCopy) -> Res mod tests { use super::*; + #[cfg(not(windows))] + #[tokio::test] + async fn disconnect_waits_for_refresh_before_removing_credentials() { + let dir = std::env::temp_dir().join(format!("rl-drive-disconnect-{}", random_text().unwrap())); + std::fs::create_dir_all(&dir).unwrap(); + let mut account = Account { + id: "player".into(), + email: "player@example.com".into(), + refresh: "original".into(), + client_id: "client".into(), + client_secret: "secret".into(), + }; + store(&dir, &account).unwrap(); + let mut refresh = ACCESS.lock().await; + *refresh = Some(Access { account: account.id.clone(), token: "access".into(), until: Instant::now() + Duration::from_secs(60) }); + let disconnect = disconnect_account(&dir); + tokio::pin!(disconnect); + assert!(futures_util::poll!(&mut disconnect).is_pending()); + assert!(connected(&dir), "credentials stay until the in-flight refresh finishes"); + account.refresh = "rotated".into(); + store(&dir, &account).unwrap(); + drop(refresh); + disconnect.await.unwrap(); + assert!(!connected(&dir), "a late refresh must not recreate the disconnected account"); + assert!(ACCESS.lock().await.is_none()); + std::fs::remove_dir_all(&dir).unwrap(); + } + fn file(id: &str, hash: &str, generation: u64, parents: &[&str]) -> Remote { Remote { id: id.into(), diff --git a/src-tauri/src/save_provider.rs b/src-tauri/src/save_provider.rs index 2b4c053d..fa56bcdb 100644 --- a/src-tauri/src/save_provider.rs +++ b/src-tauri/src/save_provider.rs @@ -54,12 +54,12 @@ pub fn state(app: &AppHandle) -> Value { #[tauri::command] pub fn save_provider_state(app: AppHandle) -> Value { - state(&app) + let st = app.state::(); + json!({"state": state(&app), "installed": st.lib.lock().unwrap().installed}) } pub fn emit(app: &AppHandle) { - let st = app.state::(); - let _ = app.emit("save-provider", json!({"state": state(app), "installed": st.lib.lock().unwrap().installed})); + let _ = app.emit("save-provider", save_provider_state(app.clone())); } pub fn ensure_idle(st: &App) -> Result<(), Error> { @@ -100,5 +100,5 @@ pub async fn save_provider_set(app: AppHandle, provider: Provider) -> Result { assert.equal(S.library.game.cloud, true); }); +test('refreshing the provider keeps individual games from a shared installation', () => { + const games = readFileSync(join(__dirname, '../ui/games.js'), 'utf8'); + const S = { gameSets: { series: { games: [{ id: 'first', name: 'First' }] } }, library: {}, saves: {} }; + const apply = runInNewContext(games + '\n' + providerHelpers + '\napplySaveProvider', { S, window: {} }); + apply({ state: { provider: 'google_drive' }, installed: { series: { id: 'series', cloud: null, games: { first: { played_secs: 60 } } } } }); + assert.equal(S.library['series--first'].name, 'First'); + assert.equal(S.library['series--first'].cloud, null); + assert.equal(S.library['series--first'].played_secs, 60); +}); + test('Drive sync before play does not need a RecompStore sign-in', async () => { const source = account.slice(account.indexOf('async function beforeCloudPlay('), account.indexOf('async function pickCloudSave(')); const calls = []; @@ -68,3 +79,54 @@ test('Drive conflict choices submit the revision the player reviewed', async () await pick('game', { local: { hash: 'local', when: 100 }, cloud: { v: 'file', revision: 'both-heads', made: 200 } }); assert.deepEqual(calls, [['saves_pick', { id: 'game', keep: 'local', localHash: 'local', cloudVersion: 'file', cloudRevision: 'both-heads' }]]); }); + +function connectionSetup({ pollResults, snapshotError = false }) { + const source = account.slice(account.indexOf('async function connectDrive('), account.indexOf('async function disconnectDrive(')); + const S = { saveProvider: { provider: 'google_drive' }, library: { game: { cloud: true } } }; + const calls = [], timers = [], errors = []; + const box = { isConnected: true, remove() { this.isConnected = false; } }; + const connect = runInNewContext(source + '\nconnectDrive', { + S, window: {}, document: { body: {} }, inTV: () => false, + t: String, tf: String, esc: String, + modal: () => box, + MutationObserver: class { observe() {} }, + setTimeout: (callback) => { timers.push(callback); return timers.length; }, + clearTimeout() {}, + invoke: async (command) => { + calls.push(command); + if (command === 'drive_connect_start') return { url: 'https://accounts.google.com/', device: false, expires: 600 }; + if (command === 'drive_connect_poll') return pollResults.shift(); + if (command === 'save_provider_state') { + if (snapshotError) throw new Error('Could not load the connected account'); + return { state: { provider: 'google_drive' }, installed: { game: { cloud: null } } }; + } + }, + applySaveProvider: (result) => { S.saveProvider = result.state; S.library = result.installed; }, + chooseSaveProvider: async (provider) => calls.push(`choose:${provider}`), + renderAccountBits() {}, toast() {}, fail: (error) => errors.push(String(error)), + }); + return { connect, timers, calls, errors, S, box }; +} + +test('finishing Drive sign-in refreshes consent without changing the provider', async () => { + const setup = connectionSetup({ pollResults: [{ status: 'pending' }, { status: 'ok' }] }); + await setup.connect(); + await setup.timers.shift()(); + await setup.timers.shift()(); + assert.equal(setup.S.library.game.cloud, null); + assert.equal(setup.calls.includes('save_provider_set'), false); + assert.equal(setup.calls.includes('save_provider_state'), true); + assert.equal(setup.calls.includes('choose:google_drive'), true); + assert.deepEqual(setup.errors, []); +}); + +test('errors on a later Drive sign-in poll close the dialog and are reported', async () => { + const setup = connectionSetup({ pollResults: [{ status: 'pending' }, { status: 'ok' }], snapshotError: true }); + await setup.connect(); + await setup.timers.shift()(); + await setup.timers.shift()(); + assert.equal(setup.box.isConnected, false); + assert.equal(setup.calls.includes('drive_connect_cancel'), true); + assert.equal(setup.calls.includes('choose:google_drive'), false); + assert.deepEqual(setup.errors, ['Error: Could not load the connected account']); +}); diff --git a/tools/check-google-drive-ui.cjs b/tools/check-google-drive-ui.cjs new file mode 100644 index 00000000..8e252018 --- /dev/null +++ b/tools/check-google-drive-ui.cjs @@ -0,0 +1,124 @@ +// Exercises the shipped desktop and Big Picture UI with simulated Tauri responses. No Google account is contacted. +const assert = require('node:assert/strict'); +const { spawn, spawnSync } = require('node:child_process'); +const { createServer } = require('node:http'); +const { readFile, mkdir, mkdtemp, writeFile } = require('node:fs/promises'); +const { resolve, extname } = require('node:path'); + +const { tmpdir } = require('node:os'); +const root = resolve(__dirname, '../ui'); +const browser = process.env.RL_UI_CHROME || 'google-chrome-stable'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +(async () => { + if (spawnSync(browser, ['--version']).status !== 0) throw new Error('Set RL_UI_CHROME to a Chrome executable to run this browser smoke check.'); + const output = process.argv[2] ? resolve(process.argv[2]) : await mkdtemp(resolve(tmpdir(), 'rl-drive-ui-')); + await mkdir(output, { recursive: true }); + const server = createServer(async (req, res) => { + const path = resolve(root, '.' + new URL(req.url, 'http://localhost').pathname); + if (!path.startsWith(root + '/') && path !== root) { res.writeHead(403).end(); return; } + try { + const file = path === root ? path + '/index.html' : path; + const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2' }; + res.setHeader('Content-Type', mime[extname(file)] || 'application/octet-stream'); + res.end(await readFile(file)); + } catch (_) { res.writeHead(404).end(); } + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const chrome = spawn(browser, ['--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run', '--disable-background-networking', '--disable-crash-reporter', `--user-data-dir=${output}/profile`, '--remote-debugging-pipe', 'about:blank'], { + stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'], + env: { ...process.env, XDG_CONFIG_HOME: output + '/config', XDG_CACHE_HOME: output + '/cache' }, + }); + let next = 0, bytes = '', session; + const pending = new Map(), errors = []; + chrome.stderr.on('data', (data) => writeFile(output + '/chrome.log', data, { flag: 'a' })); + chrome.stdio[4].on('data', (data) => { + bytes += data; + let end; + while ((end = bytes.indexOf('\0')) >= 0) { + const message = JSON.parse(bytes.slice(0, end)); bytes = bytes.slice(end + 1); + if (message.id) { + const waiter = pending.get(message.id); + if (waiter) { clearTimeout(waiter.timer); pending.delete(message.id); message.error ? waiter.reject(message.error) : waiter.resolve(message.result); } + } + if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails); + } + }); + const send = (method, params = {}, sessionId = session) => new Promise((resolve, reject) => { + const id = ++next; + const timer = setTimeout(() => { pending.delete(id); reject(new Error('Timed out: ' + method)); }, 10000); + pending.set(id, { resolve, reject, timer }); + chrome.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0'); + }); + const evaluate = async (expression) => { + const result = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); + if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails)); + return result.result.value; + }; + try { + const target = await send('Target.createTarget', { url: 'about:blank' }); + session = (await send('Target.attachToTarget', { targetId: target.targetId, flatten: true })).sessionId; + await send('Page.enable'); await send('Runtime.enable'); + await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }); + await send('Page.addScriptToEvaluateOnNewDocument', { source: ` + window.smokeCalls = []; + window.smokeState = { provider: 'recompstore', name: 'RecompStore', connected: false, google: { configured: true, deviceConfigured: false, connected: false } }; + window.smokeInstalled = {}; + const no = async () => {}; + const win = new Proxy({}, { get: (_, name) => name === 'isMaximized' ? async () => false : no }); + window.__TAURI__ = { core: { convertFileSrc: (u) => u, invoke: async (command, args) => { + window.smokeCalls.push([command, args]); + if (command === 'get_state') return { os: 'linux', arch: 'x64', version: '0.90.0-beta.53', site: '', library: window.smokeInstalled, settings: { setup_done: true, data_asked: true, check_updates: false, ui: { lang: 'en', reduce_motion: true, share_usage: false } } }; + if (command === 'get_catalog') return { data: { apps: [], origins: [] } }; + if (command === 'save_provider_state') return { state: window.smokeState, installed: window.smokeInstalled }; + if (command === 'account_state') return { signedIn: false }; + if (command === 'drive_connect_start') return { url: 'https://accounts.google.com/', device: false, expires: 600 }; + if (command === 'drive_connect_poll') return { status: 'pending' }; + if (['easy_setup', 'libraries', 'launcher_notes', 'team_notes', 'trending', 'game_sizes'].includes(command)) return []; + if (['take_link', 'take_setup_asked', 'launcher_update', 'pc_check', 'news', 'ig_info'].includes(command)) return null; + if (command === 'is_handheld') return false; + if (command === 'plugin_list') return { plugins: [], enabled: [] }; + if (command === 'ach_status') return { tester: false }; + return {}; + } }, event: { listen: async () => no }, window: { getCurrentWindow: () => win }, dpi: { PhysicalPosition: class {}, PhysicalSize: class {} } }; + ` }); + await send('Page.navigate', { url: `http://127.0.0.1:${server.address().port}/index.html` }); + await sleep(1300); + await evaluate("S.settings.setup_done = true; S.settings.data_asked = true; S.setTab = 'account'; go('settings');"); + await sleep(350); + const desktop = await evaluate("({ text: document.querySelector('#main').innerText, connect: !!document.querySelector('[data-act=acc-drive-connect]:not(:disabled)'), calls: window.smokeCalls })"); + assert(desktop.connect, 'desktop connection button enabled'); + assert(/save destination/i.test(desktop.text), 'save destination settings rendered'); + await evaluate("document.querySelector('[data-act=acc-drive-connect]').click()"); + await sleep(100); + assert(await evaluate("!!document.querySelector('[data-x=cancel]')"), 'connection dialog opens'); + await evaluate("document.querySelector('[data-x=cancel]').click()"); + await sleep(100); + assert(await evaluate("window.smokeCalls.some(([command]) => command === 'drive_connect_cancel')"), 'closing connection dialog cancels sign-in'); + await evaluate("window.smokeState.google.configured = false; applySaveProvider({state:window.smokeState,installed:{}}); renderAccountBits();"); + assert(await evaluate("document.querySelector('[data-act=acc-drive-connect]').disabled"), 'unconfigured builds disable Google sign-in'); + await evaluate("window.smokeState.google.configured = true; applySaveProvider({state:window.smokeState,installed:{}}); renderAccountBits();"); + await writeFile(output + '/desktop-settings.webp', Buffer.from((await send('Page.captureScreenshot', { format: 'webp', quality: 82 })).data, 'base64')); + await evaluate("window.smokeState = {provider:'google_drive',name:'Google Drive',connected:true,google:{configured:true,connected:true,email:'player@example.com'}}; window.smokeInstalled = {}; applySaveProvider({state:window.smokeState,installed:window.smokeInstalled}); renderAccountBits();"); + await sleep(200); + const connected = await evaluate("({ disconnect: !!document.querySelector('[data-act=acc-drive-disconnect]'), text:document.querySelector('#main').innerText })"); + assert(connected.disconnect, 'connected account has disconnect control'); + assert(connected.text.includes('player@example.com'), 'connected account displayed'); + await evaluate("window.startTV();"); + await sleep(4000); + await evaluate("window.tvGoto('settings');"); + await sleep(650); + const tv = await evaluate("({ text:document.querySelector('#tv').innerText, provider:!!document.querySelector('[data-tvact=save-provider]'), disconnect:!!document.querySelector('[data-tvact=drive-disconnect]') })"); + await writeFile(output + '/tv-debug.json', JSON.stringify({tv,errors,calls:await evaluate('window.smokeCalls')},null,2)); + assert(tv.provider && tv.disconnect, 'Big Picture provider and disconnect controls rendered'); + await send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 }); + await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 }); + await sleep(350); + assert(await evaluate("document.querySelector('[data-tvact=save-provider]').classList.contains('f')"), 'keyboard navigation reaches the save provider control'); + await writeFile(output + '/big-picture-settings.webp', Buffer.from((await send('Page.captureScreenshot', { format: 'webp', quality: 82 })).data, 'base64')); + await writeFile(output + '/results.json', JSON.stringify({ desktop, connected, tv, errors }, null, 2)); + console.log(JSON.stringify({ desktop: 'passed', connected: 'passed', bigPicture: 'passed', errors: errors.map((e) => e.exception?.description || e.text), output })); + if (errors.length) process.exitCode = 1; + } finally { + chrome.kill('SIGTERM'); server.close(); + } +})().catch((error) => { console.error(error); process.exitCode = 1; }); diff --git a/ui/account.js b/ui/account.js index 13868ef7..324c8e01 100644 --- a/ui/account.js +++ b/ui/account.js @@ -21,7 +21,7 @@ const cloudReady = () => !!S.saveProvider?.connected; function applySaveProvider(result) { S.saveProvider = result.state || result; - if (result.installed) S.library = result.installed; + if (result.installed) { S.library = result.installed; expandLib(); } S.saves = {}; S.savesAll = null; if (window.tvSavesReset) window.tvSavesReset(); } @@ -68,20 +68,24 @@ async function connectDrive() { let result; try { result = await invoke('drive_connect_poll'); } catch (e) { result = { status: 'error', error: String(e) }; } if (closed) return; - if (result.status === 'pending' && Date.now() < until) { timer = setTimeout(poll, 1000); return; } + if (result.status === 'pending' && Date.now() < until) { schedule(); return; } closed = true; if (tv) tv.close(true); if (box) box.remove(); if (result.status !== 'ok') { cancel(); return fail(result.error || t('Google sign-in expired. Try connecting again.')); } - await loadSaveProvider(); // The backend may have cleared consent when a different Google account replaced the old one. - const current = await invoke('save_provider_set', { provider: S.saveProvider.provider }); - applySaveProvider(current); + applySaveProvider(await invoke('save_provider_state')); renderAccountBits(); toast(t('Google Drive connected.')); await chooseSaveProvider('google_drive'); }; - timer = setTimeout(() => poll().catch((e) => { cancel(); fail(e); }), 1000); + const schedule = () => { timer = setTimeout(() => poll().catch((e) => { + cancel(); + if (tv) tv.close(true); + if (box) box.remove(); + fail(e); + }), 1000); }; + schedule(); } async function disconnectDrive() { @@ -102,7 +106,7 @@ function saveProviderSection(group, row) { const button = (label, act, disabled = false) => ``; const info = tf('Current destination: {name}. Enable cloud saves separately for each game.', { name: p.name }); const googleHelp = google.needsReconnect ? t('Google Drive needs you to connect again.') : google.connected ? google.email : google.configured ? t('Connect your Google account. Save copies go directly to your Drive.') : t('Google Drive is not configured in this launcher build.'); - return group(t('Save destination'), `

${esc(info)}

` + return group(t('Save Destination'), `

${esc(info)}

` + row('RecompStore', t('Use your RecompStore account for game saves.'), button(p.provider === 'recompstore' ? 'Selected' : 'Use RecompStore', 'provider-recompstore', p.provider === 'recompstore')) + row('Google Drive', googleHelp, `${google.connected ? button('Reconnect', 'drive-connect') + button('Disconnect', 'drive-disconnect') + button(p.provider === 'google_drive' ? 'Selected' : 'Use Google Drive', 'provider-google', p.provider === 'google_drive') : button('Connect Google Drive', 'drive-connect', !google.configured)}`) + row(t('Ask for Each New Game'), t('Ask before enabling cloud saves for a game.'), ``) diff --git a/ui/tv.js b/ui/tv.js index 19ab3dad..f60bb6d4 100644 --- a/ui/tv.js +++ b/ui/tv.js @@ -1396,9 +1396,9 @@ ${S.account && S.account.signedIn ? `` : ``} - ${head(t('Save destination'))} - - + ${head(t('Save Destination'))} + + ${S.saveProvider?.google?.connected ? `` : ''} ${head(t('Display'))} @@ -3173,7 +3173,7 @@ case 'drive-connect': return window.connectDrive().catch(fail); case 'drive-disconnect': return window.disconnectDrive().catch(fail); case 'cloud-ask': await saveUi({ cloud_ask: (S.settings.ui || {}).cloud_ask === false }); return draw(true); - case 'save-provider': return sheet(t('Save destination'), [ + case 'save-provider': return sheet(t('Save Destination'), [ { label: 'RecompStore', sub: t('Enable each game again after changing providers'), run: () => window.chooseSaveProvider('recompstore').catch(fail) }, { label: 'Google Drive', sub: t('Connect Google Drive first; enable each game again after changing providers'), run: () => S.saveProvider?.google?.connected ? window.chooseSaveProvider('google_drive').catch(fail) : window.connectDrive().catch(fail) }, ]); From 568483015fcc60150ef36d7d162cf2cebdab5497 Mon Sep 17 00:00:00 2001 From: innateessence Date: Sun, 15 Nov 2026 17:05:18 -0800 Subject: [PATCH 3/8] Fix Drive archive limits, upload session recovery, and proxies --- docs/GOOGLE-DRIVE-PLAN.md | 162 ++++++++++++++++++++++++++++++++++++++ docs/GOOGLE-DRIVE.md | 5 ++ src-tauri/src/drive.rs | 132 ++++++++++++++++++++++++++++++- src-tauri/src/net.rs | 3 + src-tauri/src/saves.rs | 80 +++++++++++++++++-- 5 files changed, 373 insertions(+), 9 deletions(-) create mode 100644 docs/GOOGLE-DRIVE-PLAN.md diff --git a/docs/GOOGLE-DRIVE-PLAN.md b/docs/GOOGLE-DRIVE-PLAN.md new file mode 100644 index 00000000..f783bbe6 --- /dev/null +++ b/docs/GOOGLE-DRIVE-PLAN.md @@ -0,0 +1,162 @@ +# Google Drive saves completion plan + +Finish `feat/google-drive-saves` so players can use their own Google Drive for saves, +without a RecompStore account, from desktop and Big Picture. Preserve local backups, +explicit consent for each game, and the existing RecompStore save behavior. + +## Branch baseline + +Reconstructed from the branch at `49e81a1`, based on `main` at `b6516ab`: + +- `2cbc5cb` adds the Drive provider, OAuth, storage, save integration, UI and documentation. +- `49e81a1` fixes connection and sync races and adds browser smoke checks. +- The working tree was clean before this plan was added. + +Existing implementation: + +| Area | Files | Behavior already present | +| --- | --- | --- | +| Provider selection | `src-tauri/src/save_provider.rs` | RecompStore default; explicit switch; per-game consent reset; changes blocked while games run or start | +| Google connection | `src-tauri/src/drive.rs`, `secret.rs`, `win.rs` | Browser OAuth with PKCE and loopback callback; optional device flow; refresh; cancellation; separate credentials | +| Drive storage | `src-tauri/src/drive.rs` | Visible `RecompLauncher/Saves` folder; immutable ZIP snapshots; ancestry-based conflicts; resumable upload tickets; retention | +| Save lifecycle | `src-tauri/src/cloud.rs`, `saves.rs` | Check before play; backup/upload after play; retries; provider/account-scoped sync state; archive validation | +| UI | `ui/account.js`, `ui/tv.js` | Connection, provider choice, disconnect, per-game controls, conflict revision, cache refresh | +| Documentation | `docs/GOOGLE-DRIVE.md` and linked help | Player instructions, build variables, storage behavior and manual release checks | + +Code being present does not establish that live Google authorization and storage work. +The existing browser check simulates Tauri responses. + +## Scope and decisions to preserve + +- Players connect an account; the maintainer supplies the OAuth application configuration. +- Request only `drive.file`; saves and credentials go directly to Google. +- RecompStore remains available and remains the default for existing installations. +- Changing provider or active Google account requires enabling games again. Reconnecting + the same Google account should preserve consent. Existing copies stay where they are. +- Disconnect removes this PC's credentials and stops its Drive sync. It preserves local + and remote saves. Global Google revocation remains a separate account action. +- Keep the existing archive format, save discovery, managed-input exclusions, 95 MiB + upload limit, ten local backups and five ordinary remote copies. Preserve unresolved + branches until resolution. Concurrent saves must not be ordered solely by clocks. +- Desktop and Big Picture must expose equivalent actions. Browser authorization on the + same PC is the baseline. Device-code sign-in is conditional on an eligible Google client. +- No new manifest fields, shared input types, downloads, provider migration or library + synchronization through Drive are included in this feature. + +Google documents [desktop OAuth](https://developers.google.com/identity/protocols/oauth2/native-app), +the limited-input flow and its supported scopes in the +[device authorization guide](https://developers.google.com/identity/protocols/oauth2/limited-input-device), +and the narrow file permission in the +[Drive scope guide](https://developers.google.com/workspace/drive/api/guides/api-specific-auth). + +## Work order + +### 1 Make release configuration concrete + +The release workflows currently do not supply the `RL_GOOGLE_*` build variables consumed +by `drive.rs`. As written, those builds leave connection disabled. + +- Wire `RL_GOOGLE_CLIENT_ID` and `RL_GOOGLE_CLIENT_SECRET` into the intended release + builds. Handle the optional device client separately. Keep credential values out of logs. +- Check Windows, Linux and macOS packaging, plus the separate Arch and Flatpak build + paths. Document which distributions ship Drive configuration and make that choice explicit. +- Add a release configuration check so an intended Drive-enabled release cannot silently + ship without its client ID. Ordinary contributor builds should still work without it. +- The maintainer configures the Google project, Drive API, branding, consent audience and + Desktop client. Confirm applicable publishing requirements and connect a real test account. + Repository inspection cannot establish the current state of that external project. + +Completion: a packaged build reports the expected configuration and completes real consent. + +### 2 Verify account isolation and connection lifetime + +Review `drive.rs`, `save_provider.rs` and their callers together. Add focused regressions +for canceled or superseded connections, disconnect during refresh, reconnecting the same +account, replacing it with another account, and switching providers while sync waits. + +Verify that credentials, upload tickets, pending uploads, synced hashes and UI caches cannot +cross account/provider boundaries. Check restart migration from the existing RecompStore +state, grouped installations and games with their own saves. Verify that game startup and +provider changes cannot interleave into an upload to an unintended destination. + +Completion: each transition has an explicit expected consent/state result, and stale work +cannot restore credentials or upload under the wrong account. + +### 3 Prove interrupted uploads recover + +The current tests cover upload offsets and session URL validation, but do not exercise a +complete Drive HTTP exchange. Add a small test transport seam and deterministic local HTTP +tests for the actual upload logic, keeping production destinations fixed. + +Cover partial uploads, restart with a saved ticket, lost success responses, expired sessions, +authentication refresh, throttling, server errors and quota exhaustion. Verify idempotent +completion with the allocated file ID and checksum before creating another snapshot. + +Session invalidation after upload 4xx responses is fixed for both probes and data PUTs, with +the cleared URL persisted for launcher restarts. Quota and authorization messages and transient +retry classification are preserved. Broader end-to-end upload recovery remains to be tested. See +[Google's upload recovery rules](https://developers.google.com/workspace/drive/api/guides/manage-uploads). + +Completion: retry and restart preserve the local copy, eventually complete one intended +snapshot, and expose an actionable state when authorization or storage prevents progress. + +### 4 Prove conflicts and restoration preserve saves + +Exercise concurrent uploads from two and three clients, equal timestamps, clock skew, +identical contents, and another upload arriving while the conflict prompt is open. Test both +choices and a failed upload of the resolution. Review pruning against concurrent changes, +pagination, missing ancestors and externally modified metadata. + +Expand archive regressions where needed for duplicate entries, traversal, symlinks, damaged +contents, wrong game or destination, oversized expansion, and managed-input exclusions. +Check that failed validation leaves live saves untouched and that restoration preserves the +previous local save through the existing backup path. + +Completion: divergent saves stay discoverable until resolved; stale choices cannot silently +resolve unseen changes; an invalid archive cannot change live saves. + +### 5 Finish desktop and Big Picture behavior + +Extend the existing UI checks to cover reconnect-required state, missing configuration, +provider/account changes, cancellation, offline pending uploads, full storage and conflict +resolution. Check keyboard and controller focus, recovery actions and consistent wording. + +Verify actual native browser opening and loopback callbacks on Windows and Linux/Steam Deck, +plus macOS if shipped. Test packaged sandbox behavior for supported Linux distributions. +Only exercise phone authorization with an eligible configured device client. + +Completion: each failure has a usable recovery action in both interfaces, and Drive saves +work while signed out of RecompStore. + +### 6 Validate and prepare the release + +Run the Rust and JavaScript suites and the browser smoke tool. Use two real installations +with the same Google account to upload, restore, play offline, reconnect, interrupt uploads, +create conflicts, resolve each choice, change accounts and disconnect. Include damaged ZIPs, +revoked access, full storage and regression checks for RecompStore-only users. + +Update `docs/GOOGLE-DRIVE.md`, linked help and the next patch notes draft to match the final +behavior. No Drive player release note is present in the current branch. If implementation +adds any developer-writable manifest field or `FEATURES` value, update the schema, matching +SDK docs with an example, and the separate "For the website (SDK guide)" note in the same +commit, as required by `AGENTS.md`. + +Completion: automated checks pass, supported packages contain their intended configuration, +and recorded native/live results establish that saves survive the release scenarios. + +## Validation record + +- The three review findings are fixed: archive limits apply per save location, upload 4xx + responses invalidate persisted sessions, and Drive/OAuth use the launcher's dynamic proxy. +- Regression tests include a launcher-generated backup with 10,001 files in each of two + locations, independent size budgets, rejected uploads, retained sessions after server errors, + and proxy changes on the existing Drive client. +- JavaScript suite: all 271 tests passed after the fixes. +- Rust suite: 667 passed, one ignored. The full suite ran outside the filesystem sandbox + because an existing profile test creates and removes a temporary home-directory folder. +- Browser smoke check: desktop, connected account and Big Picture checks passed with no + reported errors. Artifacts from this run: `/tmp/rl-drive-ui-CgbXpt`. +- Native/live Google checks: still required before public release. + +Resume with step 1. Keep this plan updated with completed steps, concrete findings and test +results so work can resume from the repository after a context reset. diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md index 1c00110b..9f93a019 100644 --- a/docs/GOOGLE-DRIVE.md +++ b/docs/GOOGLE-DRIVE.md @@ -10,6 +10,9 @@ archives using the same `rlsave.json` format as local backups. The launcher requ request access to the rest of your Drive. Files and credentials travel directly to Google; RecompLauncher servers do not receive them. +Google sign-in requests and save transfers follow **Settings → Network → Proxy**. Changes +apply without restarting the launcher, including choosing **Off** to bypass system proxies. + Before play, the launcher checks for another PC's saves. After play it makes a local backup and uploads changed saves. **Sync Now** checks immediately. Offline saves wait on this PC and retry later, including after restarting the launcher. Connect the same Google account @@ -87,6 +90,8 @@ No `recomplauncher.json` changes are needed. Existing `saves` paths and managed- apply to Drive backups too. Downloads are checked against the archive manifest and individual file hashes before restoration, and archive destinations must match this PC's known save folders (or the folders the player explicitly picked). +File-count and total-size limits are checked separately for each save location, matching backup +discovery when a game saves in several folders. ## Reviewing the UI without a Google account diff --git a/src-tauri/src/drive.rs b/src-tauri/src/drive.rs index fb0cb7f5..31b3c765 100644 --- a/src-tauri/src/drive.rs +++ b/src-tauri/src/drive.rs @@ -52,7 +52,7 @@ struct Connection { fn client() -> &'static reqwest::Client { static CLIENT: OnceLock = OnceLock::new(); CLIENT.get_or_init(|| { - reqwest::Client::builder() + crate::net::with_proxy(reqwest::Client::builder()) .redirect(reqwest::redirect::Policy::none()) .connect_timeout(Duration::from_secs(10)) .timeout(Duration::from_secs(300)) @@ -158,7 +158,7 @@ fn api_error(status: u16, body: &Value) -> Error { Error::Msg(format!("Google Drive refused the request ({status}). Check its connection in Settings → Account.")) } -async fn send(app: &AppHandle, request: reqwest::RequestBuilder) -> Res { +async fn send_response(app: &AppHandle, request: reqwest::RequestBuilder) -> Res { let url = request .try_clone() .ok_or_else(|| Error::Msg("Couldn't prepare the Drive request.".into()))? @@ -174,6 +174,10 @@ async fn send(app: &AppHandle, request: reqwest::RequestBuilder) -> Res Res { let status = r.status().as_u16(); if status < 400 { return Ok(r); @@ -182,6 +186,10 @@ async fn send(app: &AppHandle, request: reqwest::RequestBuilder) -> Res Res { + check_response(send_response(app, request).await?).await +} + fn transport_error() -> Error { Error::Net("Google Drive couldn't be reached. Your saves stay on this PC and will retry.".into()) } @@ -659,6 +667,18 @@ fn save_ticket(path: &Path, ticket: &Ticket) -> Res<()> { Ok(()) } +fn invalidate_session(path: &Path, ticket: &mut Ticket, status: u16) -> Res<()> { + if !(400..500).contains(&status) { return Ok(()); } + // Google requires a fresh session after upload 4xx errors, including after a restart. + ticket.url = None; + save_ticket(path, ticket) +} + +async fn upload_response(path: &Path, ticket: &mut Ticket, response: reqwest::Response) -> Res { + invalidate_session(path, ticket, response.status().as_u16())?; + check_response(response).await +} + fn valid_session(url: &str) -> bool { let Ok(url) = reqwest::Url::parse(url) else { return false }; url.scheme() == "https" @@ -706,12 +726,13 @@ async fn upload_bytes(app: &AppHandle, ticket_path: &Path, ticket: &mut Ticket, .send() .await .map_err(transport)?; + invalidate_session(ticket_path, ticket, r.status().as_u16())?; match r.status().as_u16() { 200 | 201 => { return if complete(app, ticket, bytes.len()).await? { Ok(()) } else { Err(transport_error()) }; } 308 => offset = resume_offset(r.headers(), bytes.len())?, - 404 | 410 => ticket.url = None, + 404 | 410 => {}, status => return Err(api_error(status, &r.json().await.unwrap_or(Value::Null))), } } else { @@ -746,7 +767,8 @@ async fn upload_bytes(app: &AppHandle, ticket_path: &Path, ticket: &mut Ticket, .header("Content-Type", "application/zip") .header("Content-Range", format!("bytes {offset}-{}/{total}", total - 1)) .body(bytes[offset..].to_vec()); - let r = send(app, request).await?; + let response = send_response(app, request).await?; + let r = upload_response(ticket_path, ticket, response).await?; if !r.status().is_success() { return Err(transport_error()); } @@ -871,6 +893,34 @@ pub async fn download(app: &AppHandle, id: &str, copy: &cloud::CloudCopy) -> Res mod tests { use super::*; + #[test] + fn drive_client_observes_proxy_changes_without_being_rebuilt() { + let _guard = crate::net::PROXY_TEST_LOCK.lock().unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + runtime.block_on(async { + let proxy = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = proxy.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = proxy.accept().await.unwrap(); + let mut bytes = [0; 4096]; + let count = stream.read(&mut bytes).await.unwrap(); + stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\nproxy").await.unwrap(); + String::from_utf8_lossy(&bytes[..count]).to_string() + }); + let http = client(); + let target = "http://drive-proxy.invalid/save"; + crate::net::set_proxy("custom", &format!("http://{address}"), "", "").unwrap(); + let proxied = http.get(target).timeout(Duration::from_secs(2)).send().await; + crate::net::set_proxy("off", "", "", "").unwrap(); + let direct = http.get(target).timeout(Duration::from_secs(2)).send().await; + crate::net::set_proxy("system", "", "", "").unwrap(); + let request = tokio::time::timeout(Duration::from_secs(3), server).await.unwrap().unwrap(); + assert_eq!(proxied.unwrap().text().await.unwrap(), "proxy"); + assert!(request.starts_with("GET http://drive-proxy.invalid/save HTTP/1.1")); + assert!(direct.is_err(), "turning the proxy off must stop using the existing client connection"); + }); + } + #[cfg(not(windows))] #[tokio::test] async fn disconnect_waits_for_refresh_before_removing_credentials() { @@ -1028,6 +1078,80 @@ mod tests { assert!(!valid_session("https://www.googleapis.com:444/upload/drive/v3/files")); } + fn upload_ticket() -> (PathBuf, Ticket) { + let dir = std::env::temp_dir().join(format!("rl-drive-ticket-{}", random_text().unwrap())); + let path = dir.join("ticket.json"); + let ticket = Ticket { + id: "allocated-file".into(), + archive_hash: "archive-hash".into(), + snapshot: file("allocated-file", "save-hash", 1, &[]).snapshot, + url: Some("https://www.googleapis.com/upload/drive/v3/files?upload_id=expired".into()), + }; + save_ticket(&path, &ticket).unwrap(); + (path, ticket) + } + + fn upload_reply(status: u16, body: Value) -> reqwest::Response { + tauri::http::Response::builder().status(status).body(body.to_string()).unwrap().into() + } + + #[test] + fn invalid_upload_probes_discard_the_persisted_session() { + let (path, mut ticket) = upload_ticket(); + invalidate_session(&path, &mut ticket, 400).unwrap(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(ticket.url.is_none()); + assert!(saved.url.is_none()); + assert_eq!(saved.id, "allocated-file"); + assert_eq!(saved.archive_hash, "archive-hash"); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn rejected_upload_data_discards_the_session_and_reports_quota() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(403, json!({"error": {"errors": [{"reason": "storageQuotaExceeded"}]}})); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(error.to_string().contains("Google Drive storage is full")); + assert!(saved.url.is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn unauthorized_upload_data_discards_the_session_and_requests_reconnect() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(401, Value::Null); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(error.to_string(), RECONNECT); + assert!(saved.url.is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn rate_limited_upload_data_discards_the_session_and_retries() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(403, json!({"error": {"errors": [{"reason": "userRateLimitExceeded"}]}})); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(matches!(error, Error::Net(_))); + assert!(saved.url.is_none()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[tokio::test] + async fn upload_server_errors_preserve_the_session_for_resume() { + let (path, mut ticket) = upload_ticket(); + let response = upload_reply(503, Value::Null); + let error = upload_response(&path, &mut ticket, response).await.unwrap_err(); + let saved: Ticket = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(matches!(error, Error::Net(_))); + assert_eq!(saved.url, ticket.url); + assert!(saved.url.is_some()); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + #[test] fn rate_limit_errors_retry_without_pausing_the_website() { let e = api_error(403, &json!({"error": {"errors": [{"reason": "userRateLimitExceeded"}]}})); diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index fcf6cfb9..0a36498e 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -658,6 +658,8 @@ pub enum Proxy { } static PROXY: std::sync::RwLock> = std::sync::RwLock::new(None); +#[cfg(test)] +pub(crate) static PROXY_TEST_LOCK: Mutex<()> = Mutex::new(()); /// Applies the player's setting: "off", "system" (or empty) or "custom" with its address and /// optional user and password (put into the address, which is how proxies are told). @@ -921,6 +923,7 @@ mod proxy_tests { #[test] fn a_dead_proxy_fails_fast_with_its_address() { + let _guard = PROXY_TEST_LOCK.lock().unwrap(); // Nothing listens on this port: the request through it fails at once (not a hang), and // the error names the proxy. let dead = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index 70a7d343..db2caddd 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -1132,7 +1132,8 @@ fn not_written(path: &Path, e: io::Error) -> Error { pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot]) -> Result<(), Error> { let invalid = || Error::Msg("That cloud save is damaged or doesn't match this game's save folders. Nothing was restored.".into()); let mut zip = zip::ZipArchive::new(fs::File::open(path)?).map_err(|_| invalid())?; - if zip.len() > MAX_FILES + 1 { return Err(invalid()); } + let max_entries = spots.len().saturating_mul(MAX_FILES).saturating_add(1); + if zip.len() > max_entries { return Err(invalid()); } let man: Manifest = { let mut entry = zip.by_name("rlsave.json").map_err(|_| invalid())?; if entry.size() > 8 * 1024 * 1024 { return Err(invalid()); } @@ -1147,13 +1148,11 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot]) -> if man.spots.len() != spots.len() || (!picked && man.spots.iter().zip(spots).any(|(a, b)| a != &b.template)) { return Err(invalid()); } + if !cloud_files_within_limits(&man.files, spots.len()) { return Err(invalid()); } let mut expected = HashMap::new(); - let mut total = 0u64; for file in &man.files { let unsafe_name = file.rel.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p.contains(['\\', ':'])); - if file.spot >= spots.len() || file.size > MAX_FILE || unsafe_name { return Err(invalid()); } - total = total.checked_add(file.size).ok_or_else(invalid)?; - if total > SPOT_MAX { return Err(invalid()); } + if unsafe_name { return Err(invalid()); } let name = format!("{}/{}", file.spot, file.rel); if expected.insert(name, file).is_some() { return Err(invalid()); } } @@ -1182,6 +1181,19 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot]) -> Ok(()) } +fn cloud_files_within_limits(files: &[FileInfo], spots: usize) -> bool { + // Discovery budgets each save location separately, including when one backup covers several. + let mut counts = vec![0usize; spots]; + let mut sizes = vec![0u64; spots]; + for file in files { + if file.spot >= spots || file.size > MAX_FILE { return false; } + counts[file.spot] += 1; + sizes[file.spot] += file.size; + if counts[file.spot] > MAX_FILES || sizes[file.spot] > SPOT_MAX { return false; } + } + true +} + /// Puts a copy's files back where the game reads them, on this PC. Saves that are there now and /// aren't in the copy are taken away, so the game sees exactly what was copied; what was there is /// kept as a copy first, so this can be undone. @@ -1577,6 +1589,64 @@ mod tests { assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_ok()); } + #[test] + fn cloud_copy_accepts_a_backup_with_many_files_across_locations() { + let dir = tmp("cloud-many-files"); + let g = game(&dir); + let spots = vec![ + Spot { template: "{install}/saves-0".into(), from: "developer" }, + Spot { template: "{install}/saves-1".into(), from: "developer" }, + ]; + fs::create_dir_all(dir.join("saves-0")).unwrap(); + fs::create_dir_all(dir.join("saves-1")).unwrap(); + let count = MAX_FILES + 2; + for n in 0..count { + let path = dir.join(format!("saves-{}/slot-{}.sav", n % 2, n / 2)); + fs::write(path, b"save").unwrap(); + } + let copy = backup(&dir, "g", &spots, &g).unwrap().unwrap(); + assert_eq!(copy.files, count); + let archive = dir_of(&dir, "g").join(copy.name); + assert!(validate_cloud_copy(&archive, "g", ©.hash, &spots).is_ok()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn cloud_file_counts_cannot_exceed_one_locations_limit() { + let file = FileInfo { spot: 0, rel: "slot.sav".into(), size: 4, sha256: String::new() }; + let files = vec![file; MAX_FILES + 1]; + assert!(!cloud_files_within_limits(&files, 2)); + } + + #[test] + fn cloud_file_sizes_are_budgeted_per_location() { + let count = (SPOT_MAX / MAX_FILE + 1) as usize; + let files: Vec<_> = (0..count).map(|n| FileInfo { + spot: n % 2, rel: format!("slot-{n}.sav"), size: MAX_FILE, sha256: String::new(), + }).collect(); + assert!(files.iter().map(|f| f.size).sum::() > SPOT_MAX); + assert!(cloud_files_within_limits(&files, 2)); + } + + #[test] + fn cloud_file_sizes_cannot_exceed_one_locations_budget() { + let count = (SPOT_MAX / MAX_FILE + 1) as usize; + let file = FileInfo { spot: 0, rel: "slot.sav".into(), size: MAX_FILE, sha256: String::new() }; + assert!(!cloud_files_within_limits(&vec![file; count], 2)); + } + + #[test] + fn cloud_files_reject_an_unknown_location() { + let file = FileInfo { spot: 2, rel: "slot.sav".into(), size: 4, sha256: String::new() }; + assert!(!cloud_files_within_limits(&[file], 2)); + } + + #[test] + fn cloud_files_reject_a_file_larger_than_the_discovery_limit() { + let file = FileInfo { spot: 0, rel: "slot.sav".into(), size: MAX_FILE + 1, sha256: String::new() }; + assert!(!cloud_files_within_limits(&[file], 1)); + } + #[test] fn cloud_copy_rejects_changed_file_contents() { let dir = tmp("cloud-changed"); From 47de2edfe48138d11b7663d1ee41fff113a48f2a Mon Sep 17 00:00:00 2001 From: innateessence Date: Sun, 15 Nov 2026 17:25:22 -0800 Subject: [PATCH 4/8] Reject unsafe destinations in Google Drive save restores --- docs/GOOGLE-DRIVE-PLAN.md | 8 +- docs/GOOGLE-DRIVE.md | 3 + src-tauri/src/cloud.rs | 2 +- src-tauri/src/saves.rs | 281 ++++++++++++++++++++++++++++++++++++-- 4 files changed, 281 insertions(+), 13 deletions(-) diff --git a/docs/GOOGLE-DRIVE-PLAN.md b/docs/GOOGLE-DRIVE-PLAN.md index f783bbe6..988fbecf 100644 --- a/docs/GOOGLE-DRIVE-PLAN.md +++ b/docs/GOOGLE-DRIVE-PLAN.md @@ -148,11 +148,17 @@ and recorded native/live results establish that saves survive the release scenar - The three review findings are fixed: archive limits apply per save location, upload 4xx responses invalidate persisted sessions, and Drive/OAuth use the launcher's dynamic proxy. +- Drive restores also reject non-save entries, installed release files, selected launch programs, + managed inputs, mismatched file/glob destinations and links in destination or staging paths. + The complete archive is validated before any backup or live restore begins. - Regression tests include a launcher-generated backup with 10,001 files in each of two locations, independent size budgets, rejected uploads, retained sessions after server errors, and proxy changes on the existing Drive client. +- Restore regressions reject forged executable replacements with matching hashes and confirm + that a later invalid archive entry leaves earlier saves untouched. Valid file, glob and nested + folder restores still pass; release files, managed inputs and linked staging paths stay intact. - JavaScript suite: all 271 tests passed after the fixes. -- Rust suite: 667 passed, one ignored. The full suite ran outside the filesystem sandbox +- Rust suite: 684 passed, one ignored. The full suite ran outside the filesystem sandbox because an existing profile test creates and removes a temporary home-directory folder. - Browser smoke check: desktop, connected account and Big Picture checks passed with no reported errors. Artifacts from this run: `/tmp/rl-drive-ui-CgbXpt`. diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md index 9f93a019..0554f35d 100644 --- a/docs/GOOGLE-DRIVE.md +++ b/docs/GOOGLE-DRIVE.md @@ -90,6 +90,9 @@ No `recomplauncher.json` changes are needed. Existing `saves` paths and managed- apply to Drive backups too. Downloads are checked against the archive manifest and individual file hashes before restoration, and archive destinations must match this PC's known save folders (or the folders the player explicitly picked). +Each entry must also pass the save-file exclusions and match its local file or wildcard template. +Installed release files, selected launch programs and managed inputs are protected from replacement. +Links in restore destinations or staging paths are rejected before any live saves are changed. File-count and total-size limits are checked separately for each save location, matching backup discovery when a game saves in several folders. diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index 48d6ec56..2d64ae5a 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -1255,7 +1255,7 @@ async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&s let hash = c.hash.clone(); let drive = using_drive(&st.dir); let n = blocking(move || { - if drive { saves::validate_cloud_copy(&t2, &id2, &hash, &spots)?; } + if drive { saves::validate_cloud_copy(&t2, &id2, &hash, &spots, &g)?; } match checked { Some(h) => saves::restore_if_unchanged(&dir, &id2, &t2, &spots, &g, &h), None => saves::restore(&dir, &id2, &t2, &spots, &g), diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index db2caddd..c6f97154 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -1129,7 +1129,7 @@ fn not_written(path: &Path, e: io::Error) -> Error { /// Drive files can be edited outside the launcher. Check every byte before changing live saves, /// and only allow destinations this PC already knows belong to the game. -pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot]) -> Result<(), Error> { +pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot], g: &Installed) -> Result<(), Error> { let invalid = || Error::Msg("That cloud save is damaged or doesn't match this game's save folders. Nothing was restored.".into()); let mut zip = zip::ZipArchive::new(fs::File::open(path)?).map_err(|_| invalid())?; let max_entries = spots.len().saturating_mul(MAX_FILES).saturating_add(1); @@ -1149,10 +1149,20 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot]) -> return Err(invalid()); } if !cloud_files_within_limits(&man.files, spots.len()) { return Err(invalid()); } + let release = crate::inputs::release_files(g); + let manual_exe = g.manual.as_ref().and_then(|m| m.exe.as_ref()); + let mut protected = HashSet::new(); + for file in release.iter().chain(g.exe.iter()).chain(manual_exe) { + let path = g.path.join(file); + protected.insert(lower(&path)); + if let Ok(real) = path.canonicalize() { protected.insert(lower(&real)); } + } let mut expected = HashMap::new(); for file in &man.files { - let unsafe_name = file.rel.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p.contains(['\\', ':'])); - if unsafe_name { return Err(invalid()); } + let (dest, base) = cloud_destination(file, &spots[file.spot], g).ok_or_else(invalid)?; + if !cloud_destination_allowed(&dest, &base, g, &protected) { return Err(invalid()); } + // Restore stages beside the destination; that write must not replace a protected file either. + if !cloud_destination_allowed(&dest.with_extension("rl-part"), &base, g, &protected) { return Err(invalid()); } let name = format!("{}/{}", file.spot, file.rel); if expected.insert(name, file).is_some() { return Err(invalid()); } } @@ -1181,6 +1191,52 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot]) -> Ok(()) } +pub fn restore_cloud_copy(app_dir: &Path, id: &str, path: &Path, hash: &str, spots: &[Spot], g: &Installed) -> Result { + validate_cloud_copy(path, id, hash, spots, g)?; + restore(app_dir, id, path, spots, g) +} + +fn cloud_destination(file: &FileInfo, spot: &Spot, g: &Installed) -> Option<(PathBuf, PathBuf)> { + if !plain_save_path(&file.rel) { return None; } + // Windows strips these suffixes, which could disguise an installed program's filename. + if file.rel.split('/').any(|p| p.ends_with(['.', ' '])) { return None; } + let relative = Path::new(&file.rel); + let name = relative.file_name()?.to_str()?; + if !is_save_file(name, file.size) { return None; } + if relative.parent()?.components().any(|c| skip_dir(&c.as_os_str().to_string_lossy())) { return None; } + let root = resolve_for(&spot.template, g); + let last = root.file_name()?.to_str()?; + if spot.from == "player" { return Some((root.join(relative), root)); } + if last.contains('*') { + if file.rel.contains('/') || !wild(last, &file.rel) { return None; } + let base = root.parent()?.to_path_buf(); + return Some((base.join(relative), base)); + } + if root.is_file() && file.rel != last { return None; } + if file.rel == last && !root.is_dir() { + let base = root.parent()?.to_path_buf(); + return Some((root, base)); + } + Some((root.join(relative), root)) +} + +fn cloud_destination_allowed(path: &Path, base: &Path, g: &Installed, protected: &HashSet) -> bool { + if protected.contains(&lower(path)) || crate::inputs::excluded(g, path) { return false; } + if path.canonicalize().is_ok_and(|p| protected.contains(&lower(&p))) { return false; } + // A save subfolder or staging path may be a link to a program outside the named location. + for parent in path.ancestors() { + match fs::symlink_metadata(parent) { + Ok(m) if is_save_link(&m) => return false, + Ok(m) if parent == path && !m.is_file() => return false, + Ok(m) if parent != path && !m.is_dir() => return false, + Err(e) if e.kind() != io::ErrorKind::NotFound => return false, + _ => {}, + } + if parent == base { break; } + } + true +} + fn cloud_files_within_limits(files: &[FileInfo], spots: usize) -> bool { // Discovery budgets each save location separately, including when one backup covers several. let mut counts = vec![0usize; spots]; @@ -1567,7 +1623,11 @@ pub fn share_save(app_dir: &Path, id: &str, spot: &Spot, g: &Installed, source: #[cfg(test)] mod tests { fn cloud_archive(dir: &Path, template: &str, data: &[u8], actual: &[u8]) -> (PathBuf, String) { - let files = vec![FileInfo { spot: 0, rel: "slot.sav".into(), size: data.len() as u64, sha256: hex::encode(Sha256::digest(data)) }]; + cloud_archive_named(dir, template, "slot.sav", data, actual) + } + + fn cloud_archive_named(dir: &Path, template: &str, rel: &str, data: &[u8], actual: &[u8]) -> (PathBuf, String) { + let files = vec![FileInfo { spot: 0, rel: rel.into(), size: data.len() as u64, sha256: hex::encode(Sha256::digest(data)) }]; let hash = set_hash(&files); let manifest = Manifest { format: 1, game: "g".into(), hash: hash.clone(), spots: vec![template.into()], files, ..Default::default() }; let path = dir.join("cloud.zip"); @@ -1575,7 +1635,7 @@ mod tests { let options = zip::write::SimpleFileOptions::default(); zip.start_file("rlsave.json", options).unwrap(); zip.write_all(&serde_json::to_vec(&manifest).unwrap()).unwrap(); - zip.start_file("0/slot.sav", options).unwrap(); + zip.start_file(format!("0/{rel}"), options).unwrap(); zip.write_all(actual).unwrap(); zip.finish().unwrap(); (path, hash) @@ -1586,7 +1646,206 @@ mod tests { let dir = tmp("cloud-valid"); let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); - assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_ok()); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_ok()); + } + + #[test] + fn cloud_restore_rejects_an_executable_with_matching_hashes() { + let dir = tmp("cloud-executable"); + fs::write(dir.join("game.exe"), b"installed program").unwrap(); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "game.exe", b"replacement", b"replacement"); + let app = dir.join("app"); + assert!(restore_cloud_copy(&app, "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("game.exe")).unwrap(), b"installed program"); + assert!(!app.exists(), "validation must finish before backups or live save changes"); + } + + #[test] + fn cloud_restore_validates_every_entry_before_changing_live_saves() { + let dir = tmp("cloud-all-entries"); + fs::write(dir.join("slot.sav"), b"local save").unwrap(); + fs::write(dir.join("game.exe"), b"installed program").unwrap(); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let data = b"replacement"; + let files = ["slot.sav", "game.exe"].map(|rel| FileInfo { + spot: 0, rel: rel.into(), size: data.len() as u64, sha256: hex::encode(Sha256::digest(data)), + }); + let hash = set_hash(&files); + let manifest = Manifest { + format: 1, game: "g".into(), hash: hash.clone(), spots: vec!["{install}".into()], files: files.to_vec(), ..Default::default() + }; + let path = dir.join("cloud.zip"); + let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("rlsave.json", options).unwrap(); + zip.write_all(&serde_json::to_vec(&manifest).unwrap()).unwrap(); + for file in &files { + zip.start_file(format!("0/{}", file.rel), options).unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("slot.sav")).unwrap(), b"local save"); + assert_eq!(fs::read(dir.join("game.exe")).unwrap(), b"installed program"); + assert!(!dir.join("app").exists()); + } + + #[test] + fn cloud_restore_rejects_an_installed_data_file_in_a_named_folder() { + let dir = tmp("cloud-release-data"); + fs::create_dir(dir.join("data")).unwrap(); + fs::write(dir.join("data/a.bin"), b"installed data").unwrap(); + let spots = vec![Spot { template: "{install}/data".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "a.bin", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("data/a.bin")).unwrap(), b"installed data"); + } + + #[test] + fn cloud_restore_rejects_an_imported_extensionless_program() { + let dir = tmp("cloud-imported-program"); + fs::write(dir.join("launch-game"), b"installed program").unwrap(); + let g = Installed { exe: Some("launch-game".into()), files: vec![], ..game(&dir) }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "launch-game", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(dir.join("launch-game")).unwrap(), b"installed program"); + } + + #[test] + fn cloud_restore_rejects_a_program_named_by_manual_setup() { + let dir = tmp("cloud-manual-program"); + let program = dir.join("launch-game"); + fs::write(&program, b"manual program").unwrap(); + let manual = crate::library::ManualSetup { exe: Some(program.clone()), ..Default::default() }; + let g = Installed { manual: Some(manual), files: vec![], ..game(&dir) }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "launch-game", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(program).unwrap(), b"manual program"); + } + + #[test] + fn cloud_restore_rejects_a_filename_outside_the_save_glob() { + let dir = tmp("cloud-glob-mismatch"); + fs::write(dir.join("settings.toml"), b"local settings").unwrap(); + let spots = vec![Spot { template: "{install}/*.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "settings.toml", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("settings.toml")).unwrap(), b"local settings"); + } + + #[test] + fn cloud_restore_rejects_nested_paths_in_a_save_glob() { + let dir = tmp("cloud-glob-nested"); + let spots = vec![Spot { template: "{install}/*.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "nested/slot.sav", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert!(!dir.join("nested").exists()); + } + + #[test] + fn cloud_restore_rejects_a_different_name_for_a_single_save_file() { + let dir = tmp("cloud-file-mismatch"); + fs::write(dir.join("only.sav"), b"local save").unwrap(); + let spots = vec![Spot { template: "{install}/only.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("only.sav")).unwrap(), b"local save"); + } + + #[test] + fn cloud_restore_accepts_a_matching_glob_file() { + let dir = tmp("cloud-glob-valid"); + let spots = vec![Spot { template: "{install}/*.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).unwrap(), 1); + assert_eq!(fs::read(dir.join("slot.sav")).unwrap(), b"save"); + } + + #[test] + fn cloud_restore_accepts_a_missing_single_save_file() { + let dir = tmp("cloud-file-valid"); + let spots = vec![Spot { template: "{install}/slot.sav".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).unwrap(), 1); + assert_eq!(fs::read(dir.join("slot.sav")).unwrap(), b"save"); + } + + #[test] + fn cloud_restore_accepts_nested_saves_in_a_missing_folder() { + let dir = tmp("cloud-folder-valid"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "profile/slot.sav", b"save", b"save"); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).unwrap(), 1); + assert_eq!(fs::read(dir.join("saves/profile/slot.sav")).unwrap(), b"save"); + } + + #[test] + fn cloud_restore_rejects_files_from_excluded_subfolders() { + let dir = tmp("cloud-excluded-folder"); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "mods/slot.sav", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert!(!dir.join("mods").exists()); + } + + #[test] + fn cloud_restore_rejects_a_managed_input_with_a_custom_name() { + let dir = tmp("cloud-managed-input"); + fs::write(dir.join("secret.dat"), b"managed input").unwrap(); + let mut g = game(&dir); + g.input_staged.insert("keys".into(), "secret.dat".into()); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "secret.dat", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(dir.join("secret.dat")).unwrap(), b"managed input"); + } + + #[test] + fn cloud_restore_rejects_windows_filename_suffix_aliases() { + let dir = tmp("cloud-filename-alias"); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive_named(&dir, "{install}", "game.exe. ", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + } + + #[test] + fn cloud_restore_cannot_stage_over_an_installed_release_file() { + let dir = tmp("cloud-stage-release"); + fs::write(dir.join("slot.rl-part"), b"installed data").unwrap(); + let g = Installed { files: vec!["slot.rl-part".into()], ..game(&dir) }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive(&dir, "{install}", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); + assert_eq!(fs::read(dir.join("slot.rl-part")).unwrap(), b"installed data"); + } + + #[cfg(unix)] + #[test] + fn cloud_restore_rejects_a_link_in_the_destination_path() { + let dir = tmp("cloud-folder-link"); + fs::create_dir(dir.join("saves")).unwrap(); + fs::create_dir(dir.join("outside")).unwrap(); + fs::write(dir.join("outside/slot.sav"), b"outside data").unwrap(); + std::os::unix::fs::symlink(dir.join("outside"), dir.join("saves/profile")).unwrap(); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive_named(&dir, &spots[0].template, "profile/slot.sav", b"replacement", b"replacement"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("outside/slot.sav")).unwrap(), b"outside data"); + } + + #[cfg(unix)] + #[test] + fn cloud_restore_rejects_a_link_at_the_staging_path() { + let dir = tmp("cloud-stage-link"); + fs::write(dir.join("outside.dat"), b"outside data").unwrap(); + std::os::unix::fs::symlink(dir.join("outside.dat"), dir.join("slot.rl-part")).unwrap(); + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let (path, hash) = cloud_archive(&dir, "{install}", b"save", b"save"); + assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &game(&dir)).is_err()); + assert_eq!(fs::read(dir.join("outside.dat")).unwrap(), b"outside data"); } #[test] @@ -1607,7 +1866,7 @@ mod tests { let copy = backup(&dir, "g", &spots, &g).unwrap().unwrap(); assert_eq!(copy.files, count); let archive = dir_of(&dir, "g").join(copy.name); - assert!(validate_cloud_copy(&archive, "g", ©.hash, &spots).is_ok()); + assert!(validate_cloud_copy(&archive, "g", ©.hash, &spots, &g).is_ok()); fs::remove_dir_all(dir).unwrap(); } @@ -1652,7 +1911,7 @@ mod tests { let dir = tmp("cloud-changed"); let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"evil"); - assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_err()); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_err()); } #[test] @@ -1660,7 +1919,7 @@ mod tests { let dir = tmp("cloud-redirect"); let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; let (path, hash) = cloud_archive(&dir, "{home}/Documents", b"save", b"save"); - assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_err()); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_err()); } #[test] @@ -1668,7 +1927,7 @@ mod tests { let dir = tmp("cloud-player-folder"); let spots = vec![Spot { template: "{home}/my-saves".into(), from: "player" }]; let (path, hash) = cloud_archive(&dir, "{home}/other-pc-saves", b"save", b"save"); - assert!(validate_cloud_copy(&path, "g", &hash, &spots).is_ok()); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_ok()); } #[test] @@ -1676,7 +1935,7 @@ mod tests { let dir = tmp("cloud-game"); let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); - assert!(validate_cloud_copy(&path, "another-game", &hash, &spots).is_err()); + assert!(validate_cloud_copy(&path, "another-game", &hash, &spots, &game(&dir)).is_err()); } #[test] From 5733742ecc890603f7eaa5d224a3a3b9263e4109 Mon Sep 17 00:00:00 2001 From: innateessence Date: Sun, 15 Nov 2026 17:51:09 -0800 Subject: [PATCH 5/8] Fix Drive pruning, cloud conflict resolution, and manifest limits --- docs/GOOGLE-DRIVE-PLAN.md | 10 +++- docs/GOOGLE-DRIVE.md | 4 ++ src-tauri/src/cloud.rs | 101 +++++++++++++++++++++++++++++++++----- src-tauri/src/drive.rs | 46 +++++++++++++++-- src-tauri/src/saves.rs | 42 ++++++++++++++-- 5 files changed, 180 insertions(+), 23 deletions(-) diff --git a/docs/GOOGLE-DRIVE-PLAN.md b/docs/GOOGLE-DRIVE-PLAN.md index 988fbecf..440b5223 100644 --- a/docs/GOOGLE-DRIVE-PLAN.md +++ b/docs/GOOGLE-DRIVE-PLAN.md @@ -151,14 +151,20 @@ and recorded native/live results establish that saves survive the release scenar - Drive restores also reject non-save entries, installed release files, selected launch programs, managed inputs, mismatched file/glob destinations and links in destination or staging paths. The complete archive is validated before any backup or live restore begins. -- Regression tests include a launcher-generated backup with 10,001 files in each of two +- Pruning removes discarded ancestors oldest-first, preserving the head set after each deletion. + Choosing a cloud branch resolves from its validated archive even when extra local slots remain. + Manifest validation budgets entries, paths and locations instead of using a fixed 8 MiB cap. +- Regression tests include a launcher-generated backup with 20,000 files in each of two locations, independent size budgets, rejected uploads, retained sessions after server errors, and proxy changes on the existing Drive client. +- Further regressions cover interruption after each pruned ancestor, unresolved branch retention, + cloud resolution and retry with retained local slots, a large manifest with 100-character + filenames, and rejection of a compressed manifest padded out of proportion to its files. - Restore regressions reject forged executable replacements with matching hashes and confirm that a later invalid archive entry leaves earlier saves untouched. Valid file, glob and nested folder restores still pass; release files, managed inputs and linked staging paths stay intact. - JavaScript suite: all 271 tests passed after the fixes. -- Rust suite: 684 passed, one ignored. The full suite ran outside the filesystem sandbox +- Rust suite: 689 passed, one ignored. The full suite ran outside the filesystem sandbox because an existing profile test creates and removes a temporary home-directory folder. - Browser smoke check: desktop, connected account and Big Picture checks passed with no reported errors. Artifacts from this run: `/tmp/rl-drive-ui-CgbXpt`. diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md index 0554f35d..4a62ae81 100644 --- a/docs/GOOGLE-DRIVE.md +++ b/docs/GOOGLE-DRIVE.md @@ -20,6 +20,8 @@ on each PC and enable the same games there. When both PCs changed their saves, choose which to use. Simultaneous uploads are tracked by snapshot ancestry, rather than assuming the PC with the later clock has the right save. +Choosing the cloud copy resolves from that snapshot, even when restoring into the game's +install folder retains extra local save slots. Those extra slots stay on this PC. The other copies remain available in the Saves tab. The newest five ordinary cloud copies are kept; unresolved branches retain their history until resolved. Removed old copies go to Drive's Trash, which still uses Google storage until emptied. Local backups retain their @@ -95,6 +97,8 @@ Installed release files, selected launch programs and managed inputs are protect Links in restore destinations or staging paths are rejected before any live saves are changed. File-count and total-size limits are checked separately for each save location, matching backup discovery when a game saves in several folders. +The manifest budget scales with the archive's entry count and path lengths, including full +backups from multiple save locations. Unrelated excess manifest data is still rejected. ## Reviewing the UI without a Google account diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index 2d64ae5a..f2e02058 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -1216,7 +1216,7 @@ fn open_sessions(saves_dir: &Path) -> Vec { /// `checked`: the checksum of the saves the caller looked at before deciding. Then the copy goes /// in only over those saves, not over ones made while it downloaded. None: the player picked /// this cloud save themselves, over whatever is there. -async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&str>) -> Res { +async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&str>, resolve: bool) -> Res { let st = app.state::(); let scope = crate::save_provider::scope(&st.dir); let _working = working(app, id, "down"); @@ -1254,15 +1254,19 @@ async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&s let checked = checked.map(String::from); let hash = c.hash.clone(); let drive = using_drive(&st.dir); - let n = blocking(move || { - if drive { saves::validate_cloud_copy(&t2, &id2, &hash, &spots, &g)?; } - match checked { + let n = if drive { + restore_drive_copy(dir, id2, t2, hash, spots, g, checked, |archive| async move { + if resolve { crate::drive::upload(app, id, &archive, Some(&c.revision)).await?; } + Ok(()) + }).await + } else { + blocking(move || match checked { Some(h) => saves::restore_if_unchanged(&dir, &id2, &t2, &spots, &g, &h), None => saves::restore(&dir, &id2, &t2, &spots, &g), - } - }).await; + }).await.and_then(|n| n) + }; let _ = tokio::fs::remove_file(&tmp).await; - let n = n??; + let n = n?; let mut s = saves::state(&st.dir, id); // The save is in place either way; only the new account's notes must not claim it as synced. if crate::save_provider::scope(&st.dir) != scope { @@ -1291,6 +1295,25 @@ fn incoming<'a>(s: &saves::State, list: &'a [CloudCopy]) -> Option<&'a CloudCopy should_restore(&s.last_hash, &s.synced_hash, &top.hash, false).then_some(top) } +async fn restore_drive_copy(dir: PathBuf, id: String, archive: PathBuf, hash: String, spots: Vec, g: Installed, checked: Option, resolve: F) -> Res +where + F: FnOnce(PathBuf) -> Fut, + Fut: std::future::Future>, +{ + let path = archive.clone(); + let restored = blocking(move || { + saves::validate_cloud_copy(&path, &id, &hash, &spots, &g)?; + match checked { + Some(h) => saves::restore_if_unchanged(&dir, &id, &path, &spots, &g, &h), + None => saves::restore_cloud_copy(&dir, &id, &path, &hash, &spots, &g), + } + }).await??; + // The install-folder fallback retains extra local slots. Resolve the chosen archive itself, + // rather than requiring those live files to match the cloud branch exactly. + resolve(archive).await?; + Ok(restored) +} + fn current_copy<'a>(list: &'a [CloudCopy], local: &str) -> Option<&'a CloudCopy> { let top = list.first()?; if !top.conflict { return Some(top); } @@ -1464,7 +1487,7 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { let why = format!("{PROGRAM_OPEN_PLAY}\n{program}"); return Ok(json!({"action": "not-restored", "why": why, "cloud": top})); } - let taken = take_cloud(&app, &id, top, Some(&local)).await; + let taken = take_cloud(&app, &id, top, Some(&local), false).await; // Sync Now says why. Before Play the player is asked whether to play with this PC's save // instead (saves_play_without_cloud); nothing about the sync changes until they say so. if let (Err(e), false) = (&taken, manual) { @@ -1565,10 +1588,8 @@ pub async fn saves_pick(app: AppHandle, id: String, keep: String, local_hash: St } match keep.as_str() { "cloud" => { - take_cloud(&app, &id, top, Some(&hash)).await?; - if using_drive(&st.dir) && top.conflict { - return upload_current(&app, &id, g, spots, top.hash.clone(), top.made, Some(&top.revision)).await; - } + let resolve = using_drive(&st.dir) && top.conflict; + take_cloud(&app, &id, top, Some(&hash), resolve).await?; Ok(()) } "local" => upload_current(&app, &id, g, spots, hash, top.made, Some(&top.revision)).await, @@ -2022,7 +2043,7 @@ pub async fn saves_restore(app: AppHandle, id: String, name: Option, v: if let Some(v) = v { let (list, _) = cloud_list(&app, &id).await?; let c = list.into_iter().find(|c| c.v == v).ok_or_else(|| Error::Msg("That cloud save is gone.".into()))?; - return take_cloud(&app, &id, &c, None).await; + return take_cloud(&app, &id, &c, None, false).await; } let name = name.unwrap_or_default(); if name.contains('/') || name.contains('\\') || !name.ends_with(".zip") { @@ -3083,6 +3104,60 @@ mod home_tests { mod provider_conflict_tests { use super::*; + #[tokio::test] + async fn cloud_resolution_uses_the_selected_archive_when_local_slots_remain() { + let dir = std::env::temp_dir().join(format!("rl-cloud-resolution-retained-{}", std::process::id())); + let app = dir.join("app"); + let install = dir.join("game"); + std::fs::create_dir_all(&install).unwrap(); + std::fs::write(install.join("slot.sav"), b"cloud save").unwrap(); + let g = Installed { id: "g".into(), path: install.clone(), ..Default::default() }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); + let archive = saves::dir_of(&app, "g").join(&chosen.name); + let expected = archive.clone(); + std::fs::write(install.join("slot.sav"), b"local change").unwrap(); + std::fs::write(install.join("extra.sav"), b"extra local slot").unwrap(); + let local_hash = saves::current(&spots, &g).2; + let result = restore_drive_copy(app.clone(), "g".into(), archive, chosen.hash.clone(), spots.clone(), g.clone(), |upload| async move { + assert_eq!(upload, expected); + assert_eq!(saves::manifest(&upload).unwrap().hash, chosen.hash); + assert_ne!(saves::current(&spots, &g).2, chosen.hash, "retained slots must not change the archive used for resolution"); + Ok(()) + }).await.unwrap(); + assert_eq!(result, 1); + assert_eq!(std::fs::read(install.join("slot.sav")).unwrap(), b"cloud save"); + assert_eq!(std::fs::read(install.join("extra.sav")).unwrap(), b"extra local slot"); + assert!(saves::list(&app, "g").iter().any(|c| c.hash == local_hash)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn interrupted_cloud_resolution_can_retry_with_retained_local_slots() { + let dir = std::env::temp_dir().join(format!("rl-cloud-resolution-retry-{}", std::process::id())); + let app = dir.join("app"); + let install = dir.join("game"); + std::fs::create_dir_all(&install).unwrap(); + std::fs::write(install.join("slot.sav"), b"cloud save").unwrap(); + let g = Installed { id: "g".into(), path: install.clone(), ..Default::default() }; + let spots = vec![Spot { template: "{install}".into(), from: "game" }]; + let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); + let archive = saves::dir_of(&app, "g").join(&chosen.name); + std::fs::write(install.join("extra.sav"), b"extra local slot").unwrap(); + saves::set_state(&app, "g", &saves::State { synced_hash: "previous-cloud".into(), ..Default::default() }); + let interrupted = restore_drive_copy(app.clone(), "g".into(), archive.clone(), chosen.hash.clone(), spots.clone(), g.clone(), |_| async { + Err(Error::Net("interrupted resolution".into())) + }).await; + assert!(matches!(interrupted, Err(Error::Net(_)))); + assert_eq!(saves::state(&app, "g").synced_hash, "previous-cloud"); + restore_drive_copy(app, "g".into(), archive, chosen.hash.clone(), spots, g, |upload| async move { + assert_eq!(saves::manifest(&upload).unwrap().hash, chosen.hash); + Ok(()) + }).await.unwrap(); + assert_eq!(std::fs::read(install.join("extra.sav")).unwrap(), b"extra local slot"); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn a_drive_conflict_offers_the_other_devices_save() { let list = vec![ diff --git a/src-tauri/src/drive.rs b/src-tauri/src/drive.rs index 31b3c765..290f1a29 100644 --- a/src-tauri/src/drive.rs +++ b/src-tauri/src/drive.rs @@ -852,14 +852,20 @@ pub async fn upload(app: &AppHandle, id: &str, path: &Path, resolution: Option<& Ok(()) } -async fn prune(app: &AppHandle, files: &[Remote]) { +fn prune_candidates(files: &[Remote]) -> Vec<&Remote> { // Conflicting branches and their ancestry are retained until the player resolves them. if heads(files).len() != 1 { - return; + return Vec::new(); } let mut ordered: Vec<_> = files.iter().collect(); - ordered.sort_by_key(|f| std::cmp::Reverse(f.snapshot.generation)); - for file in ordered.into_iter().skip(5) { + ordered.sort_by_key(|f| f.snapshot.generation); + ordered.truncate(files.len().saturating_sub(5)); + ordered +} + +async fn prune(app: &AppHandle, files: &[Remote]) { + // Removing older parents first keeps the head set intact if a later request fails. + for file in prune_candidates(files) { let request = client().patch(format!("{API}/files/{}", file.id)).timeout(Duration::from_secs(20)).json(&json!({"trashed": true})); if send(app, request).await.is_err() { break; @@ -1006,6 +1012,38 @@ mod tests { assert_eq!(copies(&files)[0].v, "five"); } + #[test] + fn interrupted_pruning_preserves_the_head_after_every_deletion() { + let mut files = Vec::new(); + for generation in 1..=7 { + let id = format!("v{generation}"); + let parent = format!("v{}", generation - 1); + let parents = if generation == 1 { vec![] } else { vec![parent.as_str()] }; + files.push(file(&id, &id, generation, &parents)); + } + files.reverse(); + let expected = revision(&files); + let discarded: Vec<_> = prune_candidates(&files).iter().map(|f| f.id.clone()).collect(); + assert_eq!(discarded, ["v1", "v2"]); + for id in discarded { + files.retain(|f| f.id != id); + assert_eq!(revision(&files), expected); + assert_eq!(heads(&files)[0].id, "v7"); + assert!(!copies(&files)[0].conflict); + } + assert_eq!(files.len(), 5); + } + + #[test] + fn pruning_keeps_unresolved_branches_and_their_ancestors() { + let files = vec![ + file("v1", "old", 1, &[]), file("v2", "old", 2, &["v1"]), + file("v3", "old", 3, &["v2"]), file("v4", "old", 4, &["v3"]), + file("pc", "pc-save", 5, &["v4"]), file("deck", "deck-save", 5, &["v4"]), + ]; + assert!(prune_candidates(&files).is_empty()); + } + #[test] fn revision_changes_when_another_device_uploads() { let files = vec![file("pc", "one", 2, &["base"])]; diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index c6f97154..5cb8562a 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -1134,11 +1134,13 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot], g: let mut zip = zip::ZipArchive::new(fs::File::open(path)?).map_err(|_| invalid())?; let max_entries = spots.len().saturating_mul(MAX_FILES).saturating_add(1); if zip.len() > max_entries { return Err(invalid()); } + let manifest_limit = cloud_manifest_limit(&zip, spots.len()); let man: Manifest = { let mut entry = zip.by_name("rlsave.json").map_err(|_| invalid())?; - if entry.size() > 8 * 1024 * 1024 { return Err(invalid()); } + if entry.size() > manifest_limit { return Err(invalid()); } let mut bytes = Vec::new(); - entry.read_to_end(&mut bytes)?; + entry.by_ref().take(manifest_limit + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > manifest_limit { return Err(invalid()); } serde_json::from_slice(&bytes).map_err(|_| invalid())? }; if man.format != 1 || man.game != id || man.hash != hash || set_hash(&man.files) != hash || man.files.is_empty() { @@ -1191,6 +1193,16 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot], g: Ok(()) } +fn cloud_manifest_limit(zip: &zip::ZipArchive, spots: usize) -> u64 { + // JSON may escape each path byte. Budget the entry fields too, plus source folder paths + // up to native path limits; picked folders can differ between the two PCs. + let names: u64 = zip.file_names().map(|name| name.len() as u64).sum(); + let paths = names.saturating_mul(6); + let fields = (zip.len() as u64).saturating_mul(256); + let folders = (spots as u64).saturating_mul(128 * 1024 * 6); + paths.saturating_add(fields).saturating_add(folders).saturating_add(64 * 1024) +} + pub fn restore_cloud_copy(app_dir: &Path, id: &str, path: &Path, hash: &str, spots: &[Spot], g: &Installed) -> Result { validate_cloud_copy(path, id, hash, spots, g)?; restore(app_dir, id, path, spots, g) @@ -1858,18 +1870,40 @@ mod tests { ]; fs::create_dir_all(dir.join("saves-0")).unwrap(); fs::create_dir_all(dir.join("saves-1")).unwrap(); - let count = MAX_FILES + 2; + let count = MAX_FILES * 2; + let prefix = "s".repeat(90); for n in 0..count { - let path = dir.join(format!("saves-{}/slot-{}.sav", n % 2, n / 2)); + let path = dir.join(format!("saves-{}/{prefix}-{n:05}.sav", n % 2)); fs::write(path, b"save").unwrap(); } let copy = backup(&dir, "g", &spots, &g).unwrap().unwrap(); assert_eq!(copy.files, count); let archive = dir_of(&dir, "g").join(copy.name); + let mut zip = zip::ZipArchive::new(fs::File::open(&archive).unwrap()).unwrap(); + assert!(zip.by_name("rlsave.json").unwrap().size() > 8 * 1024 * 1024); + drop(zip); assert!(validate_cloud_copy(&archive, "g", ©.hash, &spots, &g).is_ok()); fs::remove_dir_all(dir).unwrap(); } + #[test] + fn cloud_copy_rejects_a_manifest_bomb_disproportionate_to_its_files() { + let dir = tmp("cloud-manifest-bomb"); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, &spots[0].template, b"save", b"save"); + let manifest = read_manifest(&path).unwrap(); + let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + zip.start_file("rlsave.json", options).unwrap(); + zip.write_all(&vec![b' '; 2 * 1024 * 1024]).unwrap(); + serde_json::to_writer(&mut zip, &manifest).unwrap(); + zip.start_file("0/slot.sav", options).unwrap(); + zip.write_all(b"save").unwrap(); + zip.finish().unwrap(); + assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_err()); + fs::remove_dir_all(dir).unwrap(); + } + #[test] fn cloud_file_counts_cannot_exceed_one_locations_limit() { let file = FileInfo { spot: 0, rel: "slot.sav".into(), size: 4, sha256: String::new() }; From 37c5485d8b079c0c47c51e960ac7fb29465db4ec Mon Sep 17 00:00:00 2001 From: innateessence Date: Sun, 15 Nov 2026 18:15:36 -0800 Subject: [PATCH 6/8] Keep Drive validation aligned with moved save folders --- docs/GOOGLE-DRIVE.md | 2 ++ src-tauri/src/saves.rs | 36 +++++++++++++++++++++++++++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md index 4a62ae81..ad82026d 100644 --- a/docs/GOOGLE-DRIVE.md +++ b/docs/GOOGLE-DRIVE.md @@ -95,6 +95,8 @@ file hashes before restoration, and archive destinations must match this PC's kn Each entry must also pass the save-file exclusions and match its local file or wildcard template. Installed release files, selected launch programs and managed inputs are protected from replacement. Links in restore destinations or staging paths are rejected before any live saves are changed. +If the developer or catalog moves a save folder, old copies restore into the current named +location with the same file checks. A guessed save folder cannot authorize that remapping. File-count and total-size limits are checked separately for each save location, matching backup discovery when a game saves in several folders. The manifest budget scales with the archive's entry count and path lengths, including full diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index 5cb8562a..c10c863c 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -1147,7 +1147,10 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot], g: return Err(invalid()); } let picked = !spots.is_empty() && spots.iter().all(|s| s.from == "player"); - if man.spots.len() != spots.len() || (!picked && man.spots.iter().zip(spots).any(|(a, b)| a != &b.template)) { + let moved = moved_places(&man.spots, spots).is_some(); + let same = man.spots.iter().zip(spots).all(|(a, b)| a == &b.template); + // Use the same trusted remapping as restore, while validating every file against the new roots. + if man.spots.len() != spots.len() || !(picked || moved || same) { return Err(invalid()); } if !cloud_files_within_limits(&man.files, spots.len()) { return Err(invalid()); } @@ -1949,13 +1952,28 @@ mod tests { } #[test] - fn cloud_copy_cannot_redirect_a_save_to_another_folder() { + fn cloud_copy_cannot_redirect_a_save_to_a_guessed_folder() { let dir = tmp("cloud-redirect"); - let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let spots = vec![Spot { template: "{install}/saves".into(), from: "found" }]; let (path, hash) = cloud_archive(&dir, "{home}/Documents", b"save", b"save"); assert!(validate_cloud_copy(&path, "g", &hash, &spots, &game(&dir)).is_err()); } + #[test] + fn cloud_restore_uses_current_named_folders_instead_of_archive_destinations() { + let dir = tmp("cloud-redirect-named"); + let outside = dir.join("outside"); + fs::create_dir(&outside).unwrap(); + fs::write(outside.join("slot.sav"), b"keep this").unwrap(); + let spots = vec![Spot { template: "{install}/saves".into(), from: "developer" }]; + let (path, hash) = cloud_archive(&dir, outside.to_str().unwrap(), b"save", b"save"); + let g = game(&dir.join("game")); + assert_eq!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).unwrap(), 1); + assert_eq!(fs::read(g.path.join("saves/slot.sav")).unwrap(), b"save"); + assert_eq!(fs::read(outside.join("slot.sav")).unwrap(), b"keep this"); + fs::remove_dir_all(dir).unwrap(); + } + #[test] fn cloud_copy_accepts_a_different_folder_the_player_picked_on_this_pc() { let dir = tmp("cloud-player-folder"); @@ -3006,6 +3024,18 @@ mod tests { (g, archive, place) } + #[test] + fn cloud_restore_follows_a_save_folder_the_developer_moved() { + let d = tmp("cloud-restore-moved"); + let (g, archive) = copy_from_old_folder(&d); + let now = spots(&["{install}/new".into()], &[], &g); + let hash = manifest(&archive).unwrap().hash; + assert_eq!(restore_cloud_copy(&d.join("app"), "g", &archive, &hash, &now, &g).unwrap(), 1); + assert_eq!(fs::read_to_string(g.path.join("new/progress.sav")).unwrap(), "progress"); + assert!(!g.path.join("old").exists()); + fs::remove_dir_all(d).unwrap(); + } + #[test] fn restore_that_cant_write_says_so_first() { let d = tmp("restore-unwritable-first"); From af3cf702ed7b82e206409727f515a712acd57959 Mon Sep 17 00:00:00 2001 From: Zacharias Xenakis Date: Wed, 18 Nov 2026 00:31:46 +0000 Subject: [PATCH 7/8] Save status follows the chosen cloud saves_status says connected when the picked cloud is ready (not only when signed in to RecompStore) and names it. A Drive upload records its sync and sends the "up" event, Drive conflicts are remembered until the player picks, and a full Drive is a full problem. RecompStore's pause and 150 MB only count when it's the cloud, and switching cloud or account forgets the old one's conflict, problem and sync time. --- src-tauri/src/cloud.rs | 79 ++++++++++++++++++++++++++++++++---------- src-tauri/src/saves.rs | 13 ++++++- 2 files changed, 72 insertions(+), 20 deletions(-) diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index f2e02058..16ea89f2 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -828,12 +828,14 @@ fn working(app: &AppHandle, id: &str, what: &str) -> Working { Working { app: app.clone(), id: id.to_string() } } -/// The kind of trouble behind a failed upload, as saves_status reports it. -fn problem_kind(e: &Error) -> &'static str { - if paused() { +/// The kind of trouble behind a failed upload, as saves_status reports it. `website`: the saves +/// go to RecompStore, whose pause applies; with Google Drive it doesn't. +fn problem_kind(e: &Error, website: bool) -> &'static str { + if website && paused() { return "paused"; } - if is_full(e) { + // RecompStore's 150 MB, or the player's Google Drive storage. + if is_full(e) || e.to_string().contains("Drive storage is full") { return "full"; } if e.to_string().starts_with("This save is too big") { @@ -846,13 +848,20 @@ fn problem_kind(e: &Error) -> &'static str { } /// Remembers why this game's saves didn't go up, so its page can still say so after the toast is -/// gone. A conflict is kept on its own (upload sets it), not as a problem. +/// gone. A conflict is kept on its own, not as a problem: upload sets it with the cloud copy's +/// version, and Google Drive, which only says so in its upload error, sets it here. fn note_failure(dir: &Path, id: &str, e: &Error) { + let mut s = saves::state(dir, id); if e.to_string() == SYNC_CONFLICT { + if s.conflict.is_some() { + return; + } + s.conflict = Some(String::new()); + saves::set_state(dir, id, &s); return; } - let mut s = saves::state(dir, id); - s.problem = Some(saves::Problem { kind: problem_kind(e).into(), text: e.to_string(), at: crate::library::now() }); + let kind = problem_kind(e, !using_drive(dir)); + s.problem = Some(saves::Problem { kind: kind.into(), text: e.to_string(), at: crate::library::now() }); saves::set_state(dir, id, &s); } @@ -882,7 +891,10 @@ async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { .ok_or_else(|| Error::Msg("That copy is gone.".into()))?; let (list, _) = cloud_list(app, id).await?; let Some(top) = list.first() else { return upload_copy(app, id, name, 0, None, a.as_ref()).await }; + // Drive keeps both branches until the player picks. if top.conflict { + state.conflict = Some(top.v.clone()); + saves::set_state(&st.dir, id, &state); return Err(Error::Msg(SYNC_CONFLICT.into())); } if top.hash == copy.hash { @@ -909,13 +921,15 @@ async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, resol if !crate::net::forced() && copy_wait_left(id, name).is_some() { return Err(Error::Net("Google Drive upload is waiting to retry.".into())); } + let working = working(app, id, "up"); if let Err(e) = crate::drive::upload(app, id, &path, resolution).await { if matches!(e, Error::Net(_)) { copy_failed(id, name, "Google Drive unavailable"); } return Err(e); } + drop(working); copy_went_up(id, name); let mut state = saves::state(&st.dir, id); - state.synced_hash = man.hash; + state.mark_synced(&man.hash, man.made.max(earliest), &man.device); state.pending = None; saves::set_state(&st.dir, id, &state); return Ok(()); @@ -1745,19 +1759,22 @@ fn sync_status(app: &AppHandle, id: &str) -> Res { let st = app.state::(); let g = game(&st, id)?; let s = saves::state(&st.dir, id); - let signed = signed_in(&st.dir); + // Connected to whichever cloud the player picked (signed in, for RecompStore). + let ready = crate::save_provider::ready(&st.dir); + // Full and paused are what the RecompStore website said; Drive says its own in `problem`. + let website = !using_drive(&st.dir); let local = saves::list(&st.dir, id, &g); let retry = s.pending.as_deref().and_then(|p| copy_wait_left(id, p)); Ok(json!({ - "state": s.sync_state(g.cloud == Some(true), signed), - "cloudOn": g.cloud, "signedIn": signed, + "state": s.sync_state(g.cloud == Some(true), ready), + "cloudOn": g.cloud, "signedIn": ready, + "provider": crate::save_provider::current(&st.dir), "providerName": crate::save_provider::name(&st.dir), "syncedAt": s.synced_at, "syncedMade": s.synced_made, "syncedDevice": s.synced_device, - "waiting": waiting_copies(&local, &s), "retryIn": retry, "full": full_now(), "paused": paused(), + "waiting": waiting_copies(&local, &s), "retryIn": retry, + "full": website && full_now(), "paused": website && paused(), "problem": s.problem, "conflict": s.conflict.is_some(), "newest": local.first(), // False: nobody has said where it saves, so nothing of it is backed up or synced. "known": !spots_of(&st, id, &g).is_empty(), - // Where the saves go. Only RecompStore today; named so another cloud can say so later. - "provider": "recompstore", })) } @@ -3012,23 +3029,23 @@ mod status_tests { #[test] fn a_full_cloud_is_its_own_problem() { - assert_eq!(problem_kind(&Error::Msg(FULL_TEXT.into())), "full"); + assert_eq!(problem_kind(&Error::Msg(FULL_TEXT.into()), true), "full"); } #[test] fn a_copy_over_the_limit_is_too_big() { let e = Error::Msg("This save is too big for cloud saves (over 95 MB). It's kept on this PC.".into()); - assert_eq!(problem_kind(&e), "too-big-copy"); + assert_eq!(problem_kind(&e, true), "too-big-copy"); } #[test] fn no_connection_is_offline() { - assert_eq!(problem_kind(&Error::Net("Can't reach recomplauncher.com right now.".into())), "offline"); + assert_eq!(problem_kind(&Error::Net("Can't reach recomplauncher.com right now.".into()), true), "offline"); } #[test] fn any_other_refusal_is_an_error() { - assert_eq!(problem_kind(&Error::Msg("That copy is gone.".into())), "error"); + assert_eq!(problem_kind(&Error::Msg("That copy is gone.".into()), true), "error"); } #[test] @@ -3043,7 +3060,7 @@ mod status_tests { } #[test] - fn a_conflict_is_not_recorded_as_a_problem() { + fn a_conflict_is_recorded_separately_from_a_problem() { let d = tmp("conflict"); note_failure(&d, "g", &Error::Msg(SYNC_CONFLICT.into())); assert!(saves::state(&d, "g").problem.is_none()); @@ -3077,6 +3094,30 @@ mod status_tests { let s = saves::State { synced_hash: "a".into(), ..Default::default() }; assert_eq!(waiting_copies(&local, &s), 0); } + #[test] + fn a_full_google_drive_is_full() { + let e = Error::Msg("Google Drive storage is full. Free space in Drive, then press Sync Now. Your saves stay on this PC.".into()); + assert_eq!(problem_kind(&e, false), "full"); + } + + #[test] + fn a_conflict_google_drive_reports_as_an_error_is_kept() { + let d = tmp("conflict-error"); + sign_in_for_tests(&d, "A"); + note_failure(&d, "g", &Error::Msg(SYNC_CONFLICT.into())); + assert_eq!(saves::state(&d, "g").sync_state(true, true), "conflict"); + std::fs::remove_dir_all(d).unwrap(); + } + + #[test] + fn a_conflict_with_a_known_version_keeps_it() { + let d = tmp("conflict-version"); + sign_in_for_tests(&d, "A"); + saves::set_state(&d, "g", &saves::State { conflict: Some("v7".into()), ..Default::default() }); + note_failure(&d, "g", &Error::Msg(SYNC_CONFLICT.into())); + assert_eq!(saves::state(&d, "g").conflict.as_deref(), Some("v7")); + std::fs::remove_dir_all(d).unwrap(); + } } #[cfg(test)] diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index c10c863c..db7f56d4 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -1993,7 +1993,7 @@ mod tests { #[test] fn provider_changes_discard_the_sync_baseline_and_queue() { let dir = tmp("cloud-provider"); - let state = State { last_hash: "local".into(), synced_hash: "cloud".into(), pending: Some("123.zip".into()) }; + let state = State { last_hash: "local".into(), synced_hash: "cloud".into(), pending: Some("123.zip".into()), ..Default::default() }; set_state(&dir, "g", &state); fs::write(dir.join("save-provider.json"), b"\"google_drive\"").unwrap(); let read = super::state(&dir, "g"); @@ -2002,6 +2002,17 @@ mod tests { assert!(read.pending.is_none()); } + #[test] + fn provider_changes_forget_the_old_clouds_conflict_and_problem() { + let dir = tmp("cloud-provider-status"); + let problem = Some(Problem { kind: "full".into(), text: String::new(), at: 1 }); + let state = State { synced_hash: "cloud".into(), synced_at: 5, conflict: Some("v1".into()), problem, ..Default::default() }; + set_state(&dir, "g", &state); + fs::write(dir.join("save-provider.json"), b"\"google_drive\"").unwrap(); + let read = super::state(&dir, "g"); + assert_eq!((read.synced_at, read.conflict.is_none(), read.problem.is_none()), (0, true, true)); + } + #[test] fn account_changes_discard_the_sync_baseline_and_queue() { let dir = tmp("cloud-account"); From 0bf5773b58ab4c67867bd81da1beb45d24c8529a Mon Sep 17 00:00:00 2001 From: innateessence Date: Wed, 25 Nov 2026 18:00:36 -0800 Subject: [PATCH 8/8] Adapt Google Drive saves to current cloud consent and save APIs --- docs/GOOGLE-DRIVE.md | 9 +++-- src-tauri/src/cloud.rs | 73 +++++++++++++++++++++++++++------- src-tauri/src/save_provider.rs | 7 +++- src-tauri/src/saves.rs | 19 +++++---- tests/cloud-all.test.cjs | 1 + tests/google-drive.test.cjs | 14 ++++++- tests/save-badge.test.cjs | 8 ++++ tests/saves-tab.test.cjs | 18 ++++++++- ui/account.js | 19 ++++----- ui/app.js | 3 +- ui/tv.js | 11 ++--- 11 files changed, 134 insertions(+), 48 deletions(-) diff --git a/docs/GOOGLE-DRIVE.md b/docs/GOOGLE-DRIVE.md index ad82026d..f6346da1 100644 --- a/docs/GOOGLE-DRIVE.md +++ b/docs/GOOGLE-DRIVE.md @@ -2,7 +2,8 @@ Open **Settings → Account → Save destination → Connect Google Drive**. Choose your Google account in the browser and approve access. Then choose **Use Google Drive** and enable cloud -saves on each game's **Saves** tab. A RecompStore account is not required for Drive saves. +saves in each game's **Manage** tab, or use **Back Up Every Game** in the save destination +settings. A RecompStore account is not required for Drive saves. The launcher creates a visible **RecompLauncher/Saves** folder in My Drive. Copies are ZIP archives using the same `rlsave.json` format as local backups. The launcher requests only @@ -24,11 +25,13 @@ Choosing the cloud copy resolves from that snapshot, even when restoring into th install folder retains extra local save slots. Those extra slots stay on this PC. The other copies remain available in the Saves tab. The newest five ordinary cloud copies are kept; unresolved branches retain their history until resolved. Removed old copies go -to Drive's Trash, which still uses Google storage until emptied. Local backups retain their +to Drive's Trash, which still uses Google storage until emptied. The launcher manages Drive +history automatically; individual cloud-copy deletion in the Saves tab is for RecompStore. Local backups retain their existing limit of ten copies per game. The upload limit remains 95 MiB per archive, along with the existing save discovery and file limits. -Switching providers or connecting a different Google account requires enabling games again. +Switching providers or connecting a different Google account turns off **Back Up Every Game** +and requires enabling games again. Existing copies are not moved between providers. **Disconnect** stops this PC's Drive sync and removes its Google credentials; local saves and remote copies remain. You can separately remove RecompLauncher's access in your Google account's connected-app settings. Google's diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index 16ea89f2..67aea9bd 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -159,10 +159,6 @@ fn still_signed_in_as(dir: &Path, a: &Account, id: &str) -> bool { same } -pub(crate) fn account_scope(dir: &Path) -> String { - account_uid(dir) -} - /// The website said this PC's token is no good any more (signed out from the website). fn forget(app: &AppHandle) { let st = app.state::(); @@ -242,6 +238,7 @@ pub(crate) fn reset_provider_status() { FULL_TOLD.store(false, std::sync::atomic::Ordering::Relaxed); *FULL.lock().unwrap() = None; *TRIES.lock().unwrap() = None; + *PEEKED.lock().unwrap() = None; } /// A copy that didn't go up whole (cut off, too slow, "didn't arrive whole"): tried again after 1, @@ -890,6 +887,9 @@ async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { let copy = saves::manifest(&copies_dir(&st, id).join(name)) .ok_or_else(|| Error::Msg("That copy is gone.".into()))?; let (list, _) = cloud_list(app, id).await?; + if crate::save_provider::scope(&st.dir) != scope { + return Ok(()); + } let Some(top) = list.first() else { return upload_copy(app, id, name, 0, None, a.as_ref()).await }; // Drive keeps both branches until the player picks. if top.conflict { @@ -915,6 +915,8 @@ async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, resolution: Option<&str>, account: Option<&Account>) -> Res<()> { let st = app.state::(); + let scope = crate::save_provider::scope(&st.dir); + let mut state = saves::state(&st.dir, id); let path = copies_dir(&st, id).join(name); let man = saves::manifest(&path).ok_or_else(|| Error::Msg("That copy is gone.".into()))?; if using_drive(&st.dir) { @@ -928,7 +930,9 @@ async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, resol } drop(working); copy_went_up(id, name); - let mut state = saves::state(&st.dir, id); + if crate::save_provider::scope(&st.dir) != scope { + return Ok(()); + } state.mark_synced(&man.hash, man.made.max(earliest), &man.device); state.pending = None; saves::set_state(&st.dir, id, &state); @@ -1306,7 +1310,7 @@ fn incoming<'a>(s: &saves::State, list: &'a [CloudCopy]) -> Option<&'a CloudCopy return None; } let top = list.first()?; - should_restore(&s.last_hash, &s.synced_hash, &top.hash, false).then_some(top) + (!top.conflict && should_restore(&s.last_hash, &s.synced_hash, &top.hash, false)).then_some(top) } async fn restore_drive_copy(dir: PathBuf, id: String, archive: PathBuf, hash: String, spots: Vec, g: Installed, checked: Option, resolve: F) -> Res @@ -1319,7 +1323,7 @@ where saves::validate_cloud_copy(&path, &id, &hash, &spots, &g)?; match checked { Some(h) => saves::restore_if_unchanged(&dir, &id, &path, &spots, &g, &h), - None => saves::restore_cloud_copy(&dir, &id, &path, &hash, &spots, &g), + None => saves::restore(&dir, &id, &path, &spots, &g), } }).await??; // The install-folder fallback retains extra local slots. Resolve the chosen archive itself, @@ -1808,7 +1812,7 @@ fn keep_peek(id: &str, synced: &str, list: &[CloudCopy]) { pub async fn saves_peek(app: AppHandle, id: String) -> Res { let st = app.state::(); let g = game(&st, &id)?; - if g.cloud != Some(true) || !signed_in(&st.dir) || spots_of(&st, &id, &g).is_empty() { + if g.cloud != Some(true) || !crate::save_provider::ready(&st.dir) || spots_of(&st, &id, &g).is_empty() { return Ok(Value::Null); } let state = saves::state(&st.dir, &id); @@ -2081,6 +2085,9 @@ pub async fn saves_restore(app: AppHandle, id: String, name: Option, v: #[tauri::command] pub async fn saves_cloud_delete(app: AppHandle, id: String, v: String) -> Res<()> { let _busy = BUSY.lock().await; + if using_drive(&app.state::().dir) { + return Err(Error::Msg("Google Drive keeps the newest five copies automatically. Manage its files in Drive.".into())); + } let (list, _) = cloud_list(&app, &id).await?; if !deletable(&list, &v) { return Err(Error::Msg("The newest cloud save stays: the next PC you play on brings it in.".into())); @@ -2426,6 +2433,18 @@ mod child_retry_tests { ]) } + #[test] + fn changing_provider_clears_inherited_cloud_consent() { + let fixture = Fixture::new(games()); + fixture.0.lib.lock().unwrap().settings.ui["cloud_all"] = true.into(); + crate::save_provider::clear_consent(&fixture.0).unwrap(); + let library = fixture.0.lib.lock().unwrap(); + let game = library.installed.get("series").unwrap(); + assert_eq!(game.cloud, None); + assert!(!game.cloud_on(&library.settings.ui)); + assert!(!Installed::default().cloud_on(&library.settings.ui)); + } + #[test] fn a_sync_is_refused_while_the_game_is_being_uninstalled() { let fixture = Fixture::new(games()); @@ -3155,21 +3174,22 @@ mod provider_conflict_tests { let g = Installed { id: "g".into(), path: install.clone(), ..Default::default() }; let spots = vec![Spot { template: "{install}".into(), from: "game" }]; let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); - let archive = saves::dir_of(&app, "g").join(&chosen.name); + let archive = saves::dir_of(&app, "g", &g).join(&chosen.name); let expected = archive.clone(); std::fs::write(install.join("slot.sav"), b"local change").unwrap(); std::fs::write(install.join("extra.sav"), b"extra local slot").unwrap(); let local_hash = saves::current(&spots, &g).2; - let result = restore_drive_copy(app.clone(), "g".into(), archive, chosen.hash.clone(), spots.clone(), g.clone(), |upload| async move { + let checked_game = g.clone(); + let result = restore_drive_copy(app.clone(), "g".into(), archive, chosen.hash.clone(), spots.clone(), g.clone(), None, |upload| async move { assert_eq!(upload, expected); assert_eq!(saves::manifest(&upload).unwrap().hash, chosen.hash); - assert_ne!(saves::current(&spots, &g).2, chosen.hash, "retained slots must not change the archive used for resolution"); + assert_ne!(saves::current(&spots, &checked_game).2, chosen.hash, "retained slots must not change the archive used for resolution"); Ok(()) }).await.unwrap(); assert_eq!(result, 1); assert_eq!(std::fs::read(install.join("slot.sav")).unwrap(), b"cloud save"); assert_eq!(std::fs::read(install.join("extra.sav")).unwrap(), b"extra local slot"); - assert!(saves::list(&app, "g").iter().any(|c| c.hash == local_hash)); + assert!(saves::list(&app, "g", &g).iter().any(|c| c.hash == local_hash)); std::fs::remove_dir_all(dir).unwrap(); } @@ -3177,21 +3197,22 @@ mod provider_conflict_tests { async fn interrupted_cloud_resolution_can_retry_with_retained_local_slots() { let dir = std::env::temp_dir().join(format!("rl-cloud-resolution-retry-{}", std::process::id())); let app = dir.join("app"); + sign_in_for_tests(&app, "A"); let install = dir.join("game"); std::fs::create_dir_all(&install).unwrap(); std::fs::write(install.join("slot.sav"), b"cloud save").unwrap(); let g = Installed { id: "g".into(), path: install.clone(), ..Default::default() }; let spots = vec![Spot { template: "{install}".into(), from: "game" }]; let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); - let archive = saves::dir_of(&app, "g").join(&chosen.name); + let archive = saves::dir_of(&app, "g", &g).join(&chosen.name); std::fs::write(install.join("extra.sav"), b"extra local slot").unwrap(); saves::set_state(&app, "g", &saves::State { synced_hash: "previous-cloud".into(), ..Default::default() }); - let interrupted = restore_drive_copy(app.clone(), "g".into(), archive.clone(), chosen.hash.clone(), spots.clone(), g.clone(), |_| async { + let interrupted = restore_drive_copy(app.clone(), "g".into(), archive.clone(), chosen.hash.clone(), spots.clone(), g.clone(), None, |_| async { Err(Error::Net("interrupted resolution".into())) }).await; assert!(matches!(interrupted, Err(Error::Net(_)))); assert_eq!(saves::state(&app, "g").synced_hash, "previous-cloud"); - restore_drive_copy(app, "g".into(), archive, chosen.hash.clone(), spots, g, |upload| async move { + restore_drive_copy(app, "g".into(), archive, chosen.hash.clone(), spots, g, None, |upload| async move { assert_eq!(saves::manifest(&upload).unwrap().hash, chosen.hash); Ok(()) }).await.unwrap(); @@ -3199,6 +3220,28 @@ mod provider_conflict_tests { std::fs::remove_dir_all(dir).unwrap(); } + #[tokio::test] + async fn drive_restore_preserves_saves_changed_during_download() { + let dir = std::env::temp_dir().join(format!("rl-drive-restore-changed-{}", std::process::id())); + let app = dir.join("app"); + let install = dir.join("game"); + std::fs::create_dir_all(&install).unwrap(); + let slot = install.join("slot.sav"); + std::fs::write(&slot, b"cloud save").unwrap(); + let g = Installed { id: "g".into(), path: install, ..Default::default() }; + let spots = vec![Spot { template: "{install}/slot.sav".into(), from: "developer" }]; + let chosen = saves::backup(&app, "g", &spots, &g).unwrap().unwrap(); + let archive = saves::dir_of(&app, "g", &g).join(&chosen.name); + let checked = saves::current(&spots, &g).2; + std::fs::write(&slot, b"new local save").unwrap(); + let result = restore_drive_copy(app, "g".into(), archive, chosen.hash, spots, g, Some(checked), |_| async { + panic!("a changed local save must not resolve the cloud conflict"); + }).await; + assert_eq!(result.unwrap_err().to_string(), saves::CHANGED_SINCE_CHECK); + assert_eq!(std::fs::read(slot).unwrap(), b"new local save"); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn a_drive_conflict_offers_the_other_devices_save() { let list = vec![ diff --git a/src-tauri/src/save_provider.rs b/src-tauri/src/save_provider.rs index fa56bcdb..d2b9d048 100644 --- a/src-tauri/src/save_provider.rs +++ b/src-tauri/src/save_provider.rs @@ -33,7 +33,7 @@ pub fn ready(dir: &Path) -> bool { pub fn scope(dir: &Path) -> String { match current(dir) { - Provider::Recompstore => format!("recompstore:{}", cloud::account_scope(dir)), + Provider::Recompstore => format!("recompstore:{}", cloud::account_uid(dir)), Provider::GoogleDrive => format!("google_drive:{}", drive::identity(dir)), Provider::Disabled => "disabled".into(), } @@ -55,7 +55,9 @@ pub fn state(app: &AppHandle) -> Value { #[tauri::command] pub fn save_provider_state(app: AppHandle) -> Value { let st = app.state::(); - json!({"state": state(&app), "installed": st.lib.lock().unwrap().installed}) + let state = state(&app); + let library = st.lib.lock().unwrap(); + json!({"state": state, "installed": library.installed, "cloudAll": library.settings.ui.get("cloud_all")}) } pub fn emit(app: &AppHandle) { @@ -76,6 +78,7 @@ pub fn clear_consent(st: &App) -> Result<(), Error> { for game in next.installed.values_mut() { game.cloud = None; } + next.settings.ui["cloud_all"] = false.into(); next.save(&st.dir)?; *library = next; cloud::reset_provider_status(); diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index db7f56d4..9173518e 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -868,8 +868,7 @@ fn state_file(app_dir: &Path, id: &str) -> PathBuf { app_dir.join("saves").join(id).join("state.json") } -/// The key in state.json naming the sign-in its cloud fields belong to. Same name and form as the -/// Google Drive draft (PR #228) uses, ":", so the two read each other's notes. +/// The key in state.json naming the provider and account its cloud fields belong to. const SCOPE_KEY: &str = "cloud_scope"; /// The sign-in a note's cloud fields are written under now. Read from account.json without @@ -923,7 +922,7 @@ pub fn state(app_dir: &Path, id: &str) -> State { }; s.read_under = Some(now.clone()); let Some(written) = written else { - if !owned(&now) { + if !owned(&now) || !now.starts_with("recompstore:") { s.forget_cloud(); } write_note(app_dir, id, &s, &now); @@ -1154,10 +1153,8 @@ pub fn validate_cloud_copy(path: &Path, id: &str, hash: &str, spots: &[Spot], g: return Err(invalid()); } if !cloud_files_within_limits(&man.files, spots.len()) { return Err(invalid()); } - let release = crate::inputs::release_files(g); - let manual_exe = g.manual.as_ref().and_then(|m| m.exe.as_ref()); let mut protected = HashSet::new(); - for file in release.iter().chain(g.exe.iter()).chain(manual_exe) { + for file in g.files.iter().chain(g.exe.iter()) { let path = g.path.join(file); protected.insert(lower(&path)); if let Ok(real) = path.canonicalize() { protected.insert(lower(&real)); } @@ -1729,12 +1726,11 @@ mod tests { } #[test] - fn cloud_restore_rejects_a_program_named_by_manual_setup() { + fn cloud_restore_rejects_an_absolute_selected_program() { let dir = tmp("cloud-manual-program"); let program = dir.join("launch-game"); fs::write(&program, b"manual program").unwrap(); - let manual = crate::library::ManualSetup { exe: Some(program.clone()), ..Default::default() }; - let g = Installed { manual: Some(manual), files: vec![], ..game(&dir) }; + let g = Installed { exe: Some(program.clone()), files: vec![], ..game(&dir) }; let spots = vec![Spot { template: "{install}".into(), from: "game" }]; let (path, hash) = cloud_archive_named(&dir, "{install}", "launch-game", b"replacement", b"replacement"); assert!(restore_cloud_copy(&dir.join("app"), "g", &path, &hash, &spots, &g).is_err()); @@ -1881,7 +1877,7 @@ mod tests { } let copy = backup(&dir, "g", &spots, &g).unwrap().unwrap(); assert_eq!(copy.files, count); - let archive = dir_of(&dir, "g").join(copy.name); + let archive = dir_of(&dir, "g", &g).join(copy.name); let mut zip = zip::ZipArchive::new(fs::File::open(&archive).unwrap()).unwrap(); assert!(zip.by_name("rlsave.json").unwrap().size() > 8 * 1024 * 1024); drop(zip); @@ -1993,6 +1989,7 @@ mod tests { #[test] fn provider_changes_discard_the_sync_baseline_and_queue() { let dir = tmp("cloud-provider"); + crate::cloud::sign_in_for_tests(&dir, "A"); let state = State { last_hash: "local".into(), synced_hash: "cloud".into(), pending: Some("123.zip".into()), ..Default::default() }; set_state(&dir, "g", &state); fs::write(dir.join("save-provider.json"), b"\"google_drive\"").unwrap(); @@ -2005,6 +2002,7 @@ mod tests { #[test] fn provider_changes_forget_the_old_clouds_conflict_and_problem() { let dir = tmp("cloud-provider-status"); + crate::cloud::sign_in_for_tests(&dir, "A"); let problem = Some(Problem { kind: "full".into(), text: String::new(), at: 1 }); let state = State { synced_hash: "cloud".into(), synced_at: 5, conflict: Some("v1".into()), problem, ..Default::default() }; set_state(&dir, "g", &state); @@ -2028,6 +2026,7 @@ mod tests { #[test] fn legacy_website_sync_state_is_migrated() { let dir = tmp("cloud-legacy"); + crate::cloud::sign_in_for_tests(&dir, "legacy"); let value = serde_json::json!({"last_hash": "local", "synced_hash": "cloud", "pending": "123.zip"}); fs::create_dir_all(dir.join("saves/g")).unwrap(); fs::write(state_file(&dir, "g"), serde_json::to_vec(&value).unwrap()).unwrap(); diff --git a/tests/cloud-all.test.cjs b/tests/cloud-all.test.cjs index f225347b..3fb757eb 100644 --- a/tests/cloud-all.test.cjs +++ b/tests/cloud-all.test.cjs @@ -93,6 +93,7 @@ test('Play asks nothing about cloud saves for a game never switched', async () = const invoked = []; const S = { library: { g: { name: 'Game', cloud: null } }, account: { signedIn: true }, settings: { ui: {} } }; const context = { S, invoke: async (c) => { invoked.push(c); return { action: 'play' }; }, toast() {}, savesChanged() {}, fail: assert.fail, t: String, tf: String }; + context.cloudReady = () => S.account.signedIn; context.cloudOn = runInNewContext(cloudOnSrc + '\ncloudOn', context); const play = runInNewContext(playSrc + '\nbeforeCloudPlay', context); assert.equal(await play('g'), true); diff --git a/tests/google-drive.test.cjs b/tests/google-drive.test.cjs index 104a2f85..be530c87 100644 --- a/tests/google-drive.test.cjs +++ b/tests/google-drive.test.cjs @@ -18,7 +18,7 @@ function providerSetup(picked) { return { state: { provider: args.provider, connected: true }, installed: { game: { cloud: null } } }; }, renderAccountBits() {}, - expandLib() {}, + expandLib() {}, forgetSaveStatus() {}, }); return { S, calls, ...helpers }; } @@ -48,19 +48,28 @@ test('selecting the current provider does not reset consent', async () => { test('refreshing the provider keeps individual games from a shared installation', () => { const games = readFileSync(join(__dirname, '../ui/games.js'), 'utf8'); const S = { gameSets: { series: { games: [{ id: 'first', name: 'First' }] } }, library: {}, saves: {} }; - const apply = runInNewContext(games + '\n' + providerHelpers + '\napplySaveProvider', { S, window: {} }); + const apply = runInNewContext(games + '\n' + providerHelpers + '\napplySaveProvider', { S, window: {}, forgetSaveStatus() {} }); apply({ state: { provider: 'google_drive' }, installed: { series: { id: 'series', cloud: null, games: { first: { played_secs: 60 } } } } }); assert.equal(S.library['series--first'].name, 'First'); assert.equal(S.library['series--first'].cloud, null); assert.equal(S.library['series--first'].played_secs, 60); }); +test('provider refresh applies the reset global consent from the backend', () => { + const S = { settings: { ui: { cloud_all: true } }, library: {}, saves: {} }; + const apply = runInNewContext(providerHelpers + '\napplySaveProvider', { S, window: {}, expandLib() {}, forgetSaveStatus() {} }); + apply({ state: { provider: 'google_drive', connected: true }, cloudAll: false, installed: { game: { cloud: null } } }); + assert.equal(S.settings.ui.cloud_all, false); + assert.equal(S.library.game.cloud, null); +}); + test('Drive sync before play does not need a RecompStore sign-in', async () => { const source = account.slice(account.indexOf('async function beforeCloudPlay('), account.indexOf('async function pickCloudSave(')); const calls = []; const play = runInNewContext(source + '\nbeforeCloudPlay', { S: { account: { signedIn: false }, library: { game: { cloud: true } } }, cloudReady: () => true, + cloudOn: (g) => g.cloud === true, invoke: async (command, args) => { calls.push([command, { ...args }]); return { action: 'play' }; }, savesChanged() {}, toast() {}, fail: assert.fail, }); @@ -74,6 +83,7 @@ test('Drive conflict choices submit the revision the player reviewed', async () const pick = runInNewContext(source + '\npickCloudSave', { invoke: async (command, args) => calls.push([command, { ...args }]), ask: async () => 'local', + chooseSave: async () => 'local', t: String, tf: String, esc: String, whenText: String, fmtTime: String, toast() {}, }); await pick('game', { local: { hash: 'local', when: 100 }, cloud: { v: 'file', revision: 'both-heads', made: 200 } }); diff --git a/tests/save-badge.test.cjs b/tests/save-badge.test.cjs index bb2b5a50..bfddeadc 100644 --- a/tests/save-badge.test.cjs +++ b/tests/save-badge.test.cjs @@ -168,3 +168,11 @@ test('the cloud copy saved after this PC: the cloud one is newer', () => { test('saved at the same second: neither is marked', () => { assert.equal(newerSave({ when: 100 }, { made: 100 }), ''); }); + + +test('a disconnected Drive badge offers Google connection and retains backup details', () => { + const b = info.saveBadgeInfo(status('signed-out', { provider: 'google_drive', newest: { when: 100, device: 'PC' } }), undefined, false); + assert.equal(b.label, 'Connect Google Drive'); + assert.equal(b.tone, 'dim'); + assert.equal(b.rows.length, 1); +}); diff --git a/tests/saves-tab.test.cjs b/tests/saves-tab.test.cjs index 7e262123..ab4775cc 100644 --- a/tests/saves-tab.test.cjs +++ b/tests/saves-tab.test.cjs @@ -287,7 +287,7 @@ test('every button a status can show does something in Big Picture, or says to u assert.ok(tv.includes(`case '${tvAct[1]}'`), tvAct[1]); } assert.match(tv, /step\.act === 'report' \? ` \$\{t\('Report problems from the desktop view'\)\}\.`/); - assert.match(tv, /step\.act === 'url' \? ` \$\{t\('Free up space on your account page at recomplauncher\.com\.'\)\}`/); + assert.match(tv, /step\.act === 'url' \? ` \$\{storageHelp\}`/); }); test('any cloud save but the newest can be deleted', () => { @@ -379,3 +379,19 @@ test('the newer save can be synced now with Sync Now, on the desktop and in Big test('Big Picture gives the save coming in no Restore either', () => { assert.match(tv, /const act = r\.current \|\| r\.incoming \? '' :/); }); + + +test('a full Drive points to Google storage instead of RecompStore', () => { + const st = { ...problem('full'), provider: 'google_drive' }; + assert.equal(steps(st, undefined, false, false).url, 'https://drive.google.com/drive/quota'); +}); + +test('a disconnected Drive offers to reconnect Google', () => { + const st = { state: 'signed-out', provider: 'google_drive' }; + assert.equal(steps(st, undefined, false, false).act, 'acc-drive-connect'); +}); + +test('Drive history uses automatic cleanup without the RecompStore delete command', () => { + const rows = tab(fresh()).saveHistory({ provider: 'Google Drive', local: [], cloud: [cloud(200, 'b', 'v2'), cloud(100, 'a', 'v1')] }); + assert.deepEqual(rows.map((r) => r.deletable), [false, false]); +}); diff --git a/ui/account.js b/ui/account.js index 324c8e01..449830d3 100644 --- a/ui/account.js +++ b/ui/account.js @@ -20,7 +20,10 @@ S.saveProvider = { provider: 'recompstore', name: 'RecompStore', connected: fals const cloudReady = () => !!S.saveProvider?.connected; function applySaveProvider(result) { + const previous = S.saveProvider; S.saveProvider = result.state || result; + if (Object.hasOwn(result, 'cloudAll')) { S.settings.ui = S.settings.ui || {}; S.settings.ui.cloud_all = result.cloudAll; } + if (previous.provider !== S.saveProvider.provider || previous.connected !== S.saveProvider.connected || previous.google?.email !== S.saveProvider.google?.email) forgetSaveStatus(); if (result.installed) { S.library = result.installed; expandLib(); } S.saves = {}; S.savesAll = null; if (window.tvSavesReset) window.tvSavesReset(); @@ -109,7 +112,7 @@ function saveProviderSection(group, row) { return group(t('Save Destination'), `

${esc(info)}

` + row('RecompStore', t('Use your RecompStore account for game saves.'), button(p.provider === 'recompstore' ? 'Selected' : 'Use RecompStore', 'provider-recompstore', p.provider === 'recompstore')) + row('Google Drive', googleHelp, `${google.connected ? button('Reconnect', 'drive-connect') + button('Disconnect', 'drive-disconnect') + button(p.provider === 'google_drive' ? 'Selected' : 'Use Google Drive', 'provider-google', p.provider === 'google_drive') : button('Connect Google Drive', 'drive-connect', !google.configured)}`) - + row(t('Ask for Each New Game'), t('Ask before enabling cloud saves for a game.'), ``) + + (p.connected ? row(t('Back Up Every Game'), t('Turn them on or off for one game in its Manage tab. The newest five copies of each game are kept.'), ``) : '') + deviceNameRow()); } @@ -244,15 +247,10 @@ function recompAccountSection(group, row) { + group(t('Save backups'), row(t('On this PC'), t('After every session the launcher keeps a copy of each game\'s saves, the newest ten. They\'re on each game\'s Saves tab.'), '')); } const used = a.used || 0, quota = a.quota || 150 * 1024 * 1024, pct = Math.min(100, Math.round((used / quota) * 100)); - // Back Up Every Game says what it does now, like a game's own switch in its Manage tab. - const all = (S.settings.ui || {}).cloud_all === true; - const allNow = all ? t('On. Cloud saves are activated for all games. Turning it off disables cloud saves for every game. Saves stay intact.') : t('Off. Cloud saves are only active for the games you turn on in their Manage tab. Turning it on activates them for every game.'); return group(t('Account'), `
${avatar(a.user, 48)}
${esc(a.user.username)}${esc(a.offline ? t('Signed in on this PC. The website can\'t be reached right now.') : t('Signed in on this PC'))}${a.offline && a.why ? `${esc(a.why)}` : ''}
${a.offline ? `` : ''}
`) + group(t('Cloud saves'), `
${esc(tf('{used} of {quota} used', { used: fmtB(used) || '0 KB', quota: fmtB(quota) }))}
-

${esc(t('Turn them on or off for one game in its Manage tab. The newest five copies of each game are kept.'))}

` - + row(t('Back Up Every Game'), allNow, ``) - + deviceNameRow()) +

${esc(t('Turn them on or off for one game in its Manage tab. The newest five copies of each game are kept.'))}

`) + (window.betasGroup ? window.betasGroup(group, row) : ''); } // ---------- Settings > Reviews ---------- @@ -460,7 +458,7 @@ function saveStatusCard(id, s) { const text = statusCardText(st, b, picked); const offline = st.problem && st.problem.kind === 'offline' && s.status; const help = offline ? `

${esc(t('Still no answer. Check whether the website is having trouble:'))}

` : ''; - const space = s.signedIn && s.cloudOn === true ? cloudSpace() : ''; + const space = s.signedIn && s.cloudOn === true && st.provider !== 'google_drive' ? cloudSpace() : ''; const step = next ? INCOMING_STEP : saveNextStep(st, phase, running, picked); const url = step && step.url ? ` data-url="${esc(step.url)}"` : ''; const btn = step ? `` : ''; @@ -504,10 +502,12 @@ function statusCardText(st, b, picked) { function saveNextStep(st, phase, running, picked) { if (phase || running) return null; if (st.known === false) return { act: 'saves-place', label: N_('Pick a Folder') }; + if (st.state === 'signed-out' && st.provider === 'google_drive') return { act: 'acc-drive-connect', label: N_('Connect Google Drive') }; if (st.state === 'signed-out') return { act: 'acc-signin', label: N_('Sign in') }; // saves-cloud turns them on when the button has no switch state to read. if (st.state === 'off') return { act: 'saves-cloud', label: N_('Turn On') }; if (st.state === 'conflict') return { act: 'saves-sync', label: N_('Choose a Save') }; + if (st.state === 'problem' && st.provider === 'google_drive' && st.problem?.kind === 'full') return { act: 'url', label: N_('Free Up Space'), url: 'https://drive.google.com/drive/quota' }; if (st.state === 'problem') return problemStep((st.problem && st.problem.kind) || 'error', picked); if (st.state === 'waiting' || st.state === 'up-to-date') return { act: 'saves-sync', label: N_('Sync Now') }; return null; @@ -557,7 +557,7 @@ function saveHistory(s) { for (const r of rows) r.incoming = !r.current && !!next && r.v === next; // Any cloud save but the newest can be deleted (saves_cloud_delete says why not that one). const newestCloud = Array.isArray(s.cloud) && s.cloud.length ? s.cloud.reduce((p, q) => (q.made > p.made ? q : p)).v : ''; - for (const r of rows) r.deletable = !!r.v && r.v !== newestCloud; + for (const r of rows) r.deletable = s.provider !== 'Google Drive' && !!r.v && r.v !== newestCloud; return rows; } @@ -776,6 +776,7 @@ function saveBadgeInfo(st, phase, running) { if (st.known === false) return { tone: 'dim', mark: 'off', label: t('Saves not backed up'), note: '', head: t('The launcher doesn\'t know where this game saves'), text: t('Nothing of it is backed up or sent to the cloud. Pick its save folder on its Saves tab.'), rows: [] }; const synced = st.syncedAt ? [[t('Last synced'), whenText(st.syncedAt)], [t('Saved on'), st.syncedDevice || t('this PC')]] : []; const newest = st.newest ? [[t('Last backup'), `${whenText(st.newest.when)}${st.newest.device ? ' · ' + st.newest.device : ''}`]] : []; + if (st.state === 'signed-out' && st.provider === 'google_drive') return { tone: 'dim', mark: 'dash', label: t('Connect Google Drive'), note: '', head: t('Keep this save on any PC'), text: t('Google Drive needs you to connect again.'), rows: newest }; if (st.state === 'signed-out') return { tone: 'dim', mark: 'dash', label: t('Not signed in'), note: '', head: t('Keep this save on any PC'), text: t('Sign in to RecompStore and your saves go to the cloud after you play. It\'s free.'), rows: newest }; if (st.state === 'off') return { tone: 'dim', mark: 'off', label: t('Cloud saves off'), note: '', head: t('Saves stay on this PC'), text: t('The launcher still keeps a copy after every session. Turn cloud saves on in its Saves tab.'), rows: newest }; if (st.state === 'conflict') return { tone: 'warn', mark: 'conflict', label: t('Choose a save'), note: t('press Play to pick'), head: t('Both saves changed'), text: t('This PC and the cloud both changed since they last synced. Press Play, or Sync Now in its Saves tab, to pick the one to keep; the other stays as a backup on this PC.'), rows: synced }; diff --git a/ui/app.js b/ui/app.js index 13d8b41a..2ed218a0 100644 --- a/ui/app.js +++ b/ui/app.js @@ -3311,7 +3311,8 @@ function manageFileRows(id, inst) { const rows = [`
${esc(t('Folder'))}${esc(inst.path)}
${inst.local ? '' : ``}
`]; if (!inst.local) rows.push(`
${esc(t('Backups of your saves'))}${esc(t('Taken before every update: the saves in its folder.'))}
`); // Cloud saves is switched here only; the Saves tab just offers to turn it on. - if (S.account && S.account.signedIn) { + const ready = S.saveProvider ? S.saveProvider.connected : S.account && S.account.signedIn; + if (ready) { const on = cloudOn(inst); rows.push(`
${esc(t('Cloud saves'))}${esc(on ? t('On. Saves for this game are synced to the cloud.') : t('Off. Saves for this game are not synced to the cloud.'))}
`); } diff --git a/ui/tv.js b/ui/tv.js index f60bb6d4..8a40ad39 100644 --- a/ui/tv.js +++ b/ui/tv.js @@ -1400,7 +1400,7 @@ ${S.saveProvider?.google?.connected ? `` : ''} - + ${S.saveProvider?.connected ? `` : ''} ${head(t('Display'))} ${(() => { const m = window.monitorPicked(S.monitors, S.settings.tv_monitor); @@ -1490,7 +1490,7 @@ if (TV.on && TV.view === 'gsaves' && TV.arg === id) draw(true); } // The desktop's next steps as this page's actions. Reporting a problem stays in the desktop view. - const TV_STEP = { 'acc-signin': 'account', 'saves-cloud': 'gs-cloud', 'saves-sync': 'gs-sync', 'saves-place': 'gs-place' }; + const TV_STEP = { 'acc-drive-connect': 'drive-connect', 'acc-signin': 'account', 'saves-cloud': 'gs-cloud', 'saves-sync': 'gs-sync', 'saves-place': 'gs-place' }; // The status, as the item that leads the page. function savesStatusItem(id, sv) { const b = window.saveBadgeFor(id); @@ -1504,7 +1504,8 @@ const step = next ? INCOMING_STEP : saveNextStep(st, phase, running, picked); const act = step && !sv.busy && TV_STEP[step.act]; // Reporting stays in the desktop view, and the account page needs a browser: said instead. - const desk = !step ? '' : step.act === 'report' ? ` ${t('Report problems from the desktop view')}.` : step.act === 'url' ? ` ${t('Free up space on your account page at recomplauncher.com.')}` : ''; + const storageHelp = st.provider === 'google_drive' ? st.problem?.text || '' : t('Free up space on your account page at recomplauncher.com.'); + const desk = !step ? '' : step.act === 'report' ? ` ${t('Report problems from the desktop view')}.` : step.act === 'url' ? ` ${storageHelp}` : ''; const tvact = act ? ` data-tvact="${act}" data-id="${esc(id)}"` : ''; const pill = act ? `${esc(t(step.label))}` : ''; const note = b.note ? ` · ${esc(b.note)}` : ''; @@ -2015,7 +2016,7 @@ // No Add to desktop on a Mac: the shortcut the launcher makes is Linux's .desktop file, which a Mac ignores. ...(S.steam || S.os !== 'macos' ? [{ gap: true, ...(S.steam ? { label: t('Add to Steam'), sub: t('With its art'), icon: 'steam', run: () => addToSteam(id, false) } : { label: t('Add to desktop'), sub: t('A shortcut that starts it'), icon: 'desk', run: async () => { try { await invoke('desktop_shortcut', { id }); toast(tf('{name} is on your desktop.', { name: g.name })); } catch (e) { fail(e); } } }) }] : []), ...(S.steam && S.os !== 'macos' ? [{ label: t('Add to desktop'), sub: t('A shortcut that starts it'), icon: 'desk', run: async () => { try { await invoke('desktop_shortcut', { id }); toast(tf('{name} is on your desktop.', { name: g.name })); } catch (e) { fail(e); } } }] : []), - ...(S.account && S.account.signedIn ? [{ label: cloudOn(g) ? t('Turn off cloud saves') : t('Turn on cloud saves'), sub: cloudOn(g) ? t('Its saves stay on this PC from now on') : t('Its saves go to your account after you play'), icon: 'cloud', run: async () => { try { S.library[id] = await invoke('saves_cloud', { id, on: !cloudOn(g) }); toast(cloudOn(g) ? t('Cloud saves are off for it. What\'s in the cloud stays there.') : t('Cloud saves are on for it.')); } catch (e) { fail(e); } } }] : []), + ...(cloudReady() ? [{ label: cloudOn(g) ? t('Turn off cloud saves') : t('Turn on cloud saves'), sub: cloudOn(g) ? t('Its saves stay on this PC from now on') : t('Its saves go to your account after you play'), icon: 'cloud', run: async () => { try { S.library[id] = await invoke('saves_cloud', { id, on: !cloudOn(g) }); toast(cloudOn(g) ? t('Cloud saves are off for it. What\'s in the cloud stays there.') : t('Cloud saves are on for it.')); } catch (e) { fail(e); } } }] : []), ...(window.tvBetaItem && window.tvBetaItem(id) ? [window.tvBetaItem(id)] : []), // The same switch as the game's Manage tab on the desktop, and the same skip list under Settings. ...(!g.local && window.autoUpdates ? [(() => { const on = window.autoUpdates(id); return { label: on ? t('Turn off automatic updates') : t('Update automatically'), sub: on ? t('Updates wait for you in Downloads') : t('Installs new releases as soon as the launcher finds them. Your saves are backed up first.'), icon: 'refresh', run: async () => { await window.toggleAutoUpdate(id); draw(true); } }; })()] : []), @@ -3172,7 +3173,7 @@ case 'lang': sfx('open'); return pickLang(); case 'drive-connect': return window.connectDrive().catch(fail); case 'drive-disconnect': return window.disconnectDrive().catch(fail); - case 'cloud-ask': await saveUi({ cloud_ask: (S.settings.ui || {}).cloud_ask === false }); return draw(true); + case 'cloud-all': await window.setCloudAll((S.settings.ui || {}).cloud_all !== true); return draw(true); case 'save-provider': return sheet(t('Save Destination'), [ { label: 'RecompStore', sub: t('Enable each game again after changing providers'), run: () => window.chooseSaveProvider('recompstore').catch(fail) }, { label: 'Google Drive', sub: t('Connect Google Drive first; enable each game again after changing providers'), run: () => S.saveProvider?.google?.connected ? window.chooseSaveProvider('google_drive').catch(fail) : window.connectDrive().catch(fail) },