From 526ee80b698cad19fc5367906063f33f2112dd50 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:46:41 +0000 Subject: [PATCH] fix(flow): harden prefixed routes, JSPB probes, and login promotion - Strip host, account, and organization prefixes in route guards - Forward authuser and pageId and batch cPZSdc with KV2T2d probes - Decode JSPB zero flags, sparse pivot fields, and KV2T2d codes - Require post-challenge Flow workspace visits before promotion - Preserve account routes and reopen LoginChrome on failed checks --- src/auth.rs | 252 +++++++++++++++++++++++------------- src/chrome.rs | 115 ++++++++++++----- src/engine.rs | 6 +- src/project.rs | 22 +++- src/project_route.rs | 277 +++++++++++++++++++++++++++++++++++----- ts/angular.ts | 140 ++++++++++++++++---- ts/check_auth.ts | 136 ++++++++++++++------ ts/dom.ts | 2 +- ts/resolve_video_url.ts | 4 +- ts/types.ts | 4 + 10 files changed, 730 insertions(+), 228 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 596c885..272a1d3 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -14,11 +14,14 @@ use std::time::Duration; use tokio::time::Instant; use url::Url; -use crate::config::{ - FLOW_SSO_URL, FLOW_URL, chrome_profile_dir, cookies_path, has_persisted_session, -}; +use crate::config::{FLOW_SSO_URL, chrome_profile_dir, cookies_path, has_persisted_session}; use crate::cookies::{has_google_auth_cookies, read_cookies_file}; use crate::engine::{ChromeEngine, ENGINE_NAME}; +use crate::project_route::{ + flow_route_prefix, flow_sso_url_for, flow_workspace_root_url, has_segment_prefix, + is_flow_origin_host, normalize_flow_path, prefix_has_fx_tools_flow, promotion_target_url, + strip_flow_route_prefix, +}; /// Maximum number of `/about` passive SSO redirect attempts during session promotion. const MAX_ABOUT_SSO_RETRIES: usize = 2; @@ -61,57 +64,21 @@ pub(crate) struct LoginParams { pub(crate) cookies: Option>>, } -/// Returns `true` when `path` equals `prefix` or begins with `prefix` plus `/`. -fn has_segment_prefix(path: &str, prefix: &str) -> bool { - path == prefix - || (path.len() > prefix.len() - && path.starts_with(prefix) - && path.as_bytes().get(prefix.len()) == Some(&b'/')) -} - -/// Normalizes a URL path to lowercase without trailing slashes, preserving `/`. -fn normalize_flow_path(raw: &str) -> String { - let lower = raw.trim().to_ascii_lowercase(); - let with_slash = if lower.starts_with('/') { - lower - } else { - format!("/{lower}") - }; - let trimmed = with_slash.trim_end_matches('/'); - if trimmed.is_empty() { - "/".to_string() - } else { - trimmed.to_string() - } -} - -/// Strips an optional `/fx` prefix from a normalized path. -fn strip_fx_prefix(clean_path: &str) -> &str { - if clean_path == "/fx" { - "/" - } else if let Some(rest) = clean_path.strip_prefix("/fx/") { - &clean_path[3..3 + 1 + rest.len()] - } else { - clean_path - } -} - /// Returns `true` when `clean_path` matches any of the 17 non-workspace Flow routes. fn is_non_workspace_flow_path(clean_path: &str) -> bool { - let rel = strip_fx_prefix(clean_path); + let rel = strip_flow_route_prefix(clean_path); if rel == "/flow" { return true; } NON_WORKSPACE_SEGMENT_PREFIXES .iter() - .any(|prefix| has_segment_prefix(rel, prefix)) + .any(|prefix| has_segment_prefix(&rel, prefix)) } /// Returns true when the URL targets a Google Flow host. pub(crate) fn is_flow_host_url(raw: &str) -> bool { Url::parse(raw).is_ok_and(|url| { - matches!(url.scheme(), "http" | "https") - && crate::project_route::is_flow_origin_host(url.host_str()) + matches!(url.scheme(), "http" | "https") && is_flow_origin_host(url.host_str()) }) } @@ -131,7 +98,7 @@ pub(crate) fn is_signed_in_flow_url(raw: &str) -> bool { return false; } let clean_path = normalize_flow_path(parsed.path()); - if on_labs && !has_segment_prefix(&clean_path, "/fx/tools/flow") { + if on_labs && !prefix_has_fx_tools_flow(&flow_route_prefix(&clean_path)) { return false; } !is_non_workspace_flow_path(&clean_path) @@ -158,14 +125,19 @@ pub(crate) async fn check_page_auth(engine: &ChromeEngine, reload_on_expired: bo return Value::Null; }; if reload_on_expired && state.get("token_expired").and_then(Value::as_bool) == Some(true) { - let target = if is_signed_in_flow_url(&url) { - url - } else { - FLOW_URL.to_string() - }; + let target = promotion_target_url(Some(&url)); if engine.navigate(&target).await.is_ok() { let mut refreshed = engine.current_url().await.unwrap_or_default(); - let _ = redirect_sso_if_about(engine, &mut refreshed).await; + if is_about_landing_url(&refreshed) { + let sso_ref = if flow_sso_url_for(&refreshed) == FLOW_SSO_URL { + &target + } else { + &refreshed + }; + let _ = engine.navigate(&flow_sso_url_for(sso_ref)).await; + wait_for_sso_redirect(engine).await; + refreshed = engine.current_url().await.unwrap_or_default(); + } if is_signed_in_flow_url(&refreshed) { return eval_check_auth_once(engine).await.unwrap_or(Value::Null); } @@ -230,20 +202,14 @@ pub(crate) fn is_about_landing_url(url: &str) -> bool { let Ok(parsed) = Url::parse(url) else { return url.contains("flow.google.com/about") || url.contains("/fx/about"); }; - let Some(host) = parsed.host_str().map(|h| h.to_ascii_lowercase()) else { - return false; - }; - let on_flow = - host == "flow.google.com" || host == "labs.google" || host.ends_with(".labs.google"); - if !on_flow { + if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { return false; } - let clean = normalize_flow_path(parsed.path()); - let rel = strip_fx_prefix(&clean); + let rel = strip_flow_route_prefix(parsed.path()); rel == "/flow" - || has_segment_prefix(rel, "/about") - || has_segment_prefix(rel, "/flow/about") - || has_segment_prefix(rel, "/tools/flow/about") + || has_segment_prefix(&rel, "/about") + || has_segment_prefix(&rel, "/flow/about") + || has_segment_prefix(&rel, "/tools/flow/about") } /// Returns `true` when `url` points to an interactive Google Accounts sign-in route. @@ -269,7 +235,8 @@ pub(crate) async fn wait_for_sso_redirect(engine: &ChromeEngine) { /// Follows the Google SSO entry URL and refreshes `url` when Chrome lands on an `/about` page. pub(crate) async fn redirect_sso_if_about(engine: &ChromeEngine, url: &mut String) -> Result<()> { if is_about_landing_url(url) { - engine.navigate(FLOW_SSO_URL).await?; + let sso = flow_sso_url_for(url); + engine.navigate(&sso).await?; wait_for_sso_redirect(engine).await; *url = engine.current_url().await.unwrap_or_default(); } @@ -280,11 +247,13 @@ pub(crate) async fn redirect_sso_if_about(engine: &ChromeEngine, url: &mut Strin async fn ensure_flow_session_url(engine: &ChromeEngine) { let mut cur = engine.current_url().await.unwrap_or_default(); if !is_signed_in_flow_url(&cur) { - let _ = engine.navigate(FLOW_URL).await; + let target = flow_workspace_root_url(&cur); + let _ = engine.navigate(&target).await; cur = engine.current_url().await.unwrap_or_default(); } if is_about_landing_url(&cur) || !is_signed_in_flow_url(&cur) { - let _ = engine.navigate(FLOW_SSO_URL).await; + let sso = flow_sso_url_for(&cur); + let _ = engine.navigate(&sso).await; wait_for_sso_redirect(engine).await; } } @@ -292,7 +261,10 @@ async fn ensure_flow_session_url(engine: &ChromeEngine) { /// Promotes the interactive Chrome profile into background CDP mode and verifies Google Flow sign-in. async fn finalize_promoted_login(engine: &ChromeEngine, start_url: &str) -> Result> { engine.promote_login_chrome(start_url).await?; + let base_sso = flow_sso_url_for(start_url); let mut about_retries = 0usize; + let mut blocked_polls = 0usize; + let mut rejected_auth_polls = 0usize; for _ in 0..30 { let cur = engine.current_url().await.unwrap_or_default(); if is_interactive_signin_url(&cur) { @@ -303,7 +275,13 @@ async fn finalize_promoted_login(engine: &ChromeEngine, start_url: &str) -> Resu break; } about_retries += 1; - let _ = engine.navigate(FLOW_SSO_URL).await; + let cur_sso = flow_sso_url_for(&cur); + let sso_target = if cur_sso == FLOW_SSO_URL { + &base_sso + } else { + &cur_sso + }; + let _ = engine.navigate(sso_target).await; wait_for_sso_redirect(engine).await; let after_sso = engine.current_url().await.unwrap_or_default(); if is_interactive_signin_url(&after_sso) { @@ -311,15 +289,43 @@ async fn finalize_promoted_login(engine: &ChromeEngine, start_url: &str) -> Resu } continue; } - if is_signed_in_flow_url(&cur) - && let Some(count) = check_fully_signed_in(engine).await - { - let final_url = engine.current_url().await.unwrap_or_default(); - return Ok(Some(signed_in_login_result( - "interactive-chrome", - count, - final_url, - ))); + if is_flow_host_url(&cur) && !is_signed_in_flow_url(&cur) { + blocked_polls += 1; + if blocked_polls >= 2 { + break; + } + tokio::time::sleep(Duration::from_millis(500)).await; + continue; + } + blocked_polls = 0; + if is_signed_in_flow_url(&cur) && !cur.contains("accounts.google.com") { + let cookies = engine.flow_cookies().await.unwrap_or_default(); + if has_google_auth_cookies(&cookies) { + let auth_state = check_page_auth(engine, true).await; + if auth_state.get("signed_in").and_then(Value::as_bool) == Some(true) { + let final_url = engine.current_url().await.unwrap_or_default(); + return Ok(Some(signed_in_login_result( + "interactive-chrome", + cookies.len(), + final_url, + ))); + } + if auth_state + .get("explicit_signed_out") + .and_then(Value::as_bool) + == Some(true) + { + rejected_auth_polls += 1; + if rejected_auth_polls >= 2 { + break; + } + } + } else { + rejected_auth_polls += 1; + if rejected_auth_polls >= 4 { + break; + } + } } tokio::time::sleep(Duration::from_millis(500)).await; } @@ -334,12 +340,15 @@ async fn login_with_chrome( wait_for_login: bool, force: bool, ) -> Result { + let clamped_secs = timeout_secs.clamp(15, 3600); + let deadline = Instant::now() + Duration::from_secs(clamped_secs); + if force { crate::instance::acquire_instance_lock()?; remove_cookies_file(); engine.launch_interactive_login(FLOW_SSO_URL, true).await?; } else if engine.has_login_chrome().await { - if let Some(st) = engine.poll_login_chrome().await? { + if !wait_for_login && let Some(st) = engine.poll_login_chrome().await? { if let Some(rejected) = st.rejected_url { engine.shutdown().await; anyhow::bail!( @@ -347,13 +356,19 @@ async fn login_with_chrome( rejected ); } - if st.exited || st.has_google_auth_cookies { - if let Some(res) = finalize_promoted_login(engine, FLOW_URL).await? { + if st.exited || st.ready_flow_url.is_some() { + let target = promotion_target_url(st.ready_flow_url.as_deref()); + if st.ready_flow_url.is_some() && !st.exited { + tokio::time::sleep(Duration::from_secs(2)).await; + } + if let Some(res) = finalize_promoted_login(engine, &target).await? { return Ok(res); } if st.exited { anyhow::bail!("Sign-in window was closed before Google Sign-In completed."); } + let resume_sso = flow_sso_url_for(&target); + engine.launch_interactive_login(&resume_sso, false).await?; } } if !engine.has_login_chrome().await { @@ -368,13 +383,14 @@ async fn login_with_chrome( return Ok(signed_in_login_result("existing-session", count, final_url)); } } - engine.launch_interactive_login(FLOW_SSO_URL, false).await?; + let resume_sso = flow_sso_url_for(&engine.current_url().await.unwrap_or_default()); + engine.launch_interactive_login(&resume_sso, false).await?; } if !wait_for_login { let st = engine.poll_login_chrome().await?; let url = st - .and_then(|s| s.rejected_url) + .and_then(|s| s.ready_flow_url.or(s.rejected_url)) .unwrap_or_else(|| FLOW_SSO_URL.to_string()); return Ok(json!({ "ok": true, @@ -389,9 +405,6 @@ async fn login_with_chrome( })); } - let clamped_secs = timeout_secs.clamp(15, 3600); - let deadline = Instant::now() + Duration::from_secs(clamped_secs); - loop { let Some(st) = engine.poll_login_chrome().await? else { anyhow::bail!("Sign-in window was closed before Google Sign-In completed."); @@ -405,23 +418,33 @@ async fn login_with_chrome( ); } - if st.exited || st.has_google_auth_cookies { - if st.has_google_auth_cookies && !st.exited { - tokio::time::sleep(Duration::from_secs(4)).await; + if st.exited || st.ready_flow_url.is_some() { + let target = promotion_target_url(st.ready_flow_url.as_deref()); + if st.ready_flow_url.is_some() && !st.exited { + tokio::time::sleep(Duration::from_secs(2)).await; } - if let Some(res) = finalize_promoted_login(engine, FLOW_URL).await? { + if let Some(res) = finalize_promoted_login(engine, &target).await? { return Ok(res); } if st.exited { anyhow::bail!("Sign-in window was closed before Google Sign-In completed."); } - anyhow::bail!( - "Google Sign-In wrote authentication cookies, but workspace verification did not succeed. Run flow_login again." - ); + if Instant::now() >= deadline { + engine.shutdown().await; + anyhow::bail!( + "Timed out after {}s waiting for Google Sign-In in Chrome.", + clamped_secs, + ); + } + let resume_sso = flow_sso_url_for(&target); + engine.launch_interactive_login(&resume_sso, false).await?; + tokio::time::sleep(Duration::from_secs(1)).await; + continue; } if Instant::now() >= deadline { - if let Ok(Some(res)) = finalize_promoted_login(engine, FLOW_URL).await { + let target = promotion_target_url(st.ready_flow_url.as_deref()); + if let Ok(Some(res)) = finalize_promoted_login(engine, &target).await { return Ok(res); } engine.shutdown().await; @@ -488,9 +511,29 @@ pub(crate) async fn handle_login(engine: &ChromeEngine, req: LoginParams) -> Res if engine.has_login_chrome().await && let Some(st) = engine.poll_login_chrome().await? { - if st.exited || st.has_google_auth_cookies { + if st.exited || st.ready_flow_url.is_some() { promotion_attempted = true; - let _ = finalize_promoted_login(engine, FLOW_URL).await; + let target = promotion_target_url(st.ready_flow_url.as_deref()); + if st.ready_flow_url.is_some() && !st.exited { + tokio::time::sleep(Duration::from_secs(2)).await; + } + let promoted = finalize_promoted_login(engine, &target).await?; + if promoted.is_none() && !st.exited && st.rejected_url.is_none() { + let resume_sso = flow_sso_url_for(&target); + engine.launch_interactive_login(&resume_sso, false).await?; + return Ok(json!({ + "ok": true, + "action": "status", + "engine": ENGINE_NAME, + "pageReady": false, + "windowVisible": true, + "cdpEndpoint": Value::Null, + "cookiesSaved": cookies_path().is_file(), + "profileDir": chrome_profile_dir().to_string_lossy(), + "url": resume_sso, + "signedIn": false, + })); + } } else { return Ok(json!({ "ok": true, @@ -555,3 +598,30 @@ pub(crate) async fn handle_login(engine: &ChromeEngine, req: LoginParams) -> Res other => anyhow::bail!("Unknown login action: {}", other), } } + +/// Polls an active interactive Chrome sign-in window for `flow_status`, promoting when ready and returning `Some(url)` while sign-in remains open. +pub(crate) async fn poll_login_status_url(engine: &ChromeEngine, probe: bool) -> Option { + if !engine.has_login_chrome().await { + return None; + } + let Ok(Some(st)) = engine.poll_login_chrome().await else { + return None; + }; + if !probe && (st.exited || st.ready_flow_url.is_some()) { + let target = promotion_target_url(st.ready_flow_url.as_deref()); + if st.ready_flow_url.is_some() && !st.exited { + tokio::time::sleep(Duration::from_secs(2)).await; + } + let promoted = finalize_promoted_login(engine, &target) + .await + .ok() + .flatten(); + if promoted.is_none() && !st.exited && st.rejected_url.is_none() { + let resume_sso = flow_sso_url_for(&target); + let _ = engine.launch_interactive_login(&resume_sso, false).await; + return Some(resume_sso); + } + return None; + } + Some(st.rejected_url.unwrap_or_else(|| FLOW_SSO_URL.to_string())) +} diff --git a/src/chrome.rs b/src/chrome.rs index 7164984..e788b60 100644 --- a/src/chrome.rs +++ b/src/chrome.rs @@ -53,8 +53,10 @@ impl Drop for LoginChrome { pub(crate) struct LoginProfileProbe { /// Google Accounts rejection URL observed in profile history. pub(crate) rejected_url: Option, - /// True when core Google Sign-In cookies were written since launch. + /// True when core Google Sign-In cookies exist in the profile. pub(crate) has_google_auth_cookies: bool, + /// Verified Google Flow workspace URL visited after sign-in challenges when Google cookies exist. + pub(crate) ready_flow_url: Option, } /// Sets child-process English locale environment variables when unset in the parent environment. @@ -328,61 +330,105 @@ fn copy_sqlite_files_to_scratch( Some(dst) } -/// Inspects a scratch copy of Chrome's `History` SQLite database for Google Accounts rejection URLs. -fn probe_history_db(scratch_history: &Path, min_webkit_us: i64, probe: &mut LoginProfileProbe) { +/// Returns `true` when `raw` points to a Google Accounts sign-in or challenge route. +fn is_google_accounts_challenge_url(raw: &str) -> bool { + let Ok(parsed) = url::Url::parse(raw) else { + return raw.contains("accounts.google.com"); + }; + let Some(host) = parsed.host_str() else { + return false; + }; + if !host.eq_ignore_ascii_case("accounts.google.com") { + return false; + } + let path = parsed.path(); + !path.starts_with("/RotateCookiesPage") + && !path.starts_with("/CheckConnection") + && !path.starts_with("/ListAccounts") +} + +/// Inspects a scratch copy of Chrome's `History` SQLite database for rejection URLs and post-challenge Flow workspace visits. +fn probe_history_db( + scratch_history: &Path, + min_webkit_us: i64, + probe: &mut LoginProfileProbe, +) -> Option { let Ok(conn) = rusqlite::Connection::open(scratch_history) else { - return; + return None; }; let Ok(mut stmt) = conn.prepare( - "SELECT url FROM urls WHERE last_visit_time >= ?1 ORDER BY last_visit_time DESC, id DESC LIMIT 25", + "SELECT url FROM urls WHERE last_visit_time >= ?1 ORDER BY last_visit_time DESC, id DESC LIMIT 50", ) else { - return; + return None; }; let Ok(rows) = stmt.query_map([min_webkit_us], |row| row.get::<_, String>(0)) else { - return; + return None; }; + let mut candidate_flow_url = None; + let mut decided_latest = false; for url in rows.flatten() { - if url.contains("accounts.google.com/v3/signin/rejected") { - probe.rejected_url = Some(url); - return; + if probe.rejected_url.is_none() && url.contains("accounts.google.com/v3/signin/rejected") { + probe.rejected_url = Some(url.clone()); } + if !decided_latest { + if crate::auth::is_signed_in_flow_url(&url) { + candidate_flow_url = Some(url); + decided_latest = true; + } else if crate::auth::is_flow_host_url(&url) || is_google_accounts_challenge_url(&url) + { + decided_latest = true; + } + } + } + if probe.rejected_url.is_some() { + return None; } + candidate_flow_url } -/// Returns `true` when a scratch copy of Chrome's `Cookies` database holds Google auth cookies. -fn probe_cookies_db(scratch_cookies: &Path, min_webkit_us: i64) -> bool { +/// Returns `true` when a scratch copy of Chrome's `Cookies` database holds valid Google auth cookies. +fn probe_cookies_db(scratch_cookies: &Path, now_webkit_us: i64) -> bool { let Ok(conn) = rusqlite::Connection::open(scratch_cookies) else { return false; }; - let Ok(mut stmt) = - conn.prepare("SELECT host_key, name FROM cookies WHERE last_update_utc >= ?1") - else { + if let Ok(mut stmt) = + conn.prepare("SELECT host_key, name FROM cookies WHERE expires_utc = 0 OR expires_utc > ?1") + && let Ok(rows) = stmt.query_map([now_webkit_us], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + }) + { + return rows + .flatten() + .any(|(host, name)| is_google_auth_cookie_pair(&host, &name)); + } + let Ok(mut stmt) = conn.prepare("SELECT host_key, name FROM cookies") else { return false; }; - let Ok(rows) = stmt.query_map([min_webkit_us], |row| { + let Ok(rows) = stmt.query_map([], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) }) else { return false; }; - for pair in rows.flatten() { - if is_google_auth_cookie_pair(&pair.0, &pair.1) { - return true; - } - } - false + rows.flatten() + .any(|(host, name)| is_google_auth_cookie_pair(&host, &name)) } -/// Inspects Chrome `History` and `Cookies` files for entries updated since `started_at`. +/// Inspects Chrome `History` and `Cookies` files for Google cookies and post-challenge Flow workspace visits since `started_at`. pub(crate) async fn inspect_login_profile( profile_dir: &Path, started_at: SystemTime, ) -> LoginProfileProbe { - const WEBKIT_EPOCH_OFFSET_SECS: i64 = 11_644_473_600; - let unix_secs = started_at + const WEBKIT_EPOCH_OFFSET_US: i64 = 11_644_473_600 * 1_000_000; + let started_unix_us = started_at .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs() as i64) + .map(|d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX / 2)) .unwrap_or(0); - let min_webkit_us = (unix_secs.saturating_sub(2) + WEBKIT_EPOCH_OFFSET_SECS) * 1_000_000; + let now_unix_us = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX / 2)) + .unwrap_or(started_unix_us); + let min_webkit_us = started_unix_us.saturating_add(WEBKIT_EPOCH_OFFSET_US); + let now_webkit_us = now_unix_us.saturating_add(WEBKIT_EPOCH_OFFSET_US); let dir = profile_dir.to_path_buf(); tokio::task::spawn_blocking(move || { @@ -393,11 +439,10 @@ pub(crate) async fn inspect_login_profile( }; let history_src = dir.join("Default").join("History"); - if let Some(scratch_history) = - copy_sqlite_files_to_scratch(&history_src, scratch.path(), "History") - { - probe_history_db(&scratch_history, min_webkit_us, &mut probe); - } + let candidate_flow_url = + copy_sqlite_files_to_scratch(&history_src, scratch.path(), "History").and_then( + |scratch_history| probe_history_db(&scratch_history, min_webkit_us, &mut probe), + ); let cookie_candidates = [ dir.join("Default").join("Cookies"), @@ -406,13 +451,17 @@ pub(crate) async fn inspect_login_profile( for (idx, src) in cookie_candidates.iter().enumerate() { let base = format!("Cookies_{idx}"); if let Some(scratch_cookies) = copy_sqlite_files_to_scratch(src, scratch.path(), &base) - && probe_cookies_db(&scratch_cookies, min_webkit_us) + && probe_cookies_db(&scratch_cookies, now_webkit_us) { probe.has_google_auth_cookies = true; break; } } + if probe.has_google_auth_cookies && probe.rejected_url.is_none() { + probe.ready_flow_url = candidate_flow_url; + } + probe }) .await diff --git a/src/engine.rs b/src/engine.rs index 110a532..2118548 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -138,8 +138,8 @@ pub(crate) struct LoginPollStatus { pub(crate) exited: bool, /// Google Accounts rejection URL observed during sign-in, if any. pub(crate) rejected_url: Option, - /// True when Google authentication cookies exist in the login profile. - pub(crate) has_google_auth_cookies: bool, + /// Verified Google Flow workspace URL visited after sign-in challenges, if ready. + pub(crate) ready_flow_url: Option, } /// Manages the Chrome process and main page for one MCP server instance. @@ -244,7 +244,7 @@ impl ChromeEngine { Ok(Some(LoginPollStatus { exited, rejected_url: probe.rejected_url, - has_google_auth_cookies: probe.has_google_auth_cookies, + ready_flow_url: probe.ready_flow_url, })) } diff --git a/src/project.rs b/src/project.rs index e11643e..9ee3902 100644 --- a/src/project.rs +++ b/src/project.rs @@ -13,7 +13,10 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use tokio::time::{Duration, Instant}; -use crate::auth::{check_page_auth, check_page_signed_in, is_flow_host_url, redirect_sso_if_about}; +use crate::auth::{ + check_page_auth, check_page_signed_in, is_flow_host_url, poll_login_status_url, + redirect_sso_if_about, +}; use crate::config::{FLOW_URL, has_persisted_session}; use crate::engine::{ChromeEngine, ENGINE_NAME}; pub(crate) use crate::project_route::{ @@ -172,6 +175,23 @@ async fn eval_project_nav(engine: &ChromeEngine, action: &str) -> Result /// Reads Google Flow session state without navigation when `probe` is `true`, /// or opens Flow when `probe` is `false`. Reads the store without changing project routes. pub(crate) async fn get_flow_state(engine: &ChromeEngine, probe: bool) -> FlowStatus { + if let Some(login_url) = poll_login_status_url(engine, probe).await { + return FlowStatus { + signed_in: false, + in_project: false, + project: None, + project_id: None, + url: Some(login_url), + credits: None, + assets_count: None, + collections_count: None, + page_ready: false, + engine: ENGINE_NAME.to_string(), + frontend: None, + error: None, + }; + } + if !probe && !engine.has_page().await && !has_persisted_session() { return FlowStatus { signed_in: false, diff --git a/src/project_route.rs b/src/project_route.rs index 5ce889c..8babac0 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -5,7 +5,7 @@ use url::Url; -use crate::config::FLOW_URL; +use crate::config::{FLOW_SSO_URL, FLOW_URL}; /// Extracts the `/project/` segment from a Flow project URL. pub(crate) fn project_id_from_url(url: &str) -> Option { @@ -25,31 +25,80 @@ pub(crate) fn is_flow_origin_host(host: Option<&str>) -> bool { || h.to_ascii_lowercase().ends_with(".labs.google") } -/// Extracts the active route prefix before `/project/` from a Flow URL path. -fn flow_route_prefix(path: &str) -> String { - if let Some((before, _)) = path.split_once("/project/") { - return before.trim_end_matches('/').to_string(); +/// Returns `true` when `path` equals `prefix` or starts with `prefix` followed by `/`. +pub(crate) fn has_segment_prefix(path: &str, prefix: &str) -> bool { + path == prefix + || (path.len() > prefix.len() + && path.starts_with(prefix) + && path.as_bytes().get(prefix.len()) == Some(&b'/')) +} + +/// Normalizes a URL path to lowercase without trailing slashes while keeping `/` for root. +pub(crate) fn normalize_flow_path(raw: &str) -> String { + let lower = raw.trim().to_ascii_lowercase(); + let with_slash = if lower.starts_with('/') { + lower + } else { + format!("/{lower}") + }; + let trimmed = with_slash.trim_end_matches('/'); + if trimmed.is_empty() { + "/".to_string() + } else { + trimmed.to_string() } +} + +/// Returns `true` when `segment` is a reserved Flow route word rather than an organization ID. +fn is_reserved_flow_segment(segment: &str) -> bool { + matches!( + segment.to_ascii_lowercase().as_str(), + "project" + | "projects" + | "about" + | "shared" + | "flow" + | "tools" + | "fx" + | "u" + | "unsupported-country" + | "unsupported-browser" + | "unavailable" + | "age-restricted" + | "privacy" + | "credits-terms" + | "academy" + | "404" + | "login" + | "search" + | "changelogs" + | "debug" + ) +} + +/// Extracts the active `/fx/tools/flow`, `/u/`, and `//global` prefix from `path`. +pub(crate) fn flow_route_prefix(path: &str) -> String { let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); let mut prefix = Vec::new(); let mut i = 0; while i < segs.len() { - if segs[i..].starts_with(&["fx", "tools", "flow"]) { + if i + 2 < segs.len() + && segs[i].eq_ignore_ascii_case("fx") + && segs[i + 1].eq_ignore_ascii_case("tools") + && segs[i + 2].eq_ignore_ascii_case("flow") + { prefix.extend_from_slice(&["fx", "tools", "flow"]); i += 3; } else if i + 1 < segs.len() - && segs[i] == "u" + && segs[i].eq_ignore_ascii_case("u") && !segs[i + 1].is_empty() && segs[i + 1].bytes().all(|b| b.is_ascii_digit()) { prefix.extend_from_slice(&["u", segs[i + 1]]); i += 2; } else if i + 1 < segs.len() - && segs[i + 1] == "global" - && !matches!( - segs[i], - "project" | "projects" | "about" | "shared" | "flow" | "tools" | "fx" | "u" - ) + && segs[i + 1].eq_ignore_ascii_case("global") + && !is_reserved_flow_segment(segs[i]) { prefix.extend_from_slice(&[segs[i], "global"]); i += 2; @@ -64,7 +113,178 @@ fn flow_route_prefix(path: &str) -> String { } } -/// Builds a Google Flow `/project/` or subroute URL with active prefixes, `hl=en`, and `authuser`. +/// Normalizes `path` and strips `/fx/tools/flow`, `/u/`, `//global`, and `/fx` prefixes. +pub(crate) fn strip_flow_route_prefix(path: &str) -> String { + let clean = normalize_flow_path(path); + let prefix = flow_route_prefix(&clean); + let after_prefix = if prefix.is_empty() { + clean.as_str() + } else { + let rest = &clean[prefix.len()..]; + if rest.is_empty() { "/" } else { rest } + }; + if after_prefix == "/fx" { + "/".to_string() + } else if let Some(rest) = after_prefix.strip_prefix("/fx/") { + format!("/{rest}") + } else { + after_prefix.to_string() + } +} + +/// Returns `true` when `prefix` includes the `/fx/tools/flow` host mount. +pub(crate) fn prefix_has_fx_tools_flow(prefix: &str) -> bool { + let lower = prefix.to_ascii_lowercase(); + lower == "/fx/tools/flow" + || lower.starts_with("/fx/tools/flow/") + || lower.ends_with("/fx/tools/flow") + || lower.contains("/fx/tools/flow/") +} + +/// Reads a trimmed non-empty query parameter value from `url`. +fn query_param(url: &Url, key: &str) -> Option { + url.query_pairs() + .find(|(k, _)| k == key) + .map(|(_, v)| v.trim().to_string()) + .filter(|v| !v.is_empty()) +} + +/// Extracts the `/u/` account index from `path` when present. +fn path_authuser(path: &str) -> Option { + let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + let mut i = 0; + while i + 1 < segs.len() { + if segs[i].eq_ignore_ascii_case("u") + && !segs[i + 1].is_empty() + && segs[i + 1].bytes().all(|b| b.is_ascii_digit()) + { + return Some(segs[i + 1].to_string()); + } + i += 1; + } + None +} + +/// Writes `hl=en` plus optional `authuser` and `pageId` onto `url`. +fn apply_account_query_params(url: &mut Url, authuser: Option<&str>, page_id: Option<&str>) { + url.set_fragment(None); + let mut qp = url.query_pairs_mut(); + qp.clear(); + qp.append_pair("hl", "en"); + if let Some(au) = authuser { + qp.append_pair("authuser", au); + } + if let Some(pid) = page_id { + qp.append_pair("pageId", pid); + } +} + +/// Builds a Flow workspace root URL that keeps the host, route prefixes, `hl=en`, `authuser`, and `pageId` of `reference_url`. +pub(crate) fn flow_workspace_root_url(reference_url: &str) -> String { + let Some(mut parsed) = Url::parse(reference_url) + .ok() + .filter(|u| matches!(u.scheme(), "https" | "http") && is_flow_origin_host(u.host_str())) + else { + return FLOW_URL.to_string(); + }; + let on_labs = parsed.host_str().is_some_and(|h| { + h.eq_ignore_ascii_case("labs.google") || h.to_ascii_lowercase().ends_with(".labs.google") + }); + let prefix = flow_route_prefix(parsed.path()); + if on_labs && !prefix_has_fx_tools_flow(&prefix) { + return FLOW_URL.to_string(); + } + let authuser = query_param(&parsed, "authuser"); + let page_id = query_param(&parsed, "pageId"); + let root_path = if prefix.is_empty() { + "/".to_string() + } else { + format!("{prefix}/") + }; + parsed.set_path(&root_path); + apply_account_query_params(&mut parsed, authuser.as_deref(), page_id.as_deref()); + parsed.into() +} + +/// Normalizes a verified Flow workspace URL for background promotion while keeping its route, `hl=en`, `authuser`, and `pageId`. +pub(crate) fn promotion_target_url(ready_flow_url: Option<&str>) -> String { + let Some(raw) = ready_flow_url else { + return FLOW_URL.to_string(); + }; + if !crate::auth::is_signed_in_flow_url(raw) { + return flow_workspace_root_url(raw); + } + let Some(mut parsed) = Url::parse(raw) + .ok() + .filter(|u| matches!(u.scheme(), "https" | "http") && is_flow_origin_host(u.host_str())) + else { + return FLOW_URL.to_string(); + }; + let pairs: Vec<(String, String)> = parsed + .query_pairs() + .filter(|(k, _)| k != "hl") + .map(|(k, v)| (k.into_owned(), v.into_owned())) + .collect(); + parsed.set_fragment(None); + { + let mut qp = parsed.query_pairs_mut(); + qp.clear(); + qp.append_pair("hl", "en"); + for (k, v) in &pairs { + let trimmed = v.trim(); + if !trimmed.is_empty() { + qp.append_pair(k, trimmed); + } + } + } + parsed.into() +} + +/// Builds a Google Accounts passive SSO URL whose `continue` target and `authuser` match `reference_url`. +pub(crate) fn flow_sso_url_for(reference_url: &str) -> String { + let parsed_ref = Url::parse(reference_url) + .ok() + .filter(|u| matches!(u.scheme(), "https" | "http") && is_flow_origin_host(u.host_str())); + let Some(ref_url) = parsed_ref else { + return FLOW_SSO_URL.to_string(); + }; + let continue_url = if crate::auth::is_signed_in_flow_url(reference_url) { + promotion_target_url(Some(reference_url)) + } else { + flow_workspace_root_url(reference_url) + }; + let authuser = query_param(&ref_url, "authuser").or_else(|| path_authuser(ref_url.path())); + let page_id = query_param(&ref_url, "pageId"); + if continue_url == FLOW_URL && authuser.is_none() && page_id.is_none() { + return FLOW_SSO_URL.to_string(); + } + let Ok(mut sso) = Url::parse(FLOW_SSO_URL) else { + return FLOW_SSO_URL.to_string(); + }; + let existing: Vec<(String, String)> = sso + .query_pairs() + .filter(|(k, _)| k != "continue" && k != "followup" && k != "authuser" && k != "pageId") + .map(|(k, v)| (k.into_owned(), v.into_owned())) + .collect(); + { + let mut qp = sso.query_pairs_mut(); + qp.clear(); + for (k, v) in &existing { + qp.append_pair(k, v); + } + if let Some(au) = authuser.as_deref() { + qp.append_pair("authuser", au); + } + if let Some(pid) = page_id.as_deref() { + qp.append_pair("pageId", pid); + } + qp.append_pair("continue", &continue_url); + qp.append_pair("followup", &continue_url); + } + sso.into() +} + +/// Builds a Google Flow `/project/` or subroute URL with active prefixes, `hl=en`, `authuser`, and `pageId`. pub(crate) fn project_subroute_url( reference_url: &str, project_id: &str, @@ -75,14 +295,21 @@ pub(crate) fn project_subroute_url( .filter(|u| matches!(u.scheme(), "https" | "http") && is_flow_origin_host(u.host_str())); let prefix = parsed .as_ref() - .map(|u| flow_route_prefix(u.path())) + .map(|u| { + if let Some((before, _)) = u.path().split_once("/project/") { + let candidate = flow_route_prefix(before); + if !candidate.is_empty() || before.trim_matches('/').is_empty() { + candidate + } else { + before.trim_end_matches('/').to_string() + } + } else { + flow_route_prefix(u.path()) + } + }) .unwrap_or_default(); - let authuser = parsed.as_ref().and_then(|u| { - u.query_pairs() - .find(|(k, _)| k == "authuser") - .map(|(_, v)| v.trim().to_string()) - .filter(|v| !v.is_empty()) - }); + let authuser = parsed.as_ref().and_then(|u| query_param(u, "authuser")); + let page_id = parsed.as_ref().and_then(|u| query_param(u, "pageId")); let clean_sub = subroute.trim_start_matches('/'); let route_path = if clean_sub.is_empty() { format!("{prefix}/project/{project_id}") @@ -91,15 +318,7 @@ pub(crate) fn project_subroute_url( }; if let Some(mut base) = parsed.or_else(|| Url::parse(FLOW_URL).ok()) { base.set_path(&route_path); - base.set_fragment(None); - { - let mut qp = base.query_pairs_mut(); - qp.clear(); - qp.append_pair("hl", "en"); - if let Some(au) = authuser.as_deref() { - qp.append_pair("authuser", au); - } - } + apply_account_query_params(&mut base, authuser.as_deref(), page_id.as_deref()); return base.into(); } format!("https://flow.google.com{route_path}?hl=en") diff --git a/ts/angular.ts b/ts/angular.ts index 8b0bbf0..bcd50f5 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -170,50 +170,82 @@ export function withLViewMapCapture( const routerQueryParamKeys = new WeakMap(); /** Builds the query parameters that Google Flow routes keep across transitions. */ -function flowQueryParams(search: string = location.search): Record { +export function flowQueryParams(search: string = location.search): Record { const params: Record = { hl: "en" }; - const authuser = new URLSearchParams(search).get("authuser")?.trim(); + const qp = new URLSearchParams(search); + const authuser = qp.get("authuser")?.trim(); if (authuser) { params.authuser = authuser; } + const pageId = qp.get("pageId")?.trim(); + if (pageId) { + params.pageId = pageId; + } return params; } -/** Extracts the active route prefix before `/project/` from the current page URL. */ -function activeProjectPrefix(): string { - const path = location.pathname || ""; - const projectIdx = path.indexOf("/project/"); - if (projectIdx >= 0) { - return path.slice(0, projectIdx).replace(/\/+$/, ""); - } - const baseHref = document.head?.querySelector("base")?.getAttribute("href"); - if (baseHref) { - try { - const basePath = new URL(baseHref, location.origin).pathname.replace(/\/+$/, ""); - if (basePath && (path === basePath || path.startsWith(`${basePath}/`))) { - return basePath; - } - } catch { - // Fall through to segment check. - } - } - const segs = path.split("/").filter(Boolean); +/** Reserved top-level Flow route segments that must not match `` in `//global`. */ +const RESERVED_FLOW_SEGMENTS = new Set([ + "project", + "projects", + "about", + "shared", + "flow", + "tools", + "fx", + "u", + "unsupported-country", + "unsupported-browser", + "unavailable", + "age-restricted", + "privacy", + "credits-terms", + "academy", + "404", + "login", + "search", + "changelogs", + "debug", +]); + +/** Returns `true` when `path` equals `prefix` or begins with `prefix` plus `/`. */ +export function hasSegmentPrefix(path: string, prefix: string): boolean { + return path === prefix || path.startsWith(`${prefix}/`); +} + +/** Normalizes a URL pathname to lowercase without trailing slashes while preserving `/`. */ +export function normalizeFlowPathname(raw: string): string { + const lower = (raw || "/").trim().toLowerCase(); + const withSlash = lower.startsWith("/") ? lower : `/${lower}`; + const trimmed = withSlash.replace(/\/+$/, ""); + return trimmed || "/"; +} + +/** Extracts the active `/fx/tools/flow`, `/u/`, and `//global` prefix from `pathname`. */ +export function flowRoutePrefix(pathname: string): string { + const segs = (pathname || "").split("/").filter(Boolean); const prefixSegs: string[] = []; let i = 0; while (i < segs.length) { if ( - segs[i] === "fx" && - segs[i + 1] === "tools" && - segs[i + 2] === "flow" + i + 2 < segs.length && + segs[i].toLowerCase() === "fx" && + segs[i + 1].toLowerCase() === "tools" && + segs[i + 2].toLowerCase() === "flow" ) { prefixSegs.push("fx", "tools", "flow"); i += 3; - } else if (segs[i] === "u" && /^\d+$/.test(segs[i + 1] || "")) { + } else if ( + i + 1 < segs.length && + segs[i].toLowerCase() === "u" && + /^\d+$/.test(segs[i + 1]) + ) { prefixSegs.push("u", segs[i + 1]); i += 2; } else if ( - segs[i + 1] === "global" && - !/^(?:project|projects|about|shared|flow|tools|fx|u)$/.test(segs[i]) + i + 1 < segs.length && + segs[i + 1].toLowerCase() === "global" && + !RESERVED_FLOW_SEGMENTS.has(segs[i].toLowerCase()) ) { prefixSegs.push(segs[i], "global"); i += 2; @@ -224,6 +256,60 @@ function activeProjectPrefix(): string { return prefixSegs.length > 0 ? `/${prefixSegs.join("/")}` : ""; } +/** Normalizes `pathname` and strips `/fx/tools/flow`, `/u/`, `//global`, and `/fx` prefixes. */ +export function stripFlowRoutePrefix(pathname: string): string { + const clean = normalizeFlowPathname(pathname); + const prefix = flowRoutePrefix(clean); + const afterPrefix = prefix ? clean.slice(prefix.length) || "/" : clean; + if (afterPrefix === "/fx") { + return "/"; + } + if (afterPrefix.startsWith("/fx/")) { + return afterPrefix.slice(3); + } + return afterPrefix; +} + +/** Returns `true` when `prefix` contains the `/fx/tools/flow` host mount. */ +export function prefixHasFxToolsFlow(prefix: string): boolean { + const lower = prefix.toLowerCase(); + return ( + lower === "/fx/tools/flow" || + lower.startsWith("/fx/tools/flow/") || + lower.endsWith("/fx/tools/flow") || + lower.includes("/fx/tools/flow/") + ); +} + +/** Extracts the `/u/` account selector from `pathname` when present. */ +export function pathAuthuser(pathname: string): string | null { + const match = /(?:^|\/)u\/(\d+)(?:\/|$)/i.exec(pathname || ""); + return match ? match[1] : null; +} + +/** Extracts the active route prefix before `/project/` from the current page URL. */ +function activeProjectPrefix(): string { + const path = location.pathname || ""; + const projectIdx = path.indexOf("/project/"); + if (projectIdx >= 0) { + const before = path.slice(0, projectIdx); + const parsed = flowRoutePrefix(before); + return parsed || before.replace(/\/+$/, ""); + } + const baseHref = document.head?.querySelector("base")?.getAttribute("href"); + if (baseHref) { + try { + const basePath = new URL(baseHref, location.origin).pathname.replace(/\/+$/, ""); + if (basePath && (path === basePath || path.startsWith(`${basePath}/`))) { + return basePath; + } + } catch { + // Fall through to segment check. + } + } + return flowRoutePrefix(path); +} + /** Discovers the query-parameter key on `NavigationExtras` via `UrlSerializer.parse` on `router`. */ function routerQueryParamsKey(router: AngularRouter): string { const cached = routerQueryParamKeys.get(router); diff --git a/ts/check_auth.ts b/ts/check_auth.ts index 7a94a33..8381ade 100644 --- a/ts/check_auth.ts +++ b/ts/check_auth.ts @@ -3,11 +3,24 @@ // Verify Google Flow workspace access with route guards, Wiz tokens, and a read-only probe. +import { + flowQueryParams, + flowRoutePrefix, + hasSegmentPrefix, + normalizeFlowPathname, + pathAuthuser, + prefixHasFxToolsFlow, + stripFlowRoutePrefix, +} from "./angular"; +import { isJspbMessage, jspbField } from "./resolve_video_url"; import type { AuthCheckResult } from "./types"; /** Read-only `FLOW_APP_CONFIG` RPC identifier in the Flow workspace route guard. */ const APP_CONFIG_RPC_ID = "cPZSdc"; +/** Read-only `CHECK_TOOL_AVAILABILITY` RPC identifier in the Flow workspace route guard. */ +const TOOL_AVAILABILITY_RPC_ID = "KV2T2d"; + /** Default Boq frontend data prefix when `WIZ_global_data.eptZe` is absent. */ const DEFAULT_DATA_PREFIX = "/_/AiSandboxAngularFrontend/"; @@ -44,28 +57,9 @@ const NON_WORKSPACE_SEGMENT_PREFIXES = [ const SIGN_IN_SELECTOR = 'flow-landing-page, a[aria-label="Sign in" i], button[aria-label="Sign in" i], button[aria-label="Create with Google Flow" i], a[href*="accounts.google.com/ServiceLogin" i], a[href*="accounts.google.com/v3/signin" i], a[href*="accounts.google.com/InteractiveLogin" i]'; -/** Returns `true` when `path` equals `prefix` or begins with `prefix` plus `/`. */ -function hasSegmentPrefix(path: string, prefix: string): boolean { - return path === prefix || path.startsWith(`${prefix}/`); -} - -/** Normalizes a URL pathname to lowercase without trailing slashes, preserving `/`. */ -function normalizePathname(raw: string): string { - const lower = (raw || "/").trim().toLowerCase(); - const withSlash = lower.startsWith("/") ? lower : `/${lower}`; - const trimmed = withSlash.replace(/\/+$/, ""); - return trimmed || "/"; -} - /** Returns `true` when `pathname` matches any of the 17 non-workspace Flow routes. */ -function isNonWorkspaceFlowPath(pathname: string): boolean { - const clean = normalizePathname(pathname); - const rel = - clean === "/fx" - ? "/" - : clean.startsWith("/fx/") - ? clean.slice(3) - : clean; +export function isNonWorkspaceFlowPath(pathname: string): boolean { + const rel = stripFlowRoutePrefix(pathname); if (rel === "/flow") { return true; } @@ -75,14 +69,17 @@ function isNonWorkspaceFlowPath(pathname: string): boolean { } /** Returns `true` when `hostname` and `pathname` target an active Flow workspace route. */ -function isWorkspaceLocation(hostname: string, pathname: string): boolean { +export function isWorkspaceLocation( + hostname: string, + pathname: string, +): boolean { const host = (hostname || "").toLowerCase(); - const clean = normalizePathname(pathname); + const clean = normalizeFlowPathname(pathname); const onLabsHost = host === "labs.google" || host.endsWith(".labs.google"); if (host !== "flow.google.com" && !onLabsHost) { return false; } - if (onLabsHost && !hasSegmentPrefix(clean, "/fx/tools/flow")) { + if (onLabsHost && !prefixHasFxToolsFlow(flowRoutePrefix(clean))) { return false; } return !isNonWorkspaceFlowPath(clean); @@ -129,9 +126,28 @@ function resolveDataPrefix(raw: string | undefined): string { return leading.endsWith("/") ? leading : `${leading}/`; } -/** Inspects one `batchexecute` response body for `FLOW_APP_CONFIG` or token expiration. */ -function parseProbeEnvelope(text: string, status: number): AuthCheckResult { - let verifiedConfig = false; +/** Returns `true` when a JSPB boolean field value explicitly encodes `false` or `0`. */ +function isJspbDisabledFlag(val: unknown): boolean { + return val === false || val === 0; +} + +/** Parses an integer enum code from a JSPB field value, or `0` when absent. */ +function readJspbEnumCode(val: unknown): number { + if (typeof val === "number" && Number.isInteger(val)) { + return val; + } + if (typeof val === "string" && /^\d+$/.test(val.trim())) { + return Number(val.trim()); + } + return 0; +} + +/** Inspects one `batchexecute` response body for `cPZSdc`, `KV2T2d`, or token expiration. */ +export function parseProbeEnvelope( + text: string, + status: number, +): AuthCheckResult { + let verifiedProbe = false; for (const rawLine of text.split(/\r?\n/)) { const line = rawLine.replace(/^\)\]\}'\s*/, "").trim(); if (!line.startsWith("[")) { @@ -153,7 +169,10 @@ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { if (entry[0] === "xsrf") { return authResult(false, false, true, status, "xsrf_expired"); } - if (entry[0] !== "wrb.fr" || entry[1] !== APP_CONFIG_RPC_ID) { + if ( + entry[0] !== "wrb.fr" || + (entry[1] !== APP_CONFIG_RPC_ID && entry[1] !== TOOL_AVAILABILITY_RPC_ID) + ) { continue; } const rpcErr = entry[5]; @@ -172,26 +191,41 @@ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { if (typeof entry[2] !== "string") { continue; } - let config: unknown; + let payload: unknown; try { - config = JSON.parse(entry[2]); + payload = JSON.parse(entry[2]); } catch { continue; } - if (Array.isArray(config)) { - if (config[30] === false) { + if (!isJspbMessage(payload)) { + continue; + } + if (entry[1] === APP_CONFIG_RPC_ID) { + if (isJspbDisabledFlag(jspbField(payload, 31))) { return authResult(false, true, false, status, "unsupported_country"); } - if (config[31] === false) { + if (isJspbDisabledFlag(jspbField(payload, 32))) { return authResult(false, true, false, status, "age_restricted"); } - verifiedConfig = true; - } else if (config !== null && typeof config === "object") { - verifiedConfig = true; + verifiedProbe = true; + } else { + const availability = readJspbEnumCode(jspbField(payload, 1)); + if (availability === 7) { + return authResult(false, true, false, status, "age_restricted"); + } + if ( + availability === 4 || + availability === 5 || + availability === 6 || + availability === 8 + ) { + return authResult(false, true, false, status, "unavailable"); + } + verifiedProbe = true; } } } - if (!verifiedConfig) { + if (!verifiedProbe) { return authResult(false, false, false, status, "missing_rpc_payload"); } if (!isWorkspaceLocation(location.hostname, location.pathname)) { @@ -228,8 +262,11 @@ export async function checkAuth(): Promise { return authResult(false, true, false, 0, "missing_wiz_token"); } + const checkToolAvailability = wiz.cPpIQe !== true; const params = new URLSearchParams({ - rpcids: APP_CONFIG_RPC_ID, + rpcids: checkToolAvailability + ? `${APP_CONFIG_RPC_ID},${TOOL_AVAILABILITY_RPC_ID}` + : APP_CONFIG_RPC_ID, "source-path": location.pathname || "/", hl: "en", rt: "c", @@ -240,10 +277,27 @@ export async function checkAuth(): Promise { if (typeof wiz.FdrFJe === "string" && wiz.FdrFJe.trim()) { params.set("f.sid", wiz.FdrFJe.trim()); } + const routeParams = flowQueryParams(location.search); + const wizUser = + typeof wiz.QrtxK === "string" && wiz.QrtxK.trim() && wiz.QrtxK.trim() !== "0" + ? wiz.QrtxK.trim() + : ""; + const authuser = + routeParams.authuser || pathAuthuser(location.pathname) || wizUser; + if (authuser) { + params.set("authuser", authuser); + } + if (routeParams.pageId) { + params.set("pageId", routeParams.pageId); + } - const reqPayload = JSON.stringify([ - [[APP_CONFIG_RPC_ID, "[]", null, "generic"]], - ]); + const rpcCalls: Array<[string, string, null, string]> = checkToolAvailability + ? [ + [APP_CONFIG_RPC_ID, "[]", null, "1"], + [TOOL_AVAILABILITY_RPC_ID, "[22]", null, "2"], + ] + : [[APP_CONFIG_RPC_ID, "[]", null, "generic"]]; + const reqPayload = JSON.stringify([rpcCalls]); const body = `f.req=${encodeURIComponent(reqPayload)}&at=${encodeURIComponent(xsrfToken)}`; const prefix = resolveDataPrefix(wiz.eptZe); diff --git a/ts/dom.ts b/ts/dom.ts index c2e9607..9110f8d 100644 --- a/ts/dom.ts +++ b/ts/dom.ts @@ -471,7 +471,7 @@ export function fifeEnv(): FifeEnv { (locHost.endsWith(".google.com") || locHost.endsWith(".google") ? locHost : "flow.google.com"); - const pathUserMatch = /^\/u\/(\d+)(?:\/|$)/.exec(location.pathname || ""); + const pathUserMatch = /(?:^|\/)u\/(\d+)(?:\/|$)/i.exec(location.pathname || ""); const searchUser = new URLSearchParams(location.search).get("authuser"); const authuser = pathUserMatch && pathUserMatch[1] !== "0" diff --git a/ts/resolve_video_url.ts b/ts/resolve_video_url.ts index 403b2bc..51237b6 100644 --- a/ts/resolve_video_url.ts +++ b/ts/resolve_video_url.ts @@ -35,12 +35,12 @@ function isSparseMap(val: unknown): val is Record { } /** Returns true when `val` is a JSPB message array or sparse field map. */ -function isJspbMessage(val: unknown): boolean { +export function isJspbMessage(val: unknown): boolean { return Array.isArray(val) || isSparseMap(val); } /** Reads 1-based protobuf `fieldNumber` from a dense JSPB array or its trailing sparse map. */ -function jspbField(msg: unknown, fieldNumber: number): unknown { +export function jspbField(msg: unknown, fieldNumber: number): unknown { if (fieldNumber < 1) return undefined; if (isSparseMap(msg)) { return msg[String(fieldNumber)]; diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..193bcae 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -10,6 +10,8 @@ export type NgLView = unknown[]; export interface WizGlobalData { /** True when the server rendered an authenticated Google session. */ awbSEf?: boolean; + /** True when the session belongs to an enterprise tenant that skips consumer tool checks. */ + cPpIQe?: boolean; /** Signed request token for batchexecute calls. */ SNlM0e?: string; /** Session identifier for batchexecute calls. */ @@ -18,6 +20,8 @@ export interface WizGlobalData { cfb2h?: string; /** Frontend data path prefix for batchexecute calls. */ eptZe?: string; + /** Active Google Account index in multi-account sessions. */ + QrtxK?: string; /** Encoded FIFE host configuration string. */ TSDtV?: string; }