From f3d587bf3aa95d662135891e05c270a8239d5bfc 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 09:25:04 +0000 Subject: [PATCH 1/3] fix(flow): verify workspace routes and angular query state - Strip Flow host, account, and org prefixes in route allowlists. - Detect /about, /flow, and /flow/about across all route prefixes. - Read FLOW_APP_CONFIG and CHECK_TOOL_AVAILABILITY from QueryCache. - Send authuser and pageId on batched cPZSdc and KV2T2d fallbacks. - Reject JSPB 0, false, sparse 31/32 flags, and KV2T2d codes 4-8. - Require Google cookies, Flow cookies, and History URL on login. - Keep LoginChrome open on status polls and keep active Flow URLs. --- src/auth.rs | 189 ++++++++----------- src/chrome.rs | 69 +++++-- src/engine.rs | 13 +- src/project.rs | 47 +++-- src/project_route.rs | 149 ++++++++++++--- ts/angular.ts | 424 ++++++++++++++++++++++++++++++++----------- ts/check_auth.ts | 375 ++++++++++++++++++++++++++++++-------- ts/types.ts | 46 +++++ 8 files changed, 959 insertions(+), 353 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 596c885..7121992 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -19,33 +19,11 @@ use crate::config::{ }; use crate::cookies::{has_google_auth_cookies, read_cookies_file}; use crate::engine::{ChromeEngine, ENGINE_NAME}; +use crate::project_route::{is_flow_origin_host, is_workspace_flow_route, split_flow_path}; /// Maximum number of `/about` passive SSO redirect attempts during session promotion. const MAX_ABOUT_SSO_RETRIES: usize = 2; -/// Exact or segment-prefix non-workspace routes from the live Flow route table. -const NON_WORKSPACE_SEGMENT_PREFIXES: [&str; 19] = [ - "/unsupported-country", - "/unsupported-browser", - "/unavailable", - "/age-restricted", - "/privacy", - "/credits-terms", - "/about", - "/flow/about", - "/academy", - "/shared/tool", - "/shared", - "/flow/shared/tool", - "/flow/shared", - "/tools/flow/shared/tool", - "/tools/flow/shared", - "/404", - "/login", - "/tools/flow/about", - "/tools/flow/login", -]; - /// Parameters for `flow_login`. #[derive(Debug, Clone, Deserialize, JsonSchema)] pub(crate) struct LoginParams { @@ -69,76 +47,35 @@ fn has_segment_prefix(path: &str, prefix: &str) -> bool { && 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); - if rel == "/flow" { - return true; - } - NON_WORKSPACE_SEGMENT_PREFIXES - .iter() - .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()) }) } -/// Returns `true` when `raw` points to a Google Flow workspace host and route. +/// Returns `true` when `raw` points to a Google Flow workspace host and allowlisted route. pub(crate) fn is_signed_in_flow_url(raw: &str) -> bool { let Ok(parsed) = Url::parse(raw) else { return false; }; - if parsed.scheme() != "https" && parsed.scheme() != "http" { + if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { return false; } - let Some(host) = parsed.host_str().map(|h| h.to_ascii_lowercase()) else { - return false; - }; + let host = parsed.host_str().unwrap_or_default().to_ascii_lowercase(); let on_labs = host == "labs.google" || host.ends_with(".labs.google"); - if host != "flow.google.com" && !on_labs { - return false; - } - let clean_path = normalize_flow_path(parsed.path()); - if on_labs && !has_segment_prefix(&clean_path, "/fx/tools/flow") { + let stripped = split_flow_path(parsed.path()); + if on_labs && !stripped.has_labs_flow_prefix { return false; } - !is_non_workspace_flow_path(&clean_path) + is_workspace_flow_route(&stripped.route) } /// Evaluates `checkAuth` once in the active page, retrying brief context resets during navigation. async fn eval_check_auth_once(engine: &ChromeEngine) -> Option { + let _ = engine + .bind_angular_views("aisandbox-root, app-root, router-outlet") + .await; for _ in 0..3 { match engine.call_flow_async("checkAuth", json!([])).await { Ok(v) => return Some(v), @@ -225,21 +162,16 @@ fn signed_in_login_result(mode: &str, count: usize, url: String) -> Value { }) } -/// Returns `true` when `url` points to a Google Flow `/about` landing route. +/// Returns `true` when `url` points to a Google Flow `/about` landing route under any supported prefix. 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 stripped = split_flow_path(parsed.path()); + let rel = stripped.route.as_str(); rel == "/flow" || has_segment_prefix(rel, "/about") || has_segment_prefix(rel, "/flow/about") @@ -311,15 +243,28 @@ 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) { + break; + } + 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 = check_page_auth(engine, true).await; + if auth.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 matches!( + auth.get("reason").and_then(Value::as_str), + Some("unsupported_country" | "age_restricted" | "unavailable") + ) { + break; + } + } } tokio::time::sleep(Duration::from_millis(500)).await; } @@ -339,7 +284,7 @@ async fn login_with_chrome( 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,18 +292,14 @@ 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 { + let target_url = st.flow_url.as_deref().unwrap_or(FLOW_URL); + if let Some(res) = finalize_promoted_login(engine, target_url).await? { return Ok(res); } - if st.exited { - anyhow::bail!("Sign-in window was closed before Google Sign-In completed."); - } + engine.launch_interactive_login(FLOW_SSO_URL, false).await?; } } - if !engine.has_login_chrome().await { - engine.launch_interactive_login(FLOW_SSO_URL, false).await?; - } } else { if has_persisted_session() || engine.has_page().await { engine.ensure_page().await?; @@ -374,7 +315,7 @@ async fn login_with_chrome( if !wait_for_login { let st = engine.poll_login_chrome().await?; let url = st - .and_then(|s| s.rejected_url) + .and_then(|s| s.rejected_url.or(s.flow_url)) .unwrap_or_else(|| FLOW_SSO_URL.to_string()); return Ok(json!({ "ok": true, @@ -391,6 +332,9 @@ async fn login_with_chrome( let clamped_secs = timeout_secs.clamp(15, 3600); let deadline = Instant::now() + Duration::from_secs(clamped_secs); + let mut ready_polls = 0usize; + let mut ready_url: Option = None; + let mut last_flow_url: Option = None; loop { let Some(st) = engine.poll_login_chrome().await? else { @@ -405,23 +349,43 @@ 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 let Some(observed) = st.flow_url.as_ref() { + last_flow_url = Some(observed.clone()); + } + + if st.has_google_auth_cookies { + if ready_url.as_deref() == st.flow_url.as_deref() { + ready_polls += 1; + } else { + ready_url = st.flow_url.clone(); + ready_polls = 1; } - if let Some(res) = finalize_promoted_login(engine, FLOW_URL).await? { + } else { + ready_polls = 0; + ready_url = None; + } + + if st.exited || ready_polls >= 2 { + let target_url = st + .flow_url + .as_deref() + .or(last_flow_url.as_deref()) + .unwrap_or(FLOW_URL); + if let Some(res) = finalize_promoted_login(engine, target_url).await? { return Ok(res); } if st.exited { anyhow::bail!("Sign-in window was closed before Google Sign-In completed."); } + engine.launch_interactive_login(FLOW_SSO_URL, false).await?; anyhow::bail!( "Google Sign-In wrote authentication cookies, but workspace verification did not succeed. Run flow_login again." ); } if Instant::now() >= deadline { - if let Ok(Some(res)) = finalize_promoted_login(engine, FLOW_URL).await { + let target_url = last_flow_url.as_deref().unwrap_or(FLOW_URL); + if let Ok(Some(res)) = finalize_promoted_login(engine, target_url).await { return Ok(res); } engine.shutdown().await; @@ -488,10 +452,15 @@ 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 { promotion_attempted = true; - let _ = finalize_promoted_login(engine, FLOW_URL).await; + let target_url = st.flow_url.as_deref().unwrap_or(FLOW_URL); + let _ = finalize_promoted_login(engine, target_url).await; } else { + let url = st + .rejected_url + .or(st.flow_url) + .unwrap_or_else(|| FLOW_SSO_URL.to_string()); return Ok(json!({ "ok": true, "action": "status", @@ -501,7 +470,7 @@ pub(crate) async fn handle_login(engine: &ChromeEngine, req: LoginParams) -> Res "cdpEndpoint": Value::Null, "cookiesSaved": cookies_path().is_file(), "profileDir": chrome_profile_dir().to_string_lossy(), - "url": st.rejected_url.unwrap_or_else(|| FLOW_SSO_URL.to_string()), + "url": url, "signedIn": false, })); } diff --git a/src/chrome.rs b/src/chrome.rs index 7164984..f5dee73 100644 --- a/src/chrome.rs +++ b/src/chrome.rs @@ -10,7 +10,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crate::cdp::{CdpConnection, fetch_json_version}; use crate::config::{chrome_profile_dir, cli_chrome_path, configured_cdp_port}; -use crate::cookies::is_google_auth_cookie_pair; +use crate::cookies::{cookie_domain_matches, is_google_auth_cookie_pair}; use crate::instance::{acquire_instance_lock, stop_orphan_chrome}; use crate::platform::{create_private_dir_all, focus_process, interrupt_process}; @@ -53,7 +53,9 @@ 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. + /// Latest signed-in Google Flow workspace URL observed in profile history. + pub(crate) flow_url: Option, + /// True when Google auth cookies, Flow-origin cookies, and a workspace history URL exist. pub(crate) has_google_auth_cookies: bool, } @@ -328,48 +330,74 @@ fn copy_sqlite_files_to_scratch( Some(dst) } -/// Inspects a scratch copy of Chrome's `History` SQLite database for Google Accounts rejection URLs. +/// Inspects a scratch copy of Chrome's `History` SQLite database for rejection and workspace URLs. fn probe_history_db(scratch_history: &Path, min_webkit_us: i64, probe: &mut LoginProfileProbe) { let Ok(conn) = rusqlite::Connection::open(scratch_history) else { return; }; 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; }; let Ok(rows) = stmt.query_map([min_webkit_us], |row| row.get::<_, String>(0)) else { return; }; + let mut flow_checked = false; for url in rows.flatten() { if url.contains("accounts.google.com/v3/signin/rejected") { - probe.rejected_url = Some(url); + if !flow_checked { + probe.rejected_url = Some(url); + probe.flow_url = None; + } return; } + if !flow_checked && crate::auth::is_flow_host_url(&url) { + if url.to_ascii_lowercase().contains("/fx/api/auth/") { + continue; + } + flow_checked = true; + if crate::auth::is_signed_in_flow_url(&url) { + probe.flow_url = Some(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 { +/// Inspects a scratch copy of Chrome's `Cookies` database for `.google.com` and Flow-origin cookies. +fn probe_cookies_db(scratch_cookies: &Path, min_webkit_us: i64) -> (bool, bool) { let Ok(conn) = rusqlite::Connection::open(scratch_cookies) else { - return false; + return (false, false); }; let Ok(mut stmt) = conn.prepare("SELECT host_key, name FROM cookies WHERE last_update_utc >= ?1") else { - return false; + return (false, false); }; let Ok(rows) = stmt.query_map([min_webkit_us], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) }) else { - return false; + return (false, false); }; - for pair in rows.flatten() { - if is_google_auth_cookie_pair(&pair.0, &pair.1) { - return true; + let mut has_google_cookie = false; + let mut has_flow_cookie = false; + for (host, name) in rows.flatten() { + let clean_host = host.trim().trim_start_matches('.'); + if clean_host.eq_ignore_ascii_case("google.com") && is_google_auth_cookie_pair(&host, &name) + { + has_google_cookie = true; + } + if !name.trim().is_empty() + && (cookie_domain_matches(&host, "flow.google.com") + || cookie_domain_matches(&host, "labs.google")) + { + has_flow_cookie = true; + } + if has_google_cookie && has_flow_cookie { + break; } } - false + (has_google_cookie, has_flow_cookie) } /// Inspects Chrome `History` and `Cookies` files for entries updated since `started_at`. @@ -403,15 +431,22 @@ pub(crate) async fn inspect_login_profile( dir.join("Default").join("Cookies"), dir.join("Default").join("Network").join("Cookies"), ]; + let mut has_google_cookie = false; + let mut has_flow_cookie = false; 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.has_google_auth_cookies = true; - break; + let (google_hit, flow_hit) = probe_cookies_db(&scratch_cookies, min_webkit_us); + has_google_cookie |= google_hit; + has_flow_cookie |= flow_hit; + if has_google_cookie && has_flow_cookie { + break; + } } } + probe.has_google_auth_cookies = + has_google_cookie && has_flow_cookie && probe.flow_url.is_some(); probe }) diff --git a/src/engine.rs b/src/engine.rs index 110a532..d30285b 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -138,7 +138,9 @@ 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. + /// Latest signed-in Google Flow workspace URL observed in profile history. + pub(crate) flow_url: Option, + /// True when Google cookies, Flow cookies, and a workspace history entry exist. pub(crate) has_google_auth_cookies: bool, } @@ -244,6 +246,7 @@ impl ChromeEngine { Ok(Some(LoginPollStatus { exited, rejected_url: probe.rejected_url, + flow_url: probe.flow_url, has_google_auth_cookies: probe.has_google_auth_cookies, })) } @@ -869,6 +872,14 @@ async fn bind_browser_instances( ) -> Result> { let group = format!("flow-bind-{}", uuid::Uuid::new_v4()); let result = async { + let installed = eval_runtime(cdp, "Boolean(window.__flowMcp)", false, Duration::from_secs(5)) + .await + .ok() + .and_then(|v| v.as_bool()) + .unwrap_or(false); + if !installed { + eval_runtime(cdp, FLOW_RUNTIME_JS, false, Duration::from_secs(30)).await?; + } let prototype = cdp .call( "Runtime.evaluate", diff --git a/src/project.rs b/src/project.rs index e11643e..a0e57b9 100644 --- a/src/project.rs +++ b/src/project.rs @@ -17,7 +17,7 @@ use crate::auth::{check_page_auth, check_page_signed_in, is_flow_host_url, redir use crate::config::{FLOW_URL, has_persisted_session}; use crate::engine::{ChromeEngine, ENGINE_NAME}; pub(crate) use crate::project_route::{ - project_id_from_url, project_subroute_url, project_workspace_url, + is_project_subroute_url, project_id_from_url, project_subroute_url, project_workspace_url, }; use crate::project_store::{bind_current_store, prepare_project_store_status}; @@ -88,30 +88,8 @@ pub(crate) struct FlowStatus { /// Navigates back to `/project/` when Chrome is on a non-grid project subroute. pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Result<()> { - let is_subroute = |url: &str| { - let path = url.split(['?', '#']).next().unwrap_or_default(); - let Some((_, project)) = path.split_once("/project/") else { - return false; - }; - let mut segs = project.trim_end_matches('/').split('/'); - if segs.next().is_none_or(str::is_empty) { - return false; - } - match (segs.next(), segs.next(), segs.next()) { - ( - Some( - "character" | "scene" | "edit" | "chat" | "tool" | "tools" | "create-tool" - | "trash", - ), - _, - _, - ) => true, - (Some("collection"), Some(cid), Some("character")) => !cid.is_empty(), - _ => false, - } - }; let current = engine.current_url().await?; - if !is_subroute(¤t) { + if !is_project_subroute_url(¤t) { return Ok(()); } let project_id = project_id_from_url(¤t) @@ -119,7 +97,7 @@ pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Resu let workspace = project_workspace_url(¤t, &project_id); let returned = |url: &str| { is_flow_host_url(url) - && !is_subroute(url) + && !is_project_subroute_url(url) && project_id_from_url(url).as_deref() == Some(project_id.as_str()) && project_workspace_url(url, &project_id) == workspace }; @@ -172,6 +150,25 @@ 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 engine.has_login_chrome().await + && let Ok(Some(st)) = engine.poll_login_chrome().await + && !st.exited + { + return FlowStatus { + signed_in: false, + in_project: false, + project: None, + project_id: None, + url: st.rejected_url.or(st.flow_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..b9962a9 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -7,11 +7,19 @@ use url::Url; use crate::config::FLOW_URL; -/// Extracts the `/project/` segment from a Flow project URL. +/// Extracts the `/project/` segment from a Flow workspace URL or path. pub(crate) fn project_id_from_url(url: &str) -> Option { + if url.contains("://") && !crate::auth::is_signed_in_flow_url(url) { + return None; + } let path = url.split(['?', '#']).next()?; - let (_, project) = path.split_once("/project/")?; - let id = project.split('/').next()?.trim(); + let stripped = split_flow_path(path); + if !stripped.route.starts_with("/project/") || !is_workspace_flow_route(&stripped.route) { + return None; + } + let prefix_count = stripped.prefix.split('/').filter(|s| !s.is_empty()).count(); + let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + let id = segs.get(prefix_count + 1)?.trim(); (!id.is_empty()).then(|| id.to_string()) } @@ -25,45 +33,138 @@ 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(); - } +/// Parsed components of a Google Flow URL path after stripping active prefixes. +pub(crate) struct StrippedFlowPath { + /// Active route prefix starting with `/` when present, preserving original case. + pub(crate) prefix: String, + /// Normalized lowercase route path starting with `/` without trailing slashes. + pub(crate) route: String, + /// True when `/fx/tools/flow` appears in the stripped prefix segments. + pub(crate) has_labs_flow_prefix: bool, +} + +/// Returns `true` when `seg` is a reserved Flow top-level segment rather than an organization slug. +fn is_reserved_flow_segment(seg: &str) -> bool { + matches!( + seg.to_ascii_lowercase().as_str(), + "project" + | "projects" + | "search" + | "changelogs" + | "about" + | "shared" + | "flow" + | "tools" + | "fx" + | "u" + | "unsupported-country" + | "unsupported-browser" + | "unavailable" + | "age-restricted" + | "privacy" + | "credits-terms" + | "academy" + | "404" + | "login" + | "debug" + ) +} + +/// Strips `/fx/tools/flow`, `/fx`, `/u/`, and `//global` prefixes from `path`. +pub(crate) fn split_flow_path(path: &str) -> StrippedFlowPath { let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); let mut prefix = Vec::new(); + let mut has_labs_flow_prefix = false; let mut i = 0; while i < segs.len() { - if segs[i..].starts_with(&["fx", "tools", "flow"]) { - prefix.extend_from_slice(&["fx", "tools", "flow"]); - i += 3; - } else if i + 1 < segs.len() - && segs[i] == "u" - && !segs[i + 1].is_empty() - && segs[i + 1].bytes().all(|b| b.is_ascii_digit()) + if segs.len() >= i + 3 + && 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(&["u", segs[i + 1]]); - i += 2; + has_labs_flow_prefix = true; + prefix.extend_from_slice(&segs[i..i + 3]); + i += 3; + } else if segs[i].eq_ignore_ascii_case("fx") { + prefix.push(segs[i]); + i += 1; } else if i + 1 < segs.len() - && segs[i + 1] == "global" - && !matches!( - segs[i], - "project" | "projects" | "about" | "shared" | "flow" | "tools" | "fx" | "u" - ) + && ((segs[i].eq_ignore_ascii_case("u") + && !segs[i + 1].is_empty() + && segs[i + 1].bytes().all(|b| b.is_ascii_digit())) + || (segs[i + 1].eq_ignore_ascii_case("global") + && !is_reserved_flow_segment(segs[i]))) { - prefix.extend_from_slice(&[segs[i], "global"]); + prefix.extend_from_slice(&segs[i..i + 2]); i += 2; } else { break; } } - if prefix.is_empty() { + let prefix_str = if prefix.is_empty() { String::new() } else { format!("/{}", prefix.join("/")) + }; + let route = if i >= segs.len() { + "/".to_string() + } else { + format!("/{}", segs[i..].join("/")).to_ascii_lowercase() + }; + StrippedFlowPath { + prefix: prefix_str, + route, + has_labs_flow_prefix, } } +/// Returns `true` when lowercase segments after `/project/` match a recognized Flow project subroute. +fn is_project_subroute_segments(segs: &[&str]) -> bool { + match segs { + ["character" | "tools" | "create-tool" | "trash" | "chat"] => true, + [ + "character" | "scene" | "edit" | "tool" | "collection" | "chat", + id, + ] => !id.is_empty(), + ["collection", id, "character"] | ["trash", "collection", id] => !id.is_empty(), + _ => false, + } +} + +/// Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. +pub(crate) fn is_workspace_flow_route(route: &str) -> bool { + if matches!(route, "/" | "/projects" | "/search" | "/changelogs") { + return true; + } + let Some(rest) = route.strip_prefix("/project/") else { + return false; + }; + let segs: Vec<&str> = rest.split('/').collect(); + let Some((&project_id, sub)) = segs.split_first() else { + return false; + }; + !project_id.is_empty() && (sub.is_empty() || is_project_subroute_segments(sub)) +} + +/// Returns `true` when `url` points to a non-grid subroute inside `/project/`. +pub(crate) fn is_project_subroute_url(url: &str) -> bool { + let path = url.split(['?', '#']).next().unwrap_or_default(); + let stripped = split_flow_path(path); + let Some(rest) = stripped.route.strip_prefix("/project/") else { + return false; + }; + let segs: Vec<&str> = rest.split('/').collect(); + let Some((&project_id, sub)) = segs.split_first() else { + return false; + }; + !project_id.is_empty() && is_project_subroute_segments(sub) +} + +/// Extracts the active route prefix from a Flow URL path. +fn flow_route_prefix(path: &str) -> String { + split_flow_path(path).prefix +} + /// Builds a Google Flow `/project/` or subroute URL with active prefixes, `hl=en`, and `authuser`. pub(crate) fn project_subroute_url( reference_url: &str, diff --git a/ts/angular.ts b/ts/angular.ts index 8b0bbf0..f1c378c 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -8,12 +8,21 @@ import { delay, elText, fifeBase, + hoverProbe, normalizeFlowMediaUrl, readMediaUrl, } from "./dom"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; import { runtimeState } from "./state"; -import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; +import type { + AngularQueryCache, + AngularQueryClient, + AngularQueryEntry, + AngularRouter, + FlowStoreHandle, + FlowTile, + NgLView, +} from "./types"; /** Object with optional Angular Ivy `__ngContext__` or internal `lView` links. */ export interface NgContextCarrier { @@ -33,6 +42,20 @@ export function readOwn(obj: unknown, key: string): unknown { } } +/** Returns `true` when `val` is a non-null, non-array, non-`Map`, non-DOM object. */ +function isPlainRecord(val: unknown): val is Record { + return Boolean( + val && + typeof val === "object" && + val !== window && + val !== document && + val !== window.navigation && + !(val instanceof Node) && + !Array.isArray(val) && + !(val instanceof Map), + ); +} + /** Returns `lv` if `lv` is a live Angular LView whose host node remains connected. */ export function isLiveLView(lv: unknown): lv is NgLView { return Array.isArray(lv) && (!(lv[0] instanceof Node) || lv[0].isConnected); @@ -169,6 +192,106 @@ export function withLViewMapCapture( /** Cached query-parameter key per Angular Router instance. */ const routerQueryParamKeys = new WeakMap(); +/** Parsed prefix and normalized route details of a Flow pathname. */ +export interface StrippedFlowPath { + /** Active prefix starting with `/` when present, preserving original case. */ + prefix: string; + /** Normalized lowercase route starting with `/` without trailing slashes. */ + route: string; + /** True when `/fx/tools/flow` appears among the stripped prefixes. */ + hasLabsFlowPrefix: boolean; + /** Account index extracted from `/u/` when present. */ + pathAuthuser: string | null; +} + +/** Reserved Flow top-level route names that cannot act as `` before `/global`. */ +const RESERVED_FLOW_SEGMENTS = new Set([ + "project", "projects", "search", "changelogs", "about", "shared", "flow", + "tools", "fx", "u", "unsupported-country", "unsupported-browser", "unavailable", + "age-restricted", "privacy", "credits-terms", "academy", "404", "login", "debug", +]); + +/** Strips `/fx/tools/flow`, `/fx`, `/u/`, and `//global` prefixes from `pathname`. */ +export function splitFlowPath(pathname: string = location.pathname): StrippedFlowPath { + const cleanPath = (pathname || "/").split(/[?#]/)[0] || "/"; + const segs = cleanPath.split("/").filter(Boolean); + const prefixSegs: string[] = []; + let hasLabsFlowPrefix = false; + let pathAuthuser: string | null = null; + let i = 0; + while (i < segs.length) { + const low0 = segs[i].toLowerCase(); + const low1 = (segs[i + 1] || "").toLowerCase(); + const low2 = (segs[i + 2] || "").toLowerCase(); + if (low0 === "fx" && low1 === "tools" && low2 === "flow") { + hasLabsFlowPrefix = true; + prefixSegs.push(segs[i], segs[i + 1], segs[i + 2]); + i += 3; + } else if (low0 === "fx") { + prefixSegs.push(segs[i]); + i += 1; + } else if (low0 === "u" && /^\d+$/.test(segs[i + 1] || "")) { + pathAuthuser = segs[i + 1]; + prefixSegs.push(segs[i], segs[i + 1]); + i += 2; + } else if (low1 === "global" && !RESERVED_FLOW_SEGMENTS.has(low0)) { + prefixSegs.push(segs[i], segs[i + 1]); + i += 2; + } else { + break; + } + } + const prefix = prefixSegs.length > 0 ? `/${prefixSegs.join("/")}` : ""; + const route = + i >= segs.length ? "/" : `/${segs.slice(i).join("/").toLowerCase()}`; + return { prefix, route, hasLabsFlowPrefix, pathAuthuser }; +} + +/** Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. */ +export function isWorkspaceFlowRoute(route: string): boolean { + if (route === "/" || route === "/projects" || route === "/search" || route === "/changelogs") { + return true; + } + if (!route.startsWith("/project/")) return false; + const [projectId, ...sub] = route.slice("/project/".length).split("/"); + if (!projectId) return false; + if (sub.length === 0) return true; + if (sub.length === 1) { + return ["character", "tools", "create-tool", "trash", "chat"].includes(sub[0]); + } + if (sub.length === 2) { + return Boolean(sub[1]) && ["character", "scene", "edit", "tool", "collection", "chat"].includes(sub[0]); + } + if (sub.length === 3) { + return ( + (sub[0] === "collection" && Boolean(sub[1]) && sub[2] === "character") || + (sub[0] === "trash" && sub[1] === "collection" && Boolean(sub[2])) + ); + } + return false; +} + +/** Resolves the active `authuser` value from URL query, `/u/` prefix, or `WIZ_global_data`. */ +export function resolveFlowAuthuser( + search: string = location.search, + pathname: string = location.pathname, +): string | null { + const fromQuery = new URLSearchParams(search).get("authuser")?.trim(); + if (fromQuery) return fromQuery; + const { pathAuthuser } = splitFlowPath(pathname); + if (pathAuthuser) return pathAuthuser; + const fromWiz = window.WIZ_global_data?.QrtxK; + return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; +} + +/** Resolves the active `pageId` value from URL query or `WIZ_global_data.S06Grb`. */ +export function resolveFlowPageId(search: string = location.search): string | null { + const fromQuery = new URLSearchParams(search).get("pageId")?.trim(); + if (fromQuery) return fromQuery; + const fromWiz = window.WIZ_global_data?.S06Grb; + return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; +} + /** Builds the query parameters that Google Flow routes keep across transitions. */ function flowQueryParams(search: string = location.search): Record { const params: Record = { hl: "en" }; @@ -179,13 +302,11 @@ function flowQueryParams(search: string = location.search): Record`. */ function activeProjectPrefix(): string { const path = location.pathname || ""; - const projectIdx = path.indexOf("/project/"); - if (projectIdx >= 0) { - return path.slice(0, projectIdx).replace(/\/+$/, ""); - } + const { prefix } = splitFlowPath(path); + if (prefix) return prefix; const baseHref = document.head?.querySelector("base")?.getAttribute("href"); if (baseHref) { try { @@ -194,34 +315,10 @@ function activeProjectPrefix(): string { return basePath; } } catch { - // Fall through to segment check. + // Ignore malformed `` attributes. } } - const segs = path.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" - ) { - prefixSegs.push("fx", "tools", "flow"); - i += 3; - } else if (segs[i] === "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]) - ) { - prefixSegs.push(segs[i], "global"); - i += 2; - } else { - break; - } - } - return prefixSegs.length > 0 ? `/${prefixSegs.join("/")}` : ""; + return ""; } /** Discovers the query-parameter key on `NavigationExtras` via `UrlSerializer.parse` on `router`. */ @@ -231,32 +328,15 @@ function routerQueryParamsKey(router: AngularRouter): string { const candidateKeys = Array.from(new Set([...Object.keys(router), "urlSerializer"])); for (const key of candidateKeys) { const serializer = readOwn(router, key); - if ( - !serializer || - typeof serializer !== "object" || - serializer === window || - serializer === document || - serializer instanceof Node - ) { - continue; - } + if (!isPlainRecord(serializer)) continue; const parse = readOwn(serializer, "parse"); if (typeof parse !== "function") continue; try { - const tree = (parse as (url: string) => unknown).call( - serializer, - "/?__flow_qp=1", - ); - if (!tree || typeof tree !== "object") continue; - const treeKeys = Array.from(new Set([...Object.keys(tree), "queryParams"])); - for (const treeKey of treeKeys) { + const tree = (parse as (url: string) => unknown).call(serializer, "/?__flow_qp=1"); + if (!isPlainRecord(tree)) continue; + for (const treeKey of new Set([...Object.keys(tree), "queryParams"])) { const qp = readOwn(tree, treeKey); - if ( - qp && - typeof qp === "object" && - !Array.isArray(qp) && - readOwn(qp, "__flow_qp") === "1" - ) { + if (isPlainRecord(qp) && readOwn(qp, "__flow_qp") === "1") { routerQueryParamKeys.set(router, treeKey); return treeKey; } @@ -300,23 +380,12 @@ export function buildProjectUrl( return url.href; } -/** Searches visible shell nodes and captured LViews for the active Angular `Router` instance. */ -export function findRouter(): AngularRouter | null { - const isRouter = (cand: unknown): cand is AngularRouter => - Boolean( - cand && - typeof cand === "object" && - cand !== window && - cand !== document && - cand !== window.navigation && - !(cand instanceof Node) && - !Array.isArray(cand) && - !(cand instanceof Map) && - typeof (cand as Partial).navigate === "function" && - "location" in cand && - "options" in cand, - ); +/** Host selectors searched first for Angular Ivy `LView` trees and root injectors. */ +const ANGULAR_SHELL_SELECTOR = + "flow-project-shell, flow-project-page, flow-character-edit-page, flow-editor-dispatcher, flow-editor-page, flow-scene-builder, router-outlet, aisandbox-root, app-root, main, header"; +/** Searches visible shell nodes, injectors, and captured LViews for a service matching `match`. */ +function findInAngular(match: (cand: unknown) => cand is T): T | null { const ownMaps = (obj: object): Array> => { const maps: Array> = []; const named = readOwn(obj, "records"); @@ -334,25 +403,49 @@ export function findRouter(): AngularRouter | null { const seenObjs = new Set(); const seenInjectors = new Set(); - const inspectInjector = (injRoot: object): AngularRouter | null => { + const inspectInjector = (injRoot: object): T | null => { let inj: object | null = injRoot; - for (let d = 0; d < 6 && inj && typeof inj === "object"; d += 1) { + for (let d = 0; d < 10 && inj && typeof inj === "object"; d += 1) { if (seenInjectors.has(inj)) break; seenInjectors.add(inj); for (const records of ownMaps(inj)) { for (const rec of records.values()) { - if (isRouter(rec)) return rec; + if (match(rec)) return rec; const recVal = readOwn(rec, "value"); - if (isRouter(recVal)) return recVal; + if (match(recVal)) return recVal; + if (isPlainRecord(recVal) && !seenObjs.has(recVal)) { + seenObjs.add(recVal); + const rKeys = Object.keys(recVal); + for (let i = 0; i < rKeys.length && i < 16; i += 1) { + const nested = readOwn(recVal, rKeys[i]); + if (match(nested)) return nested; + } + } } } const parent = readOwn(inj, "parent"); - inj = parent && typeof parent === "object" ? parent : null; + if (parent && typeof parent === "object" && !(parent instanceof Node)) { + inj = parent; + continue; + } + let nextInj: object | null = null; + for (const key of Object.keys(inj)) { + const candParent = readOwn(inj, key); + if ( + isPlainRecord(candParent) && + !seenInjectors.has(candParent) && + ownMaps(candParent).length > 0 + ) { + nextInj = candParent; + break; + } + } + inj = nextInj; } return null; }; - const inspectLViewTree = (startLv: NgLView | null): AngularRouter | null => { + const inspectLViewTree = (startLv: NgLView | null): T | null => { if (!Array.isArray(startLv)) return null; const queue: Array<[NgLView, number]> = [[startLv, 0]]; while (queue.length > 0) { @@ -365,26 +458,19 @@ export function findRouter(): AngularRouter | null { if (!slot || typeof slot !== "object" || slot instanceof Node) { continue; } - if (isRouter(slot)) return slot; + if (match(slot)) return slot; if ("parent" in slot || ownMaps(slot).length > 0) { const fromInj = inspectInjector(slot); if (fromInj) return fromInj; } if (seenObjs.has(slot)) continue; seenObjs.add(slot); - if (!Array.isArray(slot) && !(slot instanceof Map)) { + if (isPlainRecord(slot)) { const keys = Object.keys(slot); for (let i = 0; i < keys.length && i < 30; i += 1) { const val = readOwn(slot, keys[i]); - if (isRouter(val)) return val; - if ( - val && - typeof val === "object" && - !(val instanceof Node) && - !Array.isArray(val) && - !(val instanceof Map) && - ("parent" in val || ownMaps(val).length > 0) - ) { + if (match(val)) return val; + if (isPlainRecord(val) && ("parent" in val || ownMaps(val).length > 0)) { const fromNested = inspectInjector(val); if (fromNested) return fromNested; } @@ -399,10 +485,7 @@ export function findRouter(): AngularRouter | null { return null; }; - const els = document.querySelectorAll( - "flow-project-shell, flow-project-page, flow-character-edit-page, flow-editor-dispatcher, flow-editor-page, flow-scene-builder, router-outlet, aisandbox-root, app-root, main", - ); - for (const el of els) { + for (const el of document.querySelectorAll(ANGULAR_SHELL_SELECTOR)) { const hit = inspectLViewTree(resolveLView(el)); if (hit) return hit; } @@ -412,9 +495,157 @@ export function findRouter(): AngularRouter | null { if (hit) return hit; } } + const all = document.querySelectorAll("*"); + const limit = Math.min(all.length, 200); + for (let i = 0; i < limit; i += 1) { + if ("__ngContext__" in all[i]) { + const hit = inspectLViewTree(resolveLView(all[i])); + if (hit) return hit; + } + } return null; } +/** Searches visible shell nodes and captured LViews for the active Angular `Router` instance. */ +export function findRouter(): AngularRouter | null { + return findInAngular( + (cand): cand is AngularRouter => + isPlainRecord(cand) && + typeof (cand as Partial).navigate === "function" && + "location" in cand && + "options" in cand, + ); +} + +/** Returns `true` when `cand` is a non-DOM object holding a `find` function. */ +function hasQueryFind(cand: unknown): cand is AngularQueryCache { + return isPlainRecord(cand) && typeof readOwn(cand, "find") === "function"; +} + +/** Returns `true` when `cand` matches Angular's standalone `QueryCache` shape. */ +function isAngularQueryCache(cand: unknown): cand is AngularQueryCache { + return ( + hasQueryFind(cand) && + (typeof readOwn(cand, "getAll") === "function" || + readOwn(cand, "queries") instanceof Map) + ); +} + +/** Searches Angular injectors and LViews for the live `QueryClient` or `QueryCache`. */ +export function findQueryCache(): AngularQueryCache | null { + const clientOrCache = findInAngular( + (cand): cand is AngularQueryClient | AngularQueryCache => { + if (isAngularQueryCache(cand)) return true; + if (!cand || typeof cand !== "object" || cand instanceof Node) return false; + return hasQueryFind(readOwn(cand, "queryCache")); + }, + ); + if (!clientOrCache) return null; + const nested = readOwn(clientOrCache, "queryCache"); + return hasQueryFind(nested) ? nested : (clientOrCache as AngularQueryCache); +} + +/** Resolves Angular's `QueryCache`, capturing `ngLViewMap` once if numeric contexts are unbound. */ +export async function ensureAngularQueryCache(): Promise { + const direct = findQueryCache(); + if (direct) return direct; + if (!(runtimeState.ngLViewMap instanceof Map)) { + const hasNumericContext = Array.from( + document.querySelectorAll(ANGULAR_SHELL_SELECTOR), + ).some((el) => typeof readOwn(el, "__ngContext__") === "number"); + if (hasNumericContext) { + await withLViewMapCapture(async () => { + const targets = Array.from( + document.querySelectorAll( + "[mattooltip], [cdkoverlayorigin], button[aria-label], button, a[href]", + ), + ); + if (targets.length > 0) { + await hoverProbe(targets.slice(0, 8), 20); + } + }); + } + } + return findQueryCache(); +} + +/** Returns `true` when any DOM host on the page carries an Angular Ivy `__ngContext__`. */ +export function hasAngularContext(): boolean { + if (runtimeState.ngLViewMap instanceof Map && runtimeState.ngLViewMap.size > 0) { + return true; + } + for (const el of document.querySelectorAll(ANGULAR_SHELL_SELECTOR)) { + if (readOwn(el, "__ngContext__") !== undefined) return true; + } + const all = document.querySelectorAll("*"); + const limit = Math.min(all.length, 200); + for (let i = 0; i < limit; i += 1) { + if ("__ngContext__" in all[i]) return true; + } + return false; +} + +/** Returns `true` when Angular's `Router` has an active navigation in flight. */ +export function isRouterNavigating(): boolean { + const router = findRouter(); + if (!router) return false; + for (const key of ["currentNavigation", "getCurrentNavigation"]) { + const fn = readOwn(router, key); + if (typeof fn === "function") { + try { + if (fn.call(router) != null) return true; + } catch { + // Ignore router accessor errors. + } + } + } + return readOwn(router, "navigating") === true; +} + +/** Reads a cached query entry matching `queryKey` from `cache`. */ +export function readQueryCacheEntry( + cache: AngularQueryCache | null, + queryKey: readonly unknown[], +): AngularQueryEntry | undefined { + if (!cache) return undefined; + if (typeof cache.find === "function") { + try { + const hit = cache.find({ queryKey, exact: true }); + if (hit) return hit; + } catch { + // Fall through to hash or list lookup. + } + } + const hash = JSON.stringify(queryKey); + if (typeof cache.get === "function") { + try { + const hit = cache.get(hash); + if (hit) return hit; + } catch { + // Fall through to map or list lookup. + } + } + if (cache.queries instanceof Map) { + const hit = cache.queries.get(hash); + if (hit) return hit; + } + if (typeof cache.getAll === "function") { + try { + for (const entry of cache.getAll()) { + if ( + entry?.queryHash === hash || + JSON.stringify(entry?.queryKey) === hash + ) { + return entry; + } + } + } catch { + // Ignore concurrent cache iteration errors. + } + } + return undefined; +} + /** Maximum time to confirm scene creation and the initial clip load. */ const SCENE_CREATE_TIMEOUT_MS = 30_000; @@ -582,16 +813,7 @@ function scanLViewTooltip(lv: NgLView, hostNode: Element): string { } for (const key of ["message", "Sf", "CA"]) { for (const cand of lv) { - if ( - !cand || - typeof cand !== "object" || - cand instanceof Node || - cand instanceof Error || - Array.isArray(cand) || - cand instanceof Map - ) { - continue; - } + if (!isPlainRecord(cand) || cand instanceof Error) continue; const text = readTooltipSlotValue(cand, key); if (text) return text; } diff --git a/ts/check_auth.ts b/ts/check_auth.ts index 7a94a33..e21f652 100644 --- a/ts/check_auth.ts +++ b/ts/check_auth.ts @@ -1,91 +1,70 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Verify Google Flow workspace access with route guards, Wiz tokens, and a read-only probe. +// Verify Google Flow workspace access with route allowlists, Angular QueryCache state, and RPC fallback. -import type { AuthCheckResult } from "./types"; +import { + ensureAngularQueryCache, + hasAngularContext, + isRouterNavigating, + isWorkspaceFlowRoute, + readOwn, + readQueryCacheEntry, + resolveFlowAuthuser, + resolveFlowPageId, + splitFlowPath, +} from "./angular"; +import type { AngularQueryEntry, 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"; + +/** Tool identifier passed to `CHECK_TOOL_AVAILABILITY` by the Flow workspace route guard. */ +const FLOW_TOOL_AVAILABILITY_ID = 22; + +/** Unminified `QueryCache` key for `FLOW_APP_CONFIG`. */ +const APP_CONFIG_QUERY_KEY = ["FLOW_APP_CONFIG"] as const; + +/** Unminified `QueryCache` key for `CHECK_TOOL_AVAILABILITY` on Flow workspace routes. */ +const TOOL_AVAILABILITY_QUERY_KEY = [ + "CHECK_TOOL_AVAILABILITY", + FLOW_TOOL_AVAILABILITY_ID, +] as const; + /** Default Boq frontend data prefix when `WIZ_global_data.eptZe` is absent. */ const DEFAULT_DATA_PREFIX = "/_/AiSandboxAngularFrontend/"; /** Maximum wait in milliseconds for `WIZ_global_data` while the document loads. */ const WIZ_READY_WAIT_MS = 1500; +/** Maximum wait in milliseconds for active route guards and pending queries to settle. */ +const GUARD_SETTLE_WAIT_MS = 2000; + +/** Short hydration wait in milliseconds when Angular hosts mount before `QueryCache` populates. */ +const HYDRATION_CACHE_WAIT_MS = 300; + /** Strict timeout in milliseconds for the read-only Flow backend probe. */ const PROBE_TIMEOUT_MS = 5000; -/** Exact or segment-prefix non-workspace routes from the live Flow route table. */ -const NON_WORKSPACE_SEGMENT_PREFIXES = [ - "/unsupported-country", - "/unsupported-browser", - "/unavailable", - "/age-restricted", - "/privacy", - "/credits-terms", - "/about", - "/flow/about", - "/academy", - "/shared/tool", - "/shared", - "/flow/shared/tool", - "/flow/shared", - "/tools/flow/shared/tool", - "/tools/flow/shared", - "/404", - "/login", - "/tools/flow/about", - "/tools/flow/login", -]; - /** Selector that matches explicit Google Sign-In prompts and Flow landing shells. */ 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; - if (rel === "/flow") { - return true; - } - return NON_WORKSPACE_SEGMENT_PREFIXES.some((prefix) => - hasSegmentPrefix(rel, prefix), - ); -} - -/** Returns `true` when `hostname` and `pathname` target an active Flow workspace route. */ -function isWorkspaceLocation(hostname: string, pathname: string): boolean { +/** Returns `true` when `hostname` and `pathname` target an allowlisted Flow workspace route. */ +export function isWorkspaceLocation(hostname: string, pathname: string): boolean { const host = (hostname || "").toLowerCase(); - const clean = normalizePathname(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")) { + const stripped = splitFlowPath(pathname || "/"); + if (onLabsHost && !stripped.hasLabsFlowPrefix) { return false; } - return !isNonWorkspaceFlowPath(clean); + return isWorkspaceFlowRoute(stripped.route); } /** Builds an `AuthCheckResult` record from the active document metadata. */ @@ -129,7 +108,226 @@ function resolveDataPrefix(raw: string | undefined): string { return leading.endsWith("/") ? leading : `${leading}/`; } -/** Inspects one `batchexecute` response body for `FLOW_APP_CONFIG` or token expiration. */ +/** Returns `true` when `value` is a plain key-value object suitable as a JSPB sparse pivot map. */ +function isPlainPivotObject(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return false; + } + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +/** Reads a 1-based protobuf field from a JSPB `.qf` instance, dense array, or sparse pivot object. */ +function readJspbField(payload: unknown, fieldNumber: number): unknown { + if (!payload || typeof payload !== "object") { + return undefined; + } + let target: unknown = payload; + if (!Array.isArray(target)) { + const qf = readOwn(target, "qf"); + if (Array.isArray(qf)) { + target = qf; + } else { + const toJson = readOwn(target, "toJSON"); + if (typeof toJson === "function") { + try { + const serialized: unknown = toJson.call(target); + if (serialized && typeof serialized === "object") { + target = serialized; + } + } catch { + // Fall through to direct property inspection. + } + } + } + } + const sparseKey = String(fieldNumber); + if (!Array.isArray(target)) { + return readOwn(target, sparseKey); + } + const lastIndex = target.length - 1; + if (lastIndex < 0) { + return undefined; + } + const denseIndex = fieldNumber - 1; + const tail: unknown = target[lastIndex]; + const hasPivot = isPlainPivotObject(tail); + if (denseIndex < lastIndex) { + const denseVal: unknown = target[denseIndex]; + if (denseVal !== undefined && denseVal !== null) { + return denseVal; + } + return hasPivot ? readOwn(tail, sparseKey) : denseVal; + } + if (hasPivot) { + return readOwn(tail, sparseKey); + } + return denseIndex === lastIndex ? tail : undefined; +} + +/** Returns `true` when a JSPB boolean flag value explicitly disables eligibility (`false` or `0`). */ +function isDisabledJspbBool(value: unknown): boolean { + return value === false || value === 0; +} + +/** Evaluates `FLOW_APP_CONFIG` (`cPZSdc`) payload fields `31` (country) and `32` (age). */ +function evaluateAppConfigPayload( + payload: unknown, +): "ok" | "unsupported_country" | "age_restricted" | "invalid" { + if (!payload || typeof payload !== "object") { + return "invalid"; + } + if (isDisabledJspbBool(readJspbField(payload, 31))) { + return "unsupported_country"; + } + if (isDisabledJspbBool(readJspbField(payload, 32))) { + return "age_restricted"; + } + return "ok"; +} + +/** Evaluates `CHECK_TOOL_AVAILABILITY` (`KV2T2d`) field `1` (`Cla()`) codes `4`..`8`. */ +function evaluateToolAvailabilityPayload( + payload: unknown, +): "ok" | "age_restricted" | "unavailable" { + if (!payload || typeof payload !== "object") { + return "ok"; + } + let rawCode: unknown = readJspbField(payload, 1); + if (rawCode === undefined) { + const cla = readOwn(payload, "Cla"); + if (typeof cla === "function") { + try { + rawCode = cla.call(payload); + } catch { + rawCode = undefined; + } + } + } + const code = + typeof rawCode === "number" && Number.isFinite(rawCode) + ? Math.trunc(rawCode) + : undefined; + if (code === 7) { + return "age_restricted"; + } + if (code === 4 || code === 5 || code === 6 || code === 8) { + return "unavailable"; + } + return "ok"; +} + +/** Returns `true` when `entry` is actively fetching or still awaiting its initial settlement. */ +function isQueryPending(entry: AngularQueryEntry | undefined): boolean { + if (!entry?.state) return false; + return ( + entry.state.status === "pending" || entry.state.fetchStatus === "fetching" + ); +} + +/** Returns `true` when a `QueryCache` error indicates HTTP 401 or gRPC `UNAUTHENTICATED` (`16`). */ +function isUnauthenticatedQueryError(err: unknown): boolean { + if (!err || typeof err !== "object") return false; + const um = readOwn(err, "um"); + const httpStatus = readOwn(err, "httpStatusCode"); + const status = readOwn(err, "status"); + const code = readOwn(err, "code"); + if (um === 401 || httpStatus === 401 || status === 401 || code === 16) { + return true; + } + if (status && typeof status === "object") { + const vf = readOwn(status, "vf"); + if (typeof vf === "function") { + try { + if (vf.call(status) === 16) return true; + } catch { + return false; + } + } + } + return false; +} + +/** Reads settled eligibility queries from Angular's `QueryCache` after awaiting active route guards. */ +async function checkAngularQueryEligibility(): Promise { + if (!hasAngularContext()) { + return null; + } + const start = Date.now(); + const settleDeadline = start + GUARD_SETTLE_WAIT_MS; + const hydrationDeadline = start + HYDRATION_CACHE_WAIT_MS; + + while (true) { + if (!isWorkspaceLocation(location.hostname, location.pathname)) { + return authResult(false, true, false, 0, "non_workspace_route"); + } + if (document.querySelector(SIGN_IN_SELECTOR)) { + return authResult(false, true, false, 0, "sign_in_prompt"); + } + + const cache = await ensureAngularQueryCache(); + const appQuery = readQueryCacheEntry(cache, APP_CONFIG_QUERY_KEY); + const toolQuery = readQueryCacheEntry(cache, TOOL_AVAILABILITY_QUERY_KEY); + const navigating = isRouterNavigating(); + const pending = isQueryPending(appQuery) || isQueryPending(toolQuery); + const now = Date.now(); + + if ((navigating || pending) && now < settleDeadline) { + await new Promise((resolve) => setTimeout(resolve, 50)); + continue; + } + if (!appQuery && !toolQuery && now < hydrationDeadline) { + await new Promise((resolve) => setTimeout(resolve, 50)); + continue; + } + + const authErr = + appQuery?.state?.error ?? + appQuery?.state?.failureReason ?? + toolQuery?.state?.error ?? + toolQuery?.state?.failureReason; + if (isUnauthenticatedQueryError(authErr)) { + return authResult(false, false, true, 401, "rpc_unauthenticated"); + } + + const toolData = + toolQuery?.state?.status === "success" ? toolQuery.state.data : undefined; + if (toolData !== undefined) { + const toolVerdict = evaluateToolAvailabilityPayload(toolData); + if (toolVerdict !== "ok") { + return authResult(false, true, false, 0, toolVerdict); + } + } + + const appData = + appQuery?.state?.status === "success" ? appQuery.state.data : undefined; + if (appData !== undefined) { + const appVerdict = evaluateAppConfigPayload(appData); + if (appVerdict === "unsupported_country" || appVerdict === "age_restricted") { + return authResult(false, true, false, 0, appVerdict); + } + } + + if ((!appQuery || !toolQuery) && now < hydrationDeadline) { + await new Promise((resolve) => setTimeout(resolve, 50)); + continue; + } + + if (appData !== undefined && toolData !== undefined) { + if (evaluateAppConfigPayload(appData) !== "ok") { + return null; + } + if (!isWorkspaceLocation(location.hostname, location.pathname)) { + return authResult(false, true, false, 0, "non_workspace_route"); + } + return authResult(true, false, false, 0, "ok"); + } + + return null; + } +} + +/** Inspects a batched `batchexecute` response body for `cPZSdc` and `KV2T2d` eligibility or auth errors. */ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { let verifiedConfig = false; for (const rawLine of text.split(/\r?\n/)) { @@ -153,7 +351,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,22 +373,25 @@ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { if (typeof entry[2] !== "string") { continue; } - let config: unknown; + let parsedPayload: unknown; try { - config = JSON.parse(entry[2]); + parsedPayload = JSON.parse(entry[2]); } catch { continue; } - if (Array.isArray(config)) { - if (config[30] === false) { - return authResult(false, true, false, status, "unsupported_country"); + if (entry[1] === APP_CONFIG_RPC_ID) { + const verdict = evaluateAppConfigPayload(parsedPayload); + if (verdict === "unsupported_country" || verdict === "age_restricted") { + return authResult(false, true, false, status, verdict); } - if (config[31] === false) { - return authResult(false, true, false, status, "age_restricted"); + if (verdict === "ok") { + verifiedConfig = true; + } + } else if (entry[1] === TOOL_AVAILABILITY_RPC_ID) { + const toolVerdict = evaluateToolAvailabilityPayload(parsedPayload); + if (toolVerdict !== "ok") { + return authResult(false, true, false, status, toolVerdict); } - verifiedConfig = true; - } else if (config !== null && typeof config === "object") { - verifiedConfig = true; } } } @@ -200,7 +404,7 @@ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { return authResult(true, false, false, status, "ok"); } -/** Verifies host, workspace route, `WIZ_global_data` tokens, and an HTTP 200 Flow probe. */ +/** Verifies host, workspace route, `WIZ_global_data` tokens, Angular `QueryCache`, or a batched Flow RPC probe. */ export async function checkAuth(): Promise { await waitForWizData(); @@ -228,8 +432,13 @@ export async function checkAuth(): Promise { return authResult(false, true, false, 0, "missing_wiz_token"); } + const cachedResult = await checkAngularQueryEligibility(); + if (cachedResult) { + return cachedResult; + } + const params = new URLSearchParams({ - rpcids: APP_CONFIG_RPC_ID, + rpcids: `${APP_CONFIG_RPC_ID},${TOOL_AVAILABILITY_RPC_ID}`, "source-path": location.pathname || "/", hl: "en", rt: "c", @@ -240,9 +449,25 @@ export async function checkAuth(): Promise { if (typeof wiz.FdrFJe === "string" && wiz.FdrFJe.trim()) { params.set("f.sid", wiz.FdrFJe.trim()); } + const authuser = resolveFlowAuthuser(); + if (authuser) { + params.set("authuser", authuser); + } + const pageId = resolveFlowPageId(); + if (pageId) { + params.set("pageId", pageId); + } const reqPayload = JSON.stringify([ - [[APP_CONFIG_RPC_ID, "[]", null, "generic"]], + [ + [APP_CONFIG_RPC_ID, "[]", null, "1"], + [ + TOOL_AVAILABILITY_RPC_ID, + JSON.stringify([FLOW_TOOL_AVAILABILITY_ID]), + null, + "2", + ], + ], ]); const body = `f.req=${encodeURIComponent(reqPayload)}&at=${encodeURIComponent(xsrfToken)}`; const prefix = resolveDataPrefix(wiz.eptZe); diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..eb64774 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -20,6 +20,10 @@ export interface WizGlobalData { eptZe?: string; /** Encoded FIFE host configuration string. */ TSDtV?: string; + /** Active Google account index rendered by the server. */ + QrtxK?: string; + /** Delegated or organization page identifier for batchexecute calls. */ + S06Grb?: string; } /** Angular Router subset used for in-app navigation. */ @@ -32,6 +36,48 @@ export interface AngularRouter { options: unknown; } +/** State snapshot stored on one cached query entry in `QueryCache`. */ +export interface AngularQueryState { + /** Settlement status (`pending`, `success`, or `error`). */ + status?: string; + /** Active network status (`fetching`, `paused`, or `idle`). */ + fetchStatus?: string; + /** Decoded response payload or protobuf message instance. */ + data?: unknown; + /** Terminal error reported by the last failed fetch. */ + error?: unknown; + /** Intermediate failure reason recorded while retries remain active. */ + failureReason?: unknown; +} + +/** Cached query entry managed by Angular's `QueryCache`. */ +export interface AngularQueryEntry { + /** Unminified query key array. */ + queryKey?: readonly unknown[]; + /** Serialized query key hash string. */ + queryHash?: string; + /** Live query state snapshot. */ + state?: AngularQueryState; +} + +/** Subset of TanStack `QueryCache` exposed on Angular's `QueryClient`. */ +export interface AngularQueryCache { + /** Finds a single cached query matching `queryKey`. */ + find?: (filters: { queryKey: readonly unknown[]; exact?: boolean }) => AngularQueryEntry | undefined; + /** Looks up a cached query by its serialized `queryHash`. */ + get?: (queryHash: string) => AngularQueryEntry | undefined; + /** Lists all cached query entries. */ + getAll?: () => AngularQueryEntry[]; + /** Underlying hash-keyed query registry map. */ + queries?: Map; +} + +/** Subset of Angular's injected `QueryClient` holding `queryCache`. */ +export interface AngularQueryClient { + /** Active query cache instance. */ + queryCache: AngularQueryCache; +} + /** Destroyable Angular component or service lifecycle handle. */ export interface AngularLifecycleHandle { /** Lifecycle destroy marker in the Flow front end from 2026-11-18 on. */ From 824f551625356dc620952c097c7abd12b03c4cdc Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:27:22 +0000 Subject: [PATCH 2/3] fix(flow): parse full project URLs and refine login checks - Parse URL paths in project_id_from_url and is_project_subroute_url - Keep polling across Flow SSO redirect routes during login promotion - Do not open a second login window when verification fails - Detect Google auth cookies from Cookies without requiring History - Reject only verified KV2T2d code 7 in check_auth - Move shared route and Angular query helpers to leaf modules --- src/auth.rs | 132 +++++++++--------------- src/chrome.rs | 51 +++------ src/cli.rs | 2 +- src/engine.rs | 2 +- src/flow_url.rs | 189 ++++++++++++++++++++++++++++++++++ src/main.rs | 1 + src/project.rs | 7 +- src/project_route.rs | 156 ++++++---------------------- src/project_store.rs | 2 +- ts/angular.ts | 240 +------------------------------------------ ts/angular_query.ts | 154 +++++++++++++++++++++++++++ ts/check_auth.ts | 52 ++++------ ts/flow_route.ts | 154 +++++++++++++++++++++++++++ 13 files changed, 627 insertions(+), 515 deletions(-) create mode 100644 src/flow_url.rs create mode 100644 ts/angular_query.ts create mode 100644 ts/flow_route.ts diff --git a/src/auth.rs b/src/auth.rs index 7121992..b0ba8cd 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -12,14 +12,13 @@ use serde::Deserialize; use serde_json::{Map, Value, json}; 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::cookies::{has_google_auth_cookies, read_cookies_file}; use crate::engine::{ChromeEngine, ENGINE_NAME}; -use crate::project_route::{is_flow_origin_host, is_workspace_flow_route, split_flow_path}; +use crate::flow_url::{is_about_landing_url, is_signed_in_flow_url}; /// Maximum number of `/about` passive SSO redirect attempts during session promotion. const MAX_ABOUT_SSO_RETRIES: usize = 2; @@ -39,38 +38,6 @@ 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'/')) -} - -/// 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") && is_flow_origin_host(url.host_str()) - }) -} - -/// Returns `true` when `raw` points to a Google Flow workspace host and allowlisted route. -pub(crate) fn is_signed_in_flow_url(raw: &str) -> bool { - let Ok(parsed) = Url::parse(raw) else { - return false; - }; - if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { - return false; - } - let host = parsed.host_str().unwrap_or_default().to_ascii_lowercase(); - let on_labs = host == "labs.google" || host.ends_with(".labs.google"); - let stripped = split_flow_path(parsed.path()); - if on_labs && !stripped.has_labs_flow_prefix { - return false; - } - is_workspace_flow_route(&stripped.route) -} - /// Evaluates `checkAuth` once in the active page, retrying brief context resets during navigation. async fn eval_check_auth_once(engine: &ChromeEngine) -> Option { let _ = engine @@ -162,22 +129,6 @@ fn signed_in_login_result(mode: &str, count: usize, url: String) -> Value { }) } -/// Returns `true` when `url` points to a Google Flow `/about` landing route under any supported prefix. -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"); - }; - if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { - return false; - } - let stripped = split_flow_path(parsed.path()); - let rel = stripped.route.as_str(); - rel == "/flow" - || 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. fn is_interactive_signin_url(url: &str) -> bool { url.contains("/InteractiveLogin") @@ -243,24 +194,23 @@ async fn finalize_promoted_login(engine: &ChromeEngine, start_url: &str) -> Resu } continue; } - if is_flow_host_url(&cur) && !is_signed_in_flow_url(&cur) { - break; - } 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 = check_page_auth(engine, true).await; if auth.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 is_signed_in_flow_url(&final_url) { + return Ok(Some(signed_in_login_result( + "interactive-chrome", + cookies.len(), + final_url, + ))); + } } if matches!( auth.get("reason").and_then(Value::as_str), - Some("unsupported_country" | "age_restricted" | "unavailable") + Some("unsupported_country" | "age_restricted") ) { break; } @@ -292,12 +242,33 @@ async fn login_with_chrome( rejected ); } - if st.exited { - let target_url = st.flow_url.as_deref().unwrap_or(FLOW_URL); + if st.exited || st.has_google_auth_cookies { + let mut target_flow_url = st.flow_url; + if st.has_google_auth_cookies && !st.exited { + tokio::time::sleep(Duration::from_secs(4)).await; + if let Some(after_settle) = engine.poll_login_chrome().await? { + if let Some(rejected) = after_settle.rejected_url { + engine.shutdown().await; + anyhow::bail!( + "Google Accounts rejected sign-in in this browser session (URL: {}).", + rejected + ); + } + if after_settle.flow_url.is_some() { + target_flow_url = after_settle.flow_url; + } + } + } + let target_url = target_flow_url.as_deref().unwrap_or(FLOW_URL); if let Some(res) = finalize_promoted_login(engine, target_url).await? { return Ok(res); } - engine.launch_interactive_login(FLOW_SSO_URL, false).await?; + 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." + ); } } } else { @@ -332,8 +303,6 @@ async fn login_with_chrome( let clamped_secs = timeout_secs.clamp(15, 3600); let deadline = Instant::now() + Duration::from_secs(clamped_secs); - let mut ready_polls = 0usize; - let mut ready_url: Option = None; let mut last_flow_url: Option = None; loop { @@ -353,31 +322,30 @@ async fn login_with_chrome( last_flow_url = Some(observed.clone()); } - if st.has_google_auth_cookies { - if ready_url.as_deref() == st.flow_url.as_deref() { - ready_polls += 1; - } else { - ready_url = st.flow_url.clone(); - ready_polls = 1; + if st.exited || st.has_google_auth_cookies { + let mut target_flow_url = st.flow_url.or_else(|| last_flow_url.clone()); + if st.has_google_auth_cookies && !st.exited { + tokio::time::sleep(Duration::from_secs(4)).await; + if let Some(after_settle) = engine.poll_login_chrome().await? { + if let Some(rejected) = after_settle.rejected_url { + engine.shutdown().await; + anyhow::bail!( + "Google Accounts rejected sign-in in this browser session (URL: {}).", + rejected + ); + } + if after_settle.flow_url.is_some() { + target_flow_url = after_settle.flow_url; + } + } } - } else { - ready_polls = 0; - ready_url = None; - } - - if st.exited || ready_polls >= 2 { - let target_url = st - .flow_url - .as_deref() - .or(last_flow_url.as_deref()) - .unwrap_or(FLOW_URL); + let target_url = target_flow_url.as_deref().unwrap_or(FLOW_URL); if let Some(res) = finalize_promoted_login(engine, target_url).await? { return Ok(res); } if st.exited { anyhow::bail!("Sign-in window was closed before Google Sign-In completed."); } - engine.launch_interactive_login(FLOW_SSO_URL, false).await?; anyhow::bail!( "Google Sign-In wrote authentication cookies, but workspace verification did not succeed. Run flow_login again." ); diff --git a/src/chrome.rs b/src/chrome.rs index f5dee73..a59dc00 100644 --- a/src/chrome.rs +++ b/src/chrome.rs @@ -10,7 +10,8 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crate::cdp::{CdpConnection, fetch_json_version}; use crate::config::{chrome_profile_dir, cli_chrome_path, configured_cdp_port}; -use crate::cookies::{cookie_domain_matches, is_google_auth_cookie_pair}; +use crate::cookies::is_google_auth_cookie_pair; +use crate::flow_url::{is_flow_host_url, is_signed_in_flow_url}; use crate::instance::{acquire_instance_lock, stop_orphan_chrome}; use crate::platform::{create_private_dir_all, focus_process, interrupt_process}; @@ -55,7 +56,7 @@ pub(crate) struct LoginProfileProbe { pub(crate) rejected_url: Option, /// Latest signed-in Google Flow workspace URL observed in profile history. pub(crate) flow_url: Option, - /// True when Google auth cookies, Flow-origin cookies, and a workspace history URL exist. + /// True when core Google Sign-In cookies were updated since launch. pub(crate) has_google_auth_cookies: bool, } @@ -352,52 +353,39 @@ fn probe_history_db(scratch_history: &Path, min_webkit_us: i64, probe: &mut Logi } return; } - if !flow_checked && crate::auth::is_flow_host_url(&url) { + if !flow_checked && is_flow_host_url(&url) { if url.to_ascii_lowercase().contains("/fx/api/auth/") { continue; } flow_checked = true; - if crate::auth::is_signed_in_flow_url(&url) { + if is_signed_in_flow_url(&url) { probe.flow_url = Some(url); } } } } -/// Inspects a scratch copy of Chrome's `Cookies` database for `.google.com` and Flow-origin cookies. -fn probe_cookies_db(scratch_cookies: &Path, min_webkit_us: i64) -> (bool, bool) { +/// 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 { let Ok(conn) = rusqlite::Connection::open(scratch_cookies) else { - return (false, false); + return false; }; let Ok(mut stmt) = conn.prepare("SELECT host_key, name FROM cookies WHERE last_update_utc >= ?1") else { - return (false, false); + return false; }; let Ok(rows) = stmt.query_map([min_webkit_us], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) }) else { - return (false, false); + return false; }; - let mut has_google_cookie = false; - let mut has_flow_cookie = false; for (host, name) in rows.flatten() { - let clean_host = host.trim().trim_start_matches('.'); - if clean_host.eq_ignore_ascii_case("google.com") && is_google_auth_cookie_pair(&host, &name) - { - has_google_cookie = true; - } - if !name.trim().is_empty() - && (cookie_domain_matches(&host, "flow.google.com") - || cookie_domain_matches(&host, "labs.google")) - { - has_flow_cookie = true; - } - if has_google_cookie && has_flow_cookie { - break; + if is_google_auth_cookie_pair(&host, &name) { + return true; } } - (has_google_cookie, has_flow_cookie) + false } /// Inspects Chrome `History` and `Cookies` files for entries updated since `started_at`. @@ -431,22 +419,15 @@ pub(crate) async fn inspect_login_profile( dir.join("Default").join("Cookies"), dir.join("Default").join("Network").join("Cookies"), ]; - let mut has_google_cookie = false; - let mut has_flow_cookie = false; 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) { - let (google_hit, flow_hit) = probe_cookies_db(&scratch_cookies, min_webkit_us); - has_google_cookie |= google_hit; - has_flow_cookie |= flow_hit; - if has_google_cookie && has_flow_cookie { - break; - } + probe.has_google_auth_cookies = true; + break; } } - probe.has_google_auth_cookies = - has_google_cookie && has_flow_cookie && probe.flow_url.is_some(); probe }) diff --git a/src/cli.rs b/src/cli.rs index 020215b..6b52dd8 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -398,7 +398,7 @@ async fn check_flow_build_in_engine(engine: &ChromeEngine) -> Value { return check("flow-build", "fail", format!("{e:#}")); } let mut url = engine.current_url().await.unwrap_or_default(); - if !auth::is_flow_host_url(&url) { + if !crate::flow_url::is_flow_host_url(&url) { if let Err(e) = engine.navigate(FLOW_URL).await { return check("flow-build", "fail", format!("{e:#}")); } diff --git a/src/engine.rs b/src/engine.rs index d30285b..3dd56c6 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -140,7 +140,7 @@ pub(crate) struct LoginPollStatus { pub(crate) rejected_url: Option, /// Latest signed-in Google Flow workspace URL observed in profile history. pub(crate) flow_url: Option, - /// True when Google cookies, Flow cookies, and a workspace history entry exist. + /// True when Google authentication cookies exist in the login profile. pub(crate) has_google_auth_cookies: bool, } diff --git a/src/flow_url.rs b/src/flow_url.rs new file mode 100644 index 0000000..30d2a9b --- /dev/null +++ b/src/flow_url.rs @@ -0,0 +1,189 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Parse and classify Google Flow hosts, prefixes, and workspace routes. + +use url::Url; + +/// Parsed components of a Google Flow URL path after stripping active prefixes. +pub(crate) struct StrippedFlowPath { + /// Active route prefix starting with `/` when present, keeping original case. + pub(crate) prefix: String, + /// Normalized lowercase route path starting with `/` without trailing slashes. + pub(crate) route: String, + /// True when `/fx/tools/flow` appears in the stripped prefix segments. + has_labs_flow_prefix: bool, +} + +/// Returns `true` when `path` equals `prefix` or starts with `prefix` followed by `/`. +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'/')) +} + +/// Returns `true` when `host` is a Google Flow host (`flow.google.com` or `labs.google`). +pub(crate) fn is_flow_origin_host(host: Option<&str>) -> bool { + let Some(h) = host else { + return false; + }; + h.eq_ignore_ascii_case("flow.google.com") + || h.eq_ignore_ascii_case("labs.google") + || h.to_ascii_lowercase().ends_with(".labs.google") +} + +/// Returns `true` when `raw` points to a Google Flow `http` or `https` host. +pub(crate) fn is_flow_host_url(raw: &str) -> bool { + Url::parse(raw).is_ok_and(|url| { + matches!(url.scheme(), "http" | "https") && is_flow_origin_host(url.host_str()) + }) +} + +/// Returns `true` when `seg` is a reserved Flow top-level segment rather than an organization slug. +fn is_reserved_flow_segment(seg: &str) -> bool { + matches!( + seg.to_ascii_lowercase().as_str(), + "project" + | "projects" + | "search" + | "changelogs" + | "about" + | "shared" + | "flow" + | "tools" + | "fx" + | "u" + | "unsupported-country" + | "unsupported-browser" + | "unavailable" + | "age-restricted" + | "privacy" + | "credits-terms" + | "academy" + | "404" + | "login" + | "debug" + ) +} + +/// Strips `/fx/tools/flow`, `/fx`, `/u/`, and `//global` prefixes from `path`. +pub(crate) fn split_flow_path(path: &str) -> StrippedFlowPath { + let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + let mut prefix = Vec::new(); + let mut has_labs_flow_prefix = false; + let mut i = 0; + while i < segs.len() { + if segs.len() >= i + 3 + && segs[i].eq_ignore_ascii_case("fx") + && segs[i + 1].eq_ignore_ascii_case("tools") + && segs[i + 2].eq_ignore_ascii_case("flow") + { + has_labs_flow_prefix = true; + prefix.extend_from_slice(&segs[i..i + 3]); + i += 3; + } else if segs[i].eq_ignore_ascii_case("fx") { + prefix.push(segs[i]); + i += 1; + } else if i + 1 < segs.len() + && ((segs[i].eq_ignore_ascii_case("u") + && !segs[i + 1].is_empty() + && segs[i + 1].bytes().all(|b| b.is_ascii_digit())) + || (segs[i + 1].eq_ignore_ascii_case("global") + && !is_reserved_flow_segment(segs[i]))) + { + prefix.extend_from_slice(&segs[i..i + 2]); + i += 2; + } else { + break; + } + } + let prefix_str = if prefix.is_empty() { + String::new() + } else { + format!("/{}", prefix.join("/")) + }; + let route = if i >= segs.len() { + "/".to_string() + } else { + format!("/{}", segs[i..].join("/")).to_ascii_lowercase() + }; + StrippedFlowPath { + prefix: prefix_str, + route, + has_labs_flow_prefix, + } +} + +/// Returns `true` when lowercase segments after `/project/` match a recognized Flow project subroute. +fn is_project_subroute_segments(segs: &[&str]) -> bool { + match segs { + ["character" | "tools" | "create-tool" | "trash" | "chat"] => true, + [ + "character" | "scene" | "edit" | "tool" | "collection" | "chat", + id, + ] => !id.is_empty(), + ["collection", id, "character"] | ["trash", "collection", id] => !id.is_empty(), + _ => false, + } +} + +/// Returns `true` when lowercase segments after `/project/` match a non-grid editor or view subroute. +pub(crate) fn is_non_grid_project_subroute_segments(segs: &[&str]) -> bool { + match segs { + ["character" | "tools" | "create-tool" | "trash" | "chat"] => true, + ["character" | "scene" | "edit" | "tool" | "chat", id] => !id.is_empty(), + ["collection", id, "character"] | ["trash", "collection", id] => !id.is_empty(), + _ => false, + } +} + +/// Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. +pub(crate) fn is_workspace_flow_route(route: &str) -> bool { + if matches!(route, "/" | "/projects" | "/search" | "/changelogs") { + return true; + } + let Some(rest) = route.strip_prefix("/project/") else { + return false; + }; + let segs: Vec<&str> = rest.split('/').collect(); + let Some((&project_id, sub)) = segs.split_first() else { + return false; + }; + !project_id.is_empty() && (sub.is_empty() || is_project_subroute_segments(sub)) +} + +/// Returns `true` when `parsed` points to a Google Flow workspace host and allowlisted route. +pub(crate) fn is_signed_in_parsed_flow_url(parsed: &Url) -> bool { + if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { + return false; + } + let host = parsed.host_str().unwrap_or_default().to_ascii_lowercase(); + let on_labs = host == "labs.google" || host.ends_with(".labs.google"); + let stripped = split_flow_path(parsed.path()); + if on_labs && !stripped.has_labs_flow_prefix { + return false; + } + is_workspace_flow_route(&stripped.route) +} + +/// Returns `true` when `raw` points to a Google Flow workspace host and allowlisted route. +pub(crate) fn is_signed_in_flow_url(raw: &str) -> bool { + Url::parse(raw).is_ok_and(|parsed| is_signed_in_parsed_flow_url(&parsed)) +} + +/// Returns `true` when `url` points to a Google Flow `/about` landing route under any supported prefix. +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"); + }; + if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { + return false; + } + let stripped = split_flow_path(parsed.path()); + let rel = stripped.route.as_str(); + rel == "/flow" + || has_segment_prefix(rel, "/about") + || has_segment_prefix(rel, "/flow/about") + || has_segment_prefix(rel, "/tools/flow/about") +} diff --git a/src/main.rs b/src/main.rs index d180c44..e069e29 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ mod cookies; mod db; mod download; mod engine; +mod flow_url; mod generation; mod http; mod instance; diff --git a/src/project.rs b/src/project.rs index a0e57b9..adb6d77 100644 --- a/src/project.rs +++ b/src/project.rs @@ -13,9 +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, redirect_sso_if_about}; use crate::config::{FLOW_URL, has_persisted_session}; use crate::engine::{ChromeEngine, ENGINE_NAME}; +use crate::flow_url::{is_flow_host_url, is_signed_in_flow_url}; pub(crate) use crate::project_route::{ is_project_subroute_url, project_id_from_url, project_subroute_url, project_workspace_url, }; @@ -508,8 +509,8 @@ pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { pub(crate) async fn create_project(engine: &ChromeEngine, title: Option<&str>) -> Result { engine.ensure_page().await?; let initial_url = engine.current_url().await.unwrap_or_default(); - let already_on_home = crate::auth::is_signed_in_flow_url(&initial_url) - && project_id_from_url(&initial_url).is_none(); + let already_on_home = + is_signed_in_flow_url(&initial_url) && project_id_from_url(&initial_url).is_none(); if !already_on_home { engine.navigate(FLOW_URL).await?; tokio::time::sleep(Duration::from_millis(900)).await; diff --git a/src/project_route.rs b/src/project_route.rs index b9962a9..c48c3cc 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -6,13 +6,13 @@ use url::Url; use crate::config::FLOW_URL; +use crate::flow_url::{ + is_flow_origin_host, is_non_grid_project_subroute_segments, is_signed_in_parsed_flow_url, + is_workspace_flow_route, split_flow_path, +}; -/// Extracts the `/project/` segment from a Flow workspace URL or path. -pub(crate) fn project_id_from_url(url: &str) -> Option { - if url.contains("://") && !crate::auth::is_signed_in_flow_url(url) { - return None; - } - let path = url.split(['?', '#']).next()?; +/// Extracts the `/project/` segment from a prefix-stripped Flow URL path. +fn project_id_from_path(path: &str) -> Option { let stripped = split_flow_path(path); if !stripped.route.starts_with("/project/") || !is_workspace_flow_route(&stripped.route) { return None; @@ -23,141 +23,47 @@ pub(crate) fn project_id_from_url(url: &str) -> Option { (!id.is_empty()).then(|| id.to_string()) } -/// Returns `true` when `host` is a Google Flow host (`flow.google.com` or `labs.google`). -pub(crate) fn is_flow_origin_host(host: Option<&str>) -> bool { - let Some(h) = host else { - return false; - }; - h.eq_ignore_ascii_case("flow.google.com") - || h.eq_ignore_ascii_case("labs.google") - || h.to_ascii_lowercase().ends_with(".labs.google") -} - -/// Parsed components of a Google Flow URL path after stripping active prefixes. -pub(crate) struct StrippedFlowPath { - /// Active route prefix starting with `/` when present, preserving original case. - pub(crate) prefix: String, - /// Normalized lowercase route path starting with `/` without trailing slashes. - pub(crate) route: String, - /// True when `/fx/tools/flow` appears in the stripped prefix segments. - pub(crate) has_labs_flow_prefix: bool, -} - -/// Returns `true` when `seg` is a reserved Flow top-level segment rather than an organization slug. -fn is_reserved_flow_segment(seg: &str) -> bool { - matches!( - seg.to_ascii_lowercase().as_str(), - "project" - | "projects" - | "search" - | "changelogs" - | "about" - | "shared" - | "flow" - | "tools" - | "fx" - | "u" - | "unsupported-country" - | "unsupported-browser" - | "unavailable" - | "age-restricted" - | "privacy" - | "credits-terms" - | "academy" - | "404" - | "login" - | "debug" - ) -} - -/// Strips `/fx/tools/flow`, `/fx`, `/u/`, and `//global` prefixes from `path`. -pub(crate) fn split_flow_path(path: &str) -> StrippedFlowPath { - let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); - let mut prefix = Vec::new(); - let mut has_labs_flow_prefix = false; - let mut i = 0; - while i < segs.len() { - if segs.len() >= i + 3 - && segs[i].eq_ignore_ascii_case("fx") - && segs[i + 1].eq_ignore_ascii_case("tools") - && segs[i + 2].eq_ignore_ascii_case("flow") - { - has_labs_flow_prefix = true; - prefix.extend_from_slice(&segs[i..i + 3]); - i += 3; - } else if segs[i].eq_ignore_ascii_case("fx") { - prefix.push(segs[i]); - i += 1; - } else if i + 1 < segs.len() - && ((segs[i].eq_ignore_ascii_case("u") - && !segs[i + 1].is_empty() - && segs[i + 1].bytes().all(|b| b.is_ascii_digit())) - || (segs[i + 1].eq_ignore_ascii_case("global") - && !is_reserved_flow_segment(segs[i]))) - { - prefix.extend_from_slice(&segs[i..i + 2]); - i += 2; - } else { - break; +/// Extracts the `/project/` segment from a Flow workspace URL or path. +pub(crate) fn project_id_from_url(url: &str) -> Option { + if let Ok(parsed) = Url::parse(url) { + if !is_signed_in_parsed_flow_url(&parsed) { + return None; } + return project_id_from_path(parsed.path()); } - let prefix_str = if prefix.is_empty() { - String::new() - } else { - format!("/{}", prefix.join("/")) - }; - let route = if i >= segs.len() { - "/".to_string() - } else { - format!("/{}", segs[i..].join("/")).to_ascii_lowercase() - }; - StrippedFlowPath { - prefix: prefix_str, - route, - has_labs_flow_prefix, - } -} - -/// Returns `true` when lowercase segments after `/project/` match a recognized Flow project subroute. -fn is_project_subroute_segments(segs: &[&str]) -> bool { - match segs { - ["character" | "tools" | "create-tool" | "trash" | "chat"] => true, - [ - "character" | "scene" | "edit" | "tool" | "collection" | "chat", - id, - ] => !id.is_empty(), - ["collection", id, "character"] | ["trash", "collection", id] => !id.is_empty(), - _ => false, + if !url.starts_with('/') { + return None; } + let path = url.split(['?', '#']).next()?; + project_id_from_path(path) } -/// Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. -pub(crate) fn is_workspace_flow_route(route: &str) -> bool { - if matches!(route, "/" | "/projects" | "/search" | "/changelogs") { - return true; - } - let Some(rest) = route.strip_prefix("/project/") else { +/// Returns `true` when `path` points to a non-grid subroute inside `/project/`. +fn is_project_subroute_path(path: &str) -> bool { + let stripped = split_flow_path(path); + let Some(rest) = stripped.route.strip_prefix("/project/") else { return false; }; let segs: Vec<&str> = rest.split('/').collect(); let Some((&project_id, sub)) = segs.split_first() else { return false; }; - !project_id.is_empty() && (sub.is_empty() || is_project_subroute_segments(sub)) + !project_id.is_empty() && is_non_grid_project_subroute_segments(sub) } /// Returns `true` when `url` points to a non-grid subroute inside `/project/`. pub(crate) fn is_project_subroute_url(url: &str) -> bool { - let path = url.split(['?', '#']).next().unwrap_or_default(); - let stripped = split_flow_path(path); - let Some(rest) = stripped.route.strip_prefix("/project/") else { - return false; - }; - let segs: Vec<&str> = rest.split('/').collect(); - let Some((&project_id, sub)) = segs.split_first() else { + if let Ok(parsed) = Url::parse(url) { + if !is_signed_in_parsed_flow_url(&parsed) { + return false; + } + return is_project_subroute_path(parsed.path()); + } + if !url.starts_with('/') { return false; - }; - !project_id.is_empty() && is_project_subroute_segments(sub) + } + let path = url.split(['?', '#']).next().unwrap_or_default(); + is_project_subroute_path(path) } /// Extracts the active route prefix from a Flow URL path. diff --git a/src/project_store.rs b/src/project_store.rs index 5c97689..ac56c72 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -9,8 +9,8 @@ use anyhow::{Context, Result}; use serde_json::{Value, json}; use tokio::sync::MutexGuard; -use crate::auth::is_signed_in_flow_url; use crate::engine::{ChromeEngine, checked_runtime_result}; +use crate::flow_url::is_signed_in_flow_url; use crate::project::project_id_from_url; /// Holds the browser project store lock and pins the project and runtime session. diff --git a/ts/angular.ts b/ts/angular.ts index f1c378c..d7f6606 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -8,16 +8,13 @@ import { delay, elText, fifeBase, - hoverProbe, normalizeFlowMediaUrl, readMediaUrl, } from "./dom"; +import { splitFlowPath } from "./flow_route"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; import { runtimeState } from "./state"; import type { - AngularQueryCache, - AngularQueryClient, - AngularQueryEntry, AngularRouter, FlowStoreHandle, FlowTile, @@ -43,7 +40,7 @@ export function readOwn(obj: unknown, key: string): unknown { } /** Returns `true` when `val` is a non-null, non-array, non-`Map`, non-DOM object. */ -function isPlainRecord(val: unknown): val is Record { +export function isPlainRecord(val: unknown): val is Record { return Boolean( val && typeof val === "object" && @@ -192,106 +189,6 @@ export function withLViewMapCapture( /** Cached query-parameter key per Angular Router instance. */ const routerQueryParamKeys = new WeakMap(); -/** Parsed prefix and normalized route details of a Flow pathname. */ -export interface StrippedFlowPath { - /** Active prefix starting with `/` when present, preserving original case. */ - prefix: string; - /** Normalized lowercase route starting with `/` without trailing slashes. */ - route: string; - /** True when `/fx/tools/flow` appears among the stripped prefixes. */ - hasLabsFlowPrefix: boolean; - /** Account index extracted from `/u/` when present. */ - pathAuthuser: string | null; -} - -/** Reserved Flow top-level route names that cannot act as `` before `/global`. */ -const RESERVED_FLOW_SEGMENTS = new Set([ - "project", "projects", "search", "changelogs", "about", "shared", "flow", - "tools", "fx", "u", "unsupported-country", "unsupported-browser", "unavailable", - "age-restricted", "privacy", "credits-terms", "academy", "404", "login", "debug", -]); - -/** Strips `/fx/tools/flow`, `/fx`, `/u/`, and `//global` prefixes from `pathname`. */ -export function splitFlowPath(pathname: string = location.pathname): StrippedFlowPath { - const cleanPath = (pathname || "/").split(/[?#]/)[0] || "/"; - const segs = cleanPath.split("/").filter(Boolean); - const prefixSegs: string[] = []; - let hasLabsFlowPrefix = false; - let pathAuthuser: string | null = null; - let i = 0; - while (i < segs.length) { - const low0 = segs[i].toLowerCase(); - const low1 = (segs[i + 1] || "").toLowerCase(); - const low2 = (segs[i + 2] || "").toLowerCase(); - if (low0 === "fx" && low1 === "tools" && low2 === "flow") { - hasLabsFlowPrefix = true; - prefixSegs.push(segs[i], segs[i + 1], segs[i + 2]); - i += 3; - } else if (low0 === "fx") { - prefixSegs.push(segs[i]); - i += 1; - } else if (low0 === "u" && /^\d+$/.test(segs[i + 1] || "")) { - pathAuthuser = segs[i + 1]; - prefixSegs.push(segs[i], segs[i + 1]); - i += 2; - } else if (low1 === "global" && !RESERVED_FLOW_SEGMENTS.has(low0)) { - prefixSegs.push(segs[i], segs[i + 1]); - i += 2; - } else { - break; - } - } - const prefix = prefixSegs.length > 0 ? `/${prefixSegs.join("/")}` : ""; - const route = - i >= segs.length ? "/" : `/${segs.slice(i).join("/").toLowerCase()}`; - return { prefix, route, hasLabsFlowPrefix, pathAuthuser }; -} - -/** Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. */ -export function isWorkspaceFlowRoute(route: string): boolean { - if (route === "/" || route === "/projects" || route === "/search" || route === "/changelogs") { - return true; - } - if (!route.startsWith("/project/")) return false; - const [projectId, ...sub] = route.slice("/project/".length).split("/"); - if (!projectId) return false; - if (sub.length === 0) return true; - if (sub.length === 1) { - return ["character", "tools", "create-tool", "trash", "chat"].includes(sub[0]); - } - if (sub.length === 2) { - return Boolean(sub[1]) && ["character", "scene", "edit", "tool", "collection", "chat"].includes(sub[0]); - } - if (sub.length === 3) { - return ( - (sub[0] === "collection" && Boolean(sub[1]) && sub[2] === "character") || - (sub[0] === "trash" && sub[1] === "collection" && Boolean(sub[2])) - ); - } - return false; -} - -/** Resolves the active `authuser` value from URL query, `/u/` prefix, or `WIZ_global_data`. */ -export function resolveFlowAuthuser( - search: string = location.search, - pathname: string = location.pathname, -): string | null { - const fromQuery = new URLSearchParams(search).get("authuser")?.trim(); - if (fromQuery) return fromQuery; - const { pathAuthuser } = splitFlowPath(pathname); - if (pathAuthuser) return pathAuthuser; - const fromWiz = window.WIZ_global_data?.QrtxK; - return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; -} - -/** Resolves the active `pageId` value from URL query or `WIZ_global_data.S06Grb`. */ -export function resolveFlowPageId(search: string = location.search): string | null { - const fromQuery = new URLSearchParams(search).get("pageId")?.trim(); - if (fromQuery) return fromQuery; - const fromWiz = window.WIZ_global_data?.S06Grb; - return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; -} - /** Builds the query parameters that Google Flow routes keep across transitions. */ function flowQueryParams(search: string = location.search): Record { const params: Record = { hl: "en" }; @@ -381,11 +278,11 @@ export function buildProjectUrl( } /** Host selectors searched first for Angular Ivy `LView` trees and root injectors. */ -const ANGULAR_SHELL_SELECTOR = +export const ANGULAR_SHELL_SELECTOR = "flow-project-shell, flow-project-page, flow-character-edit-page, flow-editor-dispatcher, flow-editor-page, flow-scene-builder, router-outlet, aisandbox-root, app-root, main, header"; /** Searches visible shell nodes, injectors, and captured LViews for a service matching `match`. */ -function findInAngular(match: (cand: unknown) => cand is T): T | null { +export function findInAngular(match: (cand: unknown) => cand is T): T | null { const ownMaps = (obj: object): Array> => { const maps: Array> = []; const named = readOwn(obj, "records"); @@ -517,135 +414,6 @@ export function findRouter(): AngularRouter | null { ); } -/** Returns `true` when `cand` is a non-DOM object holding a `find` function. */ -function hasQueryFind(cand: unknown): cand is AngularQueryCache { - return isPlainRecord(cand) && typeof readOwn(cand, "find") === "function"; -} - -/** Returns `true` when `cand` matches Angular's standalone `QueryCache` shape. */ -function isAngularQueryCache(cand: unknown): cand is AngularQueryCache { - return ( - hasQueryFind(cand) && - (typeof readOwn(cand, "getAll") === "function" || - readOwn(cand, "queries") instanceof Map) - ); -} - -/** Searches Angular injectors and LViews for the live `QueryClient` or `QueryCache`. */ -export function findQueryCache(): AngularQueryCache | null { - const clientOrCache = findInAngular( - (cand): cand is AngularQueryClient | AngularQueryCache => { - if (isAngularQueryCache(cand)) return true; - if (!cand || typeof cand !== "object" || cand instanceof Node) return false; - return hasQueryFind(readOwn(cand, "queryCache")); - }, - ); - if (!clientOrCache) return null; - const nested = readOwn(clientOrCache, "queryCache"); - return hasQueryFind(nested) ? nested : (clientOrCache as AngularQueryCache); -} - -/** Resolves Angular's `QueryCache`, capturing `ngLViewMap` once if numeric contexts are unbound. */ -export async function ensureAngularQueryCache(): Promise { - const direct = findQueryCache(); - if (direct) return direct; - if (!(runtimeState.ngLViewMap instanceof Map)) { - const hasNumericContext = Array.from( - document.querySelectorAll(ANGULAR_SHELL_SELECTOR), - ).some((el) => typeof readOwn(el, "__ngContext__") === "number"); - if (hasNumericContext) { - await withLViewMapCapture(async () => { - const targets = Array.from( - document.querySelectorAll( - "[mattooltip], [cdkoverlayorigin], button[aria-label], button, a[href]", - ), - ); - if (targets.length > 0) { - await hoverProbe(targets.slice(0, 8), 20); - } - }); - } - } - return findQueryCache(); -} - -/** Returns `true` when any DOM host on the page carries an Angular Ivy `__ngContext__`. */ -export function hasAngularContext(): boolean { - if (runtimeState.ngLViewMap instanceof Map && runtimeState.ngLViewMap.size > 0) { - return true; - } - for (const el of document.querySelectorAll(ANGULAR_SHELL_SELECTOR)) { - if (readOwn(el, "__ngContext__") !== undefined) return true; - } - const all = document.querySelectorAll("*"); - const limit = Math.min(all.length, 200); - for (let i = 0; i < limit; i += 1) { - if ("__ngContext__" in all[i]) return true; - } - return false; -} - -/** Returns `true` when Angular's `Router` has an active navigation in flight. */ -export function isRouterNavigating(): boolean { - const router = findRouter(); - if (!router) return false; - for (const key of ["currentNavigation", "getCurrentNavigation"]) { - const fn = readOwn(router, key); - if (typeof fn === "function") { - try { - if (fn.call(router) != null) return true; - } catch { - // Ignore router accessor errors. - } - } - } - return readOwn(router, "navigating") === true; -} - -/** Reads a cached query entry matching `queryKey` from `cache`. */ -export function readQueryCacheEntry( - cache: AngularQueryCache | null, - queryKey: readonly unknown[], -): AngularQueryEntry | undefined { - if (!cache) return undefined; - if (typeof cache.find === "function") { - try { - const hit = cache.find({ queryKey, exact: true }); - if (hit) return hit; - } catch { - // Fall through to hash or list lookup. - } - } - const hash = JSON.stringify(queryKey); - if (typeof cache.get === "function") { - try { - const hit = cache.get(hash); - if (hit) return hit; - } catch { - // Fall through to map or list lookup. - } - } - if (cache.queries instanceof Map) { - const hit = cache.queries.get(hash); - if (hit) return hit; - } - if (typeof cache.getAll === "function") { - try { - for (const entry of cache.getAll()) { - if ( - entry?.queryHash === hash || - JSON.stringify(entry?.queryKey) === hash - ) { - return entry; - } - } - } catch { - // Ignore concurrent cache iteration errors. - } - } - return undefined; -} - /** Maximum time to confirm scene creation and the initial clip load. */ const SCENE_CREATE_TIMEOUT_MS = 30_000; diff --git a/ts/angular_query.ts b/ts/angular_query.ts new file mode 100644 index 0000000..71e05a3 --- /dev/null +++ b/ts/angular_query.ts @@ -0,0 +1,154 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Read Angular QueryCache entries and router navigation state from live Ivy trees. + +import { + ANGULAR_SHELL_SELECTOR, + findInAngular, + findRouter, + isPlainRecord, + readOwn, + withLViewMapCapture, +} from "./angular"; +import { hoverProbe } from "./dom"; +import { runtimeState } from "./state"; +import type { + AngularQueryCache, + AngularQueryClient, + AngularQueryEntry, +} from "./types"; + +/** Returns `true` when `cand` is a non-DOM object holding a `find` function. */ +function hasQueryFind(cand: unknown): cand is AngularQueryCache { + return isPlainRecord(cand) && typeof readOwn(cand, "find") === "function"; +} + +/** Returns `true` when `cand` matches Angular's standalone `QueryCache` shape. */ +function isAngularQueryCache(cand: unknown): cand is AngularQueryCache { + return ( + hasQueryFind(cand) && + (typeof readOwn(cand, "getAll") === "function" || + readOwn(cand, "queries") instanceof Map) + ); +} + +/** Searches Angular injectors and LViews for the live `QueryClient` or `QueryCache`. */ +export function findQueryCache(): AngularQueryCache | null { + const clientOrCache = findInAngular( + (cand): cand is AngularQueryClient | AngularQueryCache => { + if (isAngularQueryCache(cand)) return true; + if (!cand || typeof cand !== "object" || cand instanceof Node) { + return false; + } + return hasQueryFind(readOwn(cand, "queryCache")); + }, + ); + if (!clientOrCache) return null; + const nested = readOwn(clientOrCache, "queryCache"); + return hasQueryFind(nested) ? nested : (clientOrCache as AngularQueryCache); +} + +/** Resolves Angular's `QueryCache`, capturing `ngLViewMap` once if numeric contexts are unbound. */ +export async function ensureAngularQueryCache(): Promise { + const direct = findQueryCache(); + if (direct) return direct; + if (!(runtimeState.ngLViewMap instanceof Map)) { + const hasNumericContext = Array.from( + document.querySelectorAll(ANGULAR_SHELL_SELECTOR), + ).some((el) => typeof readOwn(el, "__ngContext__") === "number"); + if (hasNumericContext) { + await withLViewMapCapture(async () => { + const targets = Array.from( + document.querySelectorAll( + "[mattooltip], [cdkoverlayorigin], button[aria-label], button, a[href]", + ), + ); + if (targets.length > 0) { + await hoverProbe(targets.slice(0, 8), 20); + } + }); + } + } + return findQueryCache(); +} + +/** Returns `true` when any DOM host on the page carries an Angular Ivy `__ngContext__`. */ +export function hasAngularContext(): boolean { + if ( + runtimeState.ngLViewMap instanceof Map && + runtimeState.ngLViewMap.size > 0 + ) { + return true; + } + for (const el of document.querySelectorAll(ANGULAR_SHELL_SELECTOR)) { + if (readOwn(el, "__ngContext__") !== undefined) return true; + } + const all = document.querySelectorAll("*"); + const limit = Math.min(all.length, 200); + for (let i = 0; i < limit; i += 1) { + if ("__ngContext__" in all[i]) return true; + } + return false; +} + +/** Returns `true` when Angular's `Router` has an active navigation in flight. */ +export function isRouterNavigating(): boolean { + const router = findRouter(); + if (!router) return false; + for (const key of ["currentNavigation", "getCurrentNavigation"]) { + const fn = readOwn(router, key); + if (typeof fn === "function") { + try { + if (fn.call(router) != null) return true; + } catch { + // Ignore router accessor errors. + } + } + } + return readOwn(router, "navigating") === true; +} + +/** Reads a cached query entry matching `queryKey` from `cache`. */ +export function readQueryCacheEntry( + cache: AngularQueryCache | null, + queryKey: readonly unknown[], +): AngularQueryEntry | undefined { + if (!cache) return undefined; + if (typeof cache.find === "function") { + try { + const hit = cache.find({ queryKey, exact: true }); + if (hit) return hit; + } catch { + // Fall through to hash or list lookup. + } + } + const hash = JSON.stringify(queryKey); + if (typeof cache.get === "function") { + try { + const hit = cache.get(hash); + if (hit) return hit; + } catch { + // Fall through to map or list lookup. + } + } + if (cache.queries instanceof Map) { + const hit = cache.queries.get(hash); + if (hit) return hit; + } + if (typeof cache.getAll === "function") { + try { + for (const entry of cache.getAll()) { + if ( + entry?.queryHash === hash || + JSON.stringify(entry?.queryKey) === hash + ) { + return entry; + } + } + } catch { + // Ignore concurrent cache iteration errors. + } + } + return undefined; +} diff --git a/ts/check_auth.ts b/ts/check_auth.ts index e21f652..7ea5f94 100644 --- a/ts/check_auth.ts +++ b/ts/check_auth.ts @@ -3,17 +3,18 @@ // Verify Google Flow workspace access with route allowlists, Angular QueryCache state, and RPC fallback. +import { readOwn } from "./angular"; import { ensureAngularQueryCache, hasAngularContext, isRouterNavigating, - isWorkspaceFlowRoute, - readOwn, readQueryCacheEntry, +} from "./angular_query"; +import { + isWorkspaceLocation, resolveFlowAuthuser, resolveFlowPageId, - splitFlowPath, -} from "./angular"; +} from "./flow_route"; import type { AngularQueryEntry, AuthCheckResult } from "./types"; /** Read-only `FLOW_APP_CONFIG` RPC identifier in the Flow workspace route guard. */ @@ -53,20 +54,6 @@ const PROBE_TIMEOUT_MS = 5000; 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 `hostname` and `pathname` target an allowlisted Flow workspace route. */ -export function isWorkspaceLocation(hostname: string, pathname: string): boolean { - const host = (hostname || "").toLowerCase(); - const onLabsHost = host === "labs.google" || host.endsWith(".labs.google"); - if (host !== "flow.google.com" && !onLabsHost) { - return false; - } - const stripped = splitFlowPath(pathname || "/"); - if (onLabsHost && !stripped.hasLabsFlowPrefix) { - return false; - } - return isWorkspaceFlowRoute(stripped.route); -} - /** Builds an `AuthCheckResult` record from the active document metadata. */ function authResult( signedIn: boolean, @@ -186,10 +173,10 @@ function evaluateAppConfigPayload( return "ok"; } -/** Evaluates `CHECK_TOOL_AVAILABILITY` (`KV2T2d`) field `1` (`Cla()`) codes `4`..`8`. */ +/** Evaluates `CHECK_TOOL_AVAILABILITY` (`KV2T2d`) field `1` (`Cla()`) for verified age restriction (`7`). */ function evaluateToolAvailabilityPayload( payload: unknown, -): "ok" | "age_restricted" | "unavailable" { +): "ok" | "age_restricted" { if (!payload || typeof payload !== "object") { return "ok"; } @@ -211,9 +198,6 @@ function evaluateToolAvailabilityPayload( if (code === 7) { return "age_restricted"; } - if (code === 4 || code === 5 || code === 6 || code === 8) { - return "unavailable"; - } return "ok"; } @@ -313,7 +297,10 @@ async function checkAngularQueryEligibility(): Promise { continue; } - if (appData !== undefined && toolData !== undefined) { + if ( + appData !== undefined && + (toolData !== undefined || toolQuery?.state?.status === "error") + ) { if (evaluateAppConfigPayload(appData) !== "ok") { return null; } @@ -362,13 +349,16 @@ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { if (rpcErr[0] === 16) { return authResult(false, false, true, status, "rpc_unauthenticated"); } - return authResult( - false, - true, - false, - status, - `rpc_error_${rpcErr[0]}`, - ); + if (entry[1] === APP_CONFIG_RPC_ID) { + return authResult( + false, + true, + false, + status, + `rpc_error_${rpcErr[0]}`, + ); + } + continue; } if (typeof entry[2] !== "string") { continue; diff --git a/ts/flow_route.ts b/ts/flow_route.ts new file mode 100644 index 0000000..f6a6d78 --- /dev/null +++ b/ts/flow_route.ts @@ -0,0 +1,154 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Parse Google Flow URL prefixes, workspace route allowlists, and request identifiers. + +/** Parsed prefix and normalized route details of a Flow pathname. */ +export interface StrippedFlowPath { + /** Active prefix starting with `/` when present, keeping original case. */ + prefix: string; + /** Normalized lowercase route starting with `/` without trailing slashes. */ + route: string; + /** True when `/fx/tools/flow` appears among the stripped prefixes. */ + hasLabsFlowPrefix: boolean; + /** Account index extracted from `/u/` when present. */ + pathAuthuser: string | null; +} + +/** Reserved Flow top-level route names that cannot act as `` before `/global`. */ +const RESERVED_FLOW_SEGMENTS = new Set([ + "project", + "projects", + "search", + "changelogs", + "about", + "shared", + "flow", + "tools", + "fx", + "u", + "unsupported-country", + "unsupported-browser", + "unavailable", + "age-restricted", + "privacy", + "credits-terms", + "academy", + "404", + "login", + "debug", +]); + +/** Strips `/fx/tools/flow`, `/fx`, `/u/`, and `//global` prefixes from `pathname`. */ +export function splitFlowPath( + pathname: string = location.pathname, +): StrippedFlowPath { + const cleanPath = (pathname || "/").split(/[?#]/)[0] || "/"; + const segs = cleanPath.split("/").filter(Boolean); + const prefixSegs: string[] = []; + let hasLabsFlowPrefix = false; + let pathAuthuser: string | null = null; + let i = 0; + while (i < segs.length) { + const low0 = segs[i].toLowerCase(); + const low1 = (segs[i + 1] || "").toLowerCase(); + const low2 = (segs[i + 2] || "").toLowerCase(); + if (low0 === "fx" && low1 === "tools" && low2 === "flow") { + hasLabsFlowPrefix = true; + prefixSegs.push(segs[i], segs[i + 1], segs[i + 2]); + i += 3; + } else if (low0 === "fx") { + prefixSegs.push(segs[i]); + i += 1; + } else if (low0 === "u" && /^\d+$/.test(segs[i + 1] || "")) { + pathAuthuser = segs[i + 1]; + prefixSegs.push(segs[i], segs[i + 1]); + i += 2; + } else if (low1 === "global" && !RESERVED_FLOW_SEGMENTS.has(low0)) { + prefixSegs.push(segs[i], segs[i + 1]); + i += 2; + } else { + break; + } + } + const prefix = prefixSegs.length > 0 ? `/${prefixSegs.join("/")}` : ""; + const route = + i >= segs.length ? "/" : `/${segs.slice(i).join("/").toLowerCase()}`; + return { prefix, route, hasLabsFlowPrefix, pathAuthuser }; +} + +/** Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. */ +export function isWorkspaceFlowRoute(route: string): boolean { + if ( + route === "/" || + route === "/projects" || + route === "/search" || + route === "/changelogs" + ) { + return true; + } + if (!route.startsWith("/project/")) return false; + const [projectId, ...sub] = route.slice("/project/".length).split("/"); + if (!projectId) return false; + if (sub.length === 0) return true; + if (sub.length === 1) { + return ["character", "tools", "create-tool", "trash", "chat"].includes( + sub[0], + ); + } + if (sub.length === 2) { + return ( + Boolean(sub[1]) && + ["character", "scene", "edit", "tool", "collection", "chat"].includes( + sub[0], + ) + ); + } + if (sub.length === 3) { + return ( + (sub[0] === "collection" && Boolean(sub[1]) && sub[2] === "character") || + (sub[0] === "trash" && sub[1] === "collection" && Boolean(sub[2])) + ); + } + return false; +} + +/** Returns `true` when `hostname` and `pathname` target an allowlisted Flow workspace route. */ +export function isWorkspaceLocation( + hostname: string, + pathname: string, +): boolean { + const host = (hostname || "").toLowerCase(); + const onLabsHost = host === "labs.google" || host.endsWith(".labs.google"); + if (host !== "flow.google.com" && !onLabsHost) { + return false; + } + const stripped = splitFlowPath(pathname || "/"); + if (onLabsHost && !stripped.hasLabsFlowPrefix) { + return false; + } + return isWorkspaceFlowRoute(stripped.route); +} + +/** Resolves the active `authuser` value from URL query, `/u/` prefix, or `WIZ_global_data`. */ +export function resolveFlowAuthuser( + search: string = location.search, + pathname: string = location.pathname, +): string | null { + const fromQuery = new URLSearchParams(search).get("authuser")?.trim(); + if (fromQuery) return fromQuery; + const { pathAuthuser } = splitFlowPath(pathname); + if (pathAuthuser) return pathAuthuser; + const fromWiz = window.WIZ_global_data?.QrtxK; + return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; +} + +/** Resolves the active `pageId` value from URL query or `WIZ_global_data.S06Grb`. */ +export function resolveFlowPageId( + search: string = location.search, +): string | null { + const fromQuery = new URLSearchParams(search).get("pageId")?.trim(); + if (fromQuery) return fromQuery; + const fromWiz = window.WIZ_global_data?.S06Grb; + return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; +} From f60b5e920858151e3613ae721cefe95f232ba6f7 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:26:50 +0000 Subject: [PATCH 3/3] fix(flow): parse prefixed routes with denylists and refine login - Keep the non-workspace route denylist in flow_url and flow_route - Strip /fx, /fx/tools/flow, /u/, and //global prefixes - Parse full URLs in project_id_from_url and is_project_subroute_url - Remove QueryCache, KV2T2d, minified names, and runtime injection - Forward URL authuser on the read-only cPZSdc workspace probe - Report unsupported_country and age_restricted errors on promotion --- src/auth.rs | 136 +++++++++--------- src/engine.rs | 8 -- src/flow_url.rs | 86 ++++++++---- src/project_route.rs | 9 +- ts/angular.ts | 159 ++++++++++----------- ts/angular_query.ts | 154 -------------------- ts/check_auth.ts | 327 ++++--------------------------------------- ts/flow_route.ts | 91 ++++++------ ts/types.ts | 46 ------ 9 files changed, 278 insertions(+), 738 deletions(-) delete mode 100644 ts/angular_query.ts diff --git a/src/auth.rs b/src/auth.rs index b0ba8cd..1e0000f 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -17,8 +17,8 @@ use crate::config::{ FLOW_SSO_URL, FLOW_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::flow_url::{is_about_landing_url, is_signed_in_flow_url}; +use crate::engine::{ChromeEngine, ENGINE_NAME, LoginPollStatus}; +use crate::flow_url::{flow_ineligible_route_reason, is_about_landing_url, is_signed_in_flow_url}; /// Maximum number of `/about` passive SSO redirect attempts during session promotion. const MAX_ABOUT_SSO_RETRIES: usize = 2; @@ -40,9 +40,6 @@ pub(crate) struct LoginParams { /// Evaluates `checkAuth` once in the active page, retrying brief context resets during navigation. async fn eval_check_auth_once(engine: &ChromeEngine) -> Option { - let _ = engine - .bind_angular_views("aisandbox-root, app-root, router-outlet") - .await; for _ in 0..3 { match engine.call_flow_async("checkAuth", json!([])).await { Ok(v) => return Some(v), @@ -172,6 +169,19 @@ async fn ensure_flow_session_url(engine: &ChromeEngine) { } } +/// Builds an error when Google Flow blocks the account by country or age policy. +fn ineligible_account_error(reason: &str) -> Option { + match reason { + "unsupported_country" => Some(anyhow::anyhow!( + "Google Flow is not available in the country or region of this Google account (unsupported_country)." + )), + "age_restricted" => Some(anyhow::anyhow!( + "Google Flow is age-restricted for this Google account (age_restricted)." + )), + _ => None, + } +} + /// 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?; @@ -181,6 +191,12 @@ async fn finalize_promoted_login(engine: &ChromeEngine, start_url: &str) -> Resu if is_interactive_signin_url(&cur) { break; } + if let Some(reason) = flow_ineligible_route_reason(&cur) + && let Some(err) = ineligible_account_error(reason) + { + engine.shutdown().await; + return Err(err); + } if is_about_landing_url(&cur) { if about_retries >= MAX_ABOUT_SSO_RETRIES { break; @@ -208,11 +224,11 @@ async fn finalize_promoted_login(engine: &ChromeEngine, start_url: &str) -> Resu ))); } } - if matches!( - auth.get("reason").and_then(Value::as_str), - Some("unsupported_country" | "age_restricted") - ) { - break; + if let Some(reason) = auth.get("reason").and_then(Value::as_str) + && let Some(err) = ineligible_account_error(reason) + { + engine.shutdown().await; + return Err(err); } } } @@ -222,6 +238,43 @@ async fn finalize_promoted_login(engine: &ChromeEngine, start_url: &str) -> Resu Ok(None) } +/// Settles an active `LoginChrome` session, promotes it into CDP Chrome, and verifies Flow access. +async fn promote_ready_login_chrome( + engine: &ChromeEngine, + st: LoginPollStatus, + fallback_flow_url: Option<&str>, +) -> Result { + let exited = st.exited; + let mut target_flow_url = st + .flow_url + .or_else(|| fallback_flow_url.map(str::to_string)); + if st.has_google_auth_cookies && !exited { + tokio::time::sleep(Duration::from_secs(4)).await; + if let Some(after_settle) = engine.poll_login_chrome().await? { + if let Some(rejected) = after_settle.rejected_url { + engine.shutdown().await; + anyhow::bail!( + "Google Accounts rejected sign-in in this browser session (URL: {}).", + rejected + ); + } + if after_settle.flow_url.is_some() { + target_flow_url = after_settle.flow_url; + } + } + } + let target_url = target_flow_url.as_deref().unwrap_or(FLOW_URL); + if let Some(res) = finalize_promoted_login(engine, target_url).await? { + return Ok(res); + } + if 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." + ); +} + /// Signs in to Google Flow using standard Chrome and promotes the session into background CDP Chrome. async fn login_with_chrome( engine: &ChromeEngine, @@ -243,32 +296,7 @@ async fn login_with_chrome( ); } if st.exited || st.has_google_auth_cookies { - let mut target_flow_url = st.flow_url; - if st.has_google_auth_cookies && !st.exited { - tokio::time::sleep(Duration::from_secs(4)).await; - if let Some(after_settle) = engine.poll_login_chrome().await? { - if let Some(rejected) = after_settle.rejected_url { - engine.shutdown().await; - anyhow::bail!( - "Google Accounts rejected sign-in in this browser session (URL: {}).", - rejected - ); - } - if after_settle.flow_url.is_some() { - target_flow_url = after_settle.flow_url; - } - } - } - let target_url = target_flow_url.as_deref().unwrap_or(FLOW_URL); - if let Some(res) = finalize_promoted_login(engine, target_url).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." - ); + return promote_ready_login_chrome(engine, st, None).await; } } } else { @@ -323,38 +351,18 @@ async fn login_with_chrome( } if st.exited || st.has_google_auth_cookies { - let mut target_flow_url = st.flow_url.or_else(|| last_flow_url.clone()); - if st.has_google_auth_cookies && !st.exited { - tokio::time::sleep(Duration::from_secs(4)).await; - if let Some(after_settle) = engine.poll_login_chrome().await? { - if let Some(rejected) = after_settle.rejected_url { - engine.shutdown().await; - anyhow::bail!( - "Google Accounts rejected sign-in in this browser session (URL: {}).", - rejected - ); - } - if after_settle.flow_url.is_some() { - target_flow_url = after_settle.flow_url; - } - } - } - let target_url = target_flow_url.as_deref().unwrap_or(FLOW_URL); - if let Some(res) = finalize_promoted_login(engine, target_url).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." - ); + return promote_ready_login_chrome(engine, st, last_flow_url.as_deref()).await; } if Instant::now() >= deadline { let target_url = last_flow_url.as_deref().unwrap_or(FLOW_URL); - if let Ok(Some(res)) = finalize_promoted_login(engine, target_url).await { - return Ok(res); + match finalize_promoted_login(engine, target_url).await { + Ok(Some(res)) => return Ok(res), + Ok(None) => {} + Err(err) => { + engine.shutdown().await; + return Err(err); + } } engine.shutdown().await; anyhow::bail!( diff --git a/src/engine.rs b/src/engine.rs index 3dd56c6..77063cc 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -872,14 +872,6 @@ async fn bind_browser_instances( ) -> Result> { let group = format!("flow-bind-{}", uuid::Uuid::new_v4()); let result = async { - let installed = eval_runtime(cdp, "Boolean(window.__flowMcp)", false, Duration::from_secs(5)) - .await - .ok() - .and_then(|v| v.as_bool()) - .unwrap_or(false); - if !installed { - eval_runtime(cdp, FLOW_RUNTIME_JS, false, Duration::from_secs(30)).await?; - } let prototype = cdp .call( "Runtime.evaluate", diff --git a/src/flow_url.rs b/src/flow_url.rs index 30d2a9b..1f9035d 100644 --- a/src/flow_url.rs +++ b/src/flow_url.rs @@ -5,6 +5,31 @@ use url::Url; +/// Non-workspace Flow routes matched by exact segment or segment prefix after prefix stripping. +const NON_WORKSPACE_SEGMENT_PREFIXES: [&str; 21] = [ + "/unsupported-country", + "/unsupported-browser", + "/unavailable", + "/age-restricted", + "/privacy", + "/credits-terms", + "/about", + "/flow/about", + "/academy", + "/shared/tool", + "/shared", + "/flow/shared/tool", + "/flow/shared", + "/tools/flow/shared/tool", + "/tools/flow/shared", + "/404", + "/login", + "/tools/flow/about", + "/tools/flow/login", + "/api", + "/_", +]; + /// Parsed components of a Google Flow URL path after stripping active prefixes. pub(crate) struct StrippedFlowPath { /// Active route prefix starting with `/` when present, keeping original case. @@ -64,6 +89,8 @@ fn is_reserved_flow_segment(seg: &str) -> bool { | "404" | "login" | "debug" + | "api" + | "_" ) } @@ -115,45 +142,29 @@ pub(crate) fn split_flow_path(path: &str) -> StrippedFlowPath { } } -/// Returns `true` when lowercase segments after `/project/` match a recognized Flow project subroute. -fn is_project_subroute_segments(segs: &[&str]) -> bool { - match segs { - ["character" | "tools" | "create-tool" | "trash" | "chat"] => true, - [ - "character" | "scene" | "edit" | "tool" | "collection" | "chat", - id, - ] => !id.is_empty(), - ["collection", id, "character"] | ["trash", "collection", id] => !id.is_empty(), - _ => false, - } -} - /// Returns `true` when lowercase segments after `/project/` match a non-grid editor or view subroute. pub(crate) fn is_non_grid_project_subroute_segments(segs: &[&str]) -> bool { match segs { - ["character" | "tools" | "create-tool" | "trash" | "chat"] => true, - ["character" | "scene" | "edit" | "tool" | "chat", id] => !id.is_empty(), - ["collection", id, "character"] | ["trash", "collection", id] => !id.is_empty(), + [ + "character" | "scene" | "edit" | "chat" | "tool" | "tools" | "create-tool" | "trash", + .., + ] => true, + ["collection", cid, "character", ..] => !cid.is_empty(), _ => false, } } -/// Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. +/// Returns `true` when a prefix-stripped lowercase `route` is outside the Flow non-workspace denylist. pub(crate) fn is_workspace_flow_route(route: &str) -> bool { - if matches!(route, "/" | "/projects" | "/search" | "/changelogs") { - return true; - } - let Some(rest) = route.strip_prefix("/project/") else { - return false; - }; - let segs: Vec<&str> = rest.split('/').collect(); - let Some((&project_id, sub)) = segs.split_first() else { + if route == "/flow" { return false; - }; - !project_id.is_empty() && (sub.is_empty() || is_project_subroute_segments(sub)) + } + !NON_WORKSPACE_SEGMENT_PREFIXES + .iter() + .any(|prefix| has_segment_prefix(route, prefix)) } -/// Returns `true` when `parsed` points to a Google Flow workspace host and allowlisted route. +/// Returns `true` when `parsed` points to a Google Flow workspace host and non-denylisted route. pub(crate) fn is_signed_in_parsed_flow_url(parsed: &Url) -> bool { if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { return false; @@ -167,7 +178,7 @@ pub(crate) fn is_signed_in_parsed_flow_url(parsed: &Url) -> bool { is_workspace_flow_route(&stripped.route) } -/// Returns `true` when `raw` points to a Google Flow workspace host and allowlisted route. +/// Returns `true` when `raw` points to a Google Flow workspace host and non-denylisted route. pub(crate) fn is_signed_in_flow_url(raw: &str) -> bool { Url::parse(raw).is_ok_and(|parsed| is_signed_in_parsed_flow_url(&parsed)) } @@ -187,3 +198,20 @@ pub(crate) fn is_about_landing_url(url: &str) -> bool { || has_segment_prefix(rel, "/flow/about") || has_segment_prefix(rel, "/tools/flow/about") } + +/// Returns the eligibility failure code when `raw` points to `/unsupported-country` or `/age-restricted`. +pub(crate) fn flow_ineligible_route_reason(raw: &str) -> Option<&'static str> { + let parsed = Url::parse(raw).ok()?; + if !matches!(parsed.scheme(), "http" | "https") || !is_flow_origin_host(parsed.host_str()) { + return None; + } + let stripped = split_flow_path(parsed.path()); + let rel = stripped.route.as_str(); + if has_segment_prefix(rel, "/unsupported-country") { + Some("unsupported_country") + } else if has_segment_prefix(rel, "/age-restricted") { + Some("age_restricted") + } else { + None + } +} diff --git a/src/project_route.rs b/src/project_route.rs index c48c3cc..a912574 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -68,7 +68,14 @@ pub(crate) fn is_project_subroute_url(url: &str) -> bool { /// Extracts the active route prefix from a Flow URL path. fn flow_route_prefix(path: &str) -> String { - split_flow_path(path).prefix + let stripped = split_flow_path(path); + if !stripped.prefix.is_empty() { + return stripped.prefix; + } + if let Some((before, _)) = path.split_once("/project/") { + return before.trim_end_matches('/').to_string(); + } + String::new() } /// Builds a Google Flow `/project/` or subroute URL with active prefixes, `hl=en`, and `authuser`. diff --git a/ts/angular.ts b/ts/angular.ts index de6672c..4614b49 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -14,12 +14,7 @@ import { import { splitFlowPath } from "./flow_route"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; import { runtimeState } from "./state"; -import type { - AngularRouter, - FlowStoreHandle, - FlowTile, - NgLView, -} from "./types"; +import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; /** Object with optional Angular Ivy `__ngContext__` or internal `lView` links. */ export interface NgContextCarrier { @@ -39,20 +34,6 @@ export function readOwn(obj: unknown, key: string): unknown { } } -/** Returns `true` when `val` is a non-null, non-array, non-`Map`, non-DOM object. */ -export function isPlainRecord(val: unknown): val is Record { - return Boolean( - val && - typeof val === "object" && - val !== window && - val !== document && - val !== window.navigation && - !(val instanceof Node) && - !Array.isArray(val) && - !(val instanceof Map), - ); -} - /** Returns `lv` if `lv` is a live Angular LView whose host node remains connected. */ export function isLiveLView(lv: unknown): lv is NgLView { return Array.isArray(lv) && (!(lv[0] instanceof Node) || lv[0].isConnected); @@ -204,6 +185,10 @@ function activeProjectPrefix(): string { const path = location.pathname || ""; const { prefix } = splitFlowPath(path); if (prefix) return prefix; + 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 { @@ -225,15 +210,32 @@ function routerQueryParamsKey(router: AngularRouter): string { const candidateKeys = Array.from(new Set([...Object.keys(router), "urlSerializer"])); for (const key of candidateKeys) { const serializer = readOwn(router, key); - if (!isPlainRecord(serializer)) continue; + if ( + !serializer || + typeof serializer !== "object" || + serializer === window || + serializer === document || + serializer instanceof Node + ) { + continue; + } const parse = readOwn(serializer, "parse"); if (typeof parse !== "function") continue; try { - const tree = (parse as (url: string) => unknown).call(serializer, "/?__flow_qp=1"); - if (!isPlainRecord(tree)) continue; - for (const treeKey of new Set([...Object.keys(tree), "queryParams"])) { + const tree = (parse as (url: string) => unknown).call( + serializer, + "/?__flow_qp=1", + ); + if (!tree || typeof tree !== "object") continue; + const treeKeys = Array.from(new Set([...Object.keys(tree), "queryParams"])); + for (const treeKey of treeKeys) { const qp = readOwn(tree, treeKey); - if (isPlainRecord(qp) && readOwn(qp, "__flow_qp") === "1") { + if ( + qp && + typeof qp === "object" && + !Array.isArray(qp) && + readOwn(qp, "__flow_qp") === "1" + ) { routerQueryParamKeys.set(router, treeKey); return treeKey; } @@ -277,12 +279,23 @@ export function buildProjectUrl( return url.href; } -/** Host selectors searched first for Angular Ivy `LView` trees and root injectors. */ -export const ANGULAR_SHELL_SELECTOR = - "flow-project-shell, flow-project-page, flow-character-edit-page, flow-editor-dispatcher, flow-editor-page, flow-scene-builder, router-outlet, aisandbox-root, app-root, main, header"; +/** Searches visible shell nodes and captured LViews for the active Angular `Router` instance. */ +export function findRouter(): AngularRouter | null { + const isRouter = (cand: unknown): cand is AngularRouter => + Boolean( + cand && + typeof cand === "object" && + cand !== window && + cand !== document && + cand !== window.navigation && + !(cand instanceof Node) && + !Array.isArray(cand) && + !(cand instanceof Map) && + typeof (cand as Partial).navigate === "function" && + "location" in cand && + "options" in cand, + ); -/** Searches visible shell nodes, injectors, and captured LViews for a service matching `match`. */ -export function findInAngular(match: (cand: unknown) => cand is T): T | null { const ownMaps = (obj: object): Array> => { const maps: Array> = []; const named = readOwn(obj, "records"); @@ -300,49 +313,25 @@ export function findInAngular(match: (cand: unknown) => cand is T): T | null const seenObjs = new Set(); const seenInjectors = new Set(); - const inspectInjector = (injRoot: object): T | null => { + const inspectInjector = (injRoot: object): AngularRouter | null => { let inj: object | null = injRoot; - for (let d = 0; d < 10 && inj && typeof inj === "object"; d += 1) { + for (let d = 0; d < 6 && inj && typeof inj === "object"; d += 1) { if (seenInjectors.has(inj)) break; seenInjectors.add(inj); for (const records of ownMaps(inj)) { for (const rec of records.values()) { - if (match(rec)) return rec; + if (isRouter(rec)) return rec; const recVal = readOwn(rec, "value"); - if (match(recVal)) return recVal; - if (isPlainRecord(recVal) && !seenObjs.has(recVal)) { - seenObjs.add(recVal); - const rKeys = Object.keys(recVal); - for (let i = 0; i < rKeys.length && i < 16; i += 1) { - const nested = readOwn(recVal, rKeys[i]); - if (match(nested)) return nested; - } - } + if (isRouter(recVal)) return recVal; } } const parent = readOwn(inj, "parent"); - if (parent && typeof parent === "object" && !(parent instanceof Node)) { - inj = parent; - continue; - } - let nextInj: object | null = null; - for (const key of Object.keys(inj)) { - const candParent = readOwn(inj, key); - if ( - isPlainRecord(candParent) && - !seenInjectors.has(candParent) && - ownMaps(candParent).length > 0 - ) { - nextInj = candParent; - break; - } - } - inj = nextInj; + inj = parent && typeof parent === "object" ? parent : null; } return null; }; - const inspectLViewTree = (startLv: NgLView | null): T | null => { + const inspectLViewTree = (startLv: NgLView | null): AngularRouter | null => { if (!Array.isArray(startLv)) return null; const queue: Array<[NgLView, number]> = [[startLv, 0]]; while (queue.length > 0) { @@ -355,19 +344,26 @@ export function findInAngular(match: (cand: unknown) => cand is T): T | null if (!slot || typeof slot !== "object" || slot instanceof Node) { continue; } - if (match(slot)) return slot; + if (isRouter(slot)) return slot; if ("parent" in slot || ownMaps(slot).length > 0) { const fromInj = inspectInjector(slot); if (fromInj) return fromInj; } if (seenObjs.has(slot)) continue; seenObjs.add(slot); - if (isPlainRecord(slot)) { + if (!Array.isArray(slot) && !(slot instanceof Map)) { const keys = Object.keys(slot); for (let i = 0; i < keys.length && i < 30; i += 1) { const val = readOwn(slot, keys[i]); - if (match(val)) return val; - if (isPlainRecord(val) && ("parent" in val || ownMaps(val).length > 0)) { + if (isRouter(val)) return val; + if ( + val && + typeof val === "object" && + !(val instanceof Node) && + !Array.isArray(val) && + !(val instanceof Map) && + ("parent" in val || ownMaps(val).length > 0) + ) { const fromNested = inspectInjector(val); if (fromNested) return fromNested; } @@ -382,7 +378,10 @@ export function findInAngular(match: (cand: unknown) => cand is T): T | null return null; }; - for (const el of document.querySelectorAll(ANGULAR_SHELL_SELECTOR)) { + const els = document.querySelectorAll( + "flow-project-shell, flow-project-page, flow-character-edit-page, flow-editor-dispatcher, flow-editor-page, flow-scene-builder, router-outlet, aisandbox-root, app-root, main", + ); + for (const el of els) { const hit = inspectLViewTree(resolveLView(el)); if (hit) return hit; } @@ -392,28 +391,9 @@ export function findInAngular(match: (cand: unknown) => cand is T): T | null if (hit) return hit; } } - const all = document.querySelectorAll("*"); - const limit = Math.min(all.length, 200); - for (let i = 0; i < limit; i += 1) { - if ("__ngContext__" in all[i]) { - const hit = inspectLViewTree(resolveLView(all[i])); - if (hit) return hit; - } - } return null; } -/** Searches visible shell nodes and captured LViews for the active Angular `Router` instance. */ -export function findRouter(): AngularRouter | null { - return findInAngular( - (cand): cand is AngularRouter => - isPlainRecord(cand) && - typeof (cand as Partial).navigate === "function" && - "location" in cand && - "options" in cand, - ); -} - /** Maximum time to confirm scene creation and the initial clip load. */ const SCENE_CREATE_TIMEOUT_MS = 30_000; @@ -582,7 +562,16 @@ function scanLViewTooltip(lv: NgLView, hostNode: Element, seen = new Set { - if (isAngularQueryCache(cand)) return true; - if (!cand || typeof cand !== "object" || cand instanceof Node) { - return false; - } - return hasQueryFind(readOwn(cand, "queryCache")); - }, - ); - if (!clientOrCache) return null; - const nested = readOwn(clientOrCache, "queryCache"); - return hasQueryFind(nested) ? nested : (clientOrCache as AngularQueryCache); -} - -/** Resolves Angular's `QueryCache`, capturing `ngLViewMap` once if numeric contexts are unbound. */ -export async function ensureAngularQueryCache(): Promise { - const direct = findQueryCache(); - if (direct) return direct; - if (!(runtimeState.ngLViewMap instanceof Map)) { - const hasNumericContext = Array.from( - document.querySelectorAll(ANGULAR_SHELL_SELECTOR), - ).some((el) => typeof readOwn(el, "__ngContext__") === "number"); - if (hasNumericContext) { - await withLViewMapCapture(async () => { - const targets = Array.from( - document.querySelectorAll( - "[mattooltip], [cdkoverlayorigin], button[aria-label], button, a[href]", - ), - ); - if (targets.length > 0) { - await hoverProbe(targets.slice(0, 8), 20); - } - }); - } - } - return findQueryCache(); -} - -/** Returns `true` when any DOM host on the page carries an Angular Ivy `__ngContext__`. */ -export function hasAngularContext(): boolean { - if ( - runtimeState.ngLViewMap instanceof Map && - runtimeState.ngLViewMap.size > 0 - ) { - return true; - } - for (const el of document.querySelectorAll(ANGULAR_SHELL_SELECTOR)) { - if (readOwn(el, "__ngContext__") !== undefined) return true; - } - const all = document.querySelectorAll("*"); - const limit = Math.min(all.length, 200); - for (let i = 0; i < limit; i += 1) { - if ("__ngContext__" in all[i]) return true; - } - return false; -} - -/** Returns `true` when Angular's `Router` has an active navigation in flight. */ -export function isRouterNavigating(): boolean { - const router = findRouter(); - if (!router) return false; - for (const key of ["currentNavigation", "getCurrentNavigation"]) { - const fn = readOwn(router, key); - if (typeof fn === "function") { - try { - if (fn.call(router) != null) return true; - } catch { - // Ignore router accessor errors. - } - } - } - return readOwn(router, "navigating") === true; -} - -/** Reads a cached query entry matching `queryKey` from `cache`. */ -export function readQueryCacheEntry( - cache: AngularQueryCache | null, - queryKey: readonly unknown[], -): AngularQueryEntry | undefined { - if (!cache) return undefined; - if (typeof cache.find === "function") { - try { - const hit = cache.find({ queryKey, exact: true }); - if (hit) return hit; - } catch { - // Fall through to hash or list lookup. - } - } - const hash = JSON.stringify(queryKey); - if (typeof cache.get === "function") { - try { - const hit = cache.get(hash); - if (hit) return hit; - } catch { - // Fall through to map or list lookup. - } - } - if (cache.queries instanceof Map) { - const hit = cache.queries.get(hash); - if (hit) return hit; - } - if (typeof cache.getAll === "function") { - try { - for (const entry of cache.getAll()) { - if ( - entry?.queryHash === hash || - JSON.stringify(entry?.queryKey) === hash - ) { - return entry; - } - } - } catch { - // Ignore concurrent cache iteration errors. - } - } - return undefined; -} diff --git a/ts/check_auth.ts b/ts/check_auth.ts index 7ea5f94..d842474 100644 --- a/ts/check_auth.ts +++ b/ts/check_auth.ts @@ -1,52 +1,20 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Verify Google Flow workspace access with route allowlists, Angular QueryCache state, and RPC fallback. +// Verify Google Flow workspace access with route guards, Wiz tokens, and a read-only probe. -import { readOwn } from "./angular"; -import { - ensureAngularQueryCache, - hasAngularContext, - isRouterNavigating, - readQueryCacheEntry, -} from "./angular_query"; -import { - isWorkspaceLocation, - resolveFlowAuthuser, - resolveFlowPageId, -} from "./flow_route"; -import type { AngularQueryEntry, AuthCheckResult } from "./types"; +import { isWorkspaceLocation, resolveFlowAuthuser } from "./flow_route"; +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"; - -/** Tool identifier passed to `CHECK_TOOL_AVAILABILITY` by the Flow workspace route guard. */ -const FLOW_TOOL_AVAILABILITY_ID = 22; - -/** Unminified `QueryCache` key for `FLOW_APP_CONFIG`. */ -const APP_CONFIG_QUERY_KEY = ["FLOW_APP_CONFIG"] as const; - -/** Unminified `QueryCache` key for `CHECK_TOOL_AVAILABILITY` on Flow workspace routes. */ -const TOOL_AVAILABILITY_QUERY_KEY = [ - "CHECK_TOOL_AVAILABILITY", - FLOW_TOOL_AVAILABILITY_ID, -] as const; - /** Default Boq frontend data prefix when `WIZ_global_data.eptZe` is absent. */ const DEFAULT_DATA_PREFIX = "/_/AiSandboxAngularFrontend/"; /** Maximum wait in milliseconds for `WIZ_global_data` while the document loads. */ const WIZ_READY_WAIT_MS = 1500; -/** Maximum wait in milliseconds for active route guards and pending queries to settle. */ -const GUARD_SETTLE_WAIT_MS = 2000; - -/** Short hydration wait in milliseconds when Angular hosts mount before `QueryCache` populates. */ -const HYDRATION_CACHE_WAIT_MS = 300; - /** Strict timeout in milliseconds for the read-only Flow backend probe. */ const PROBE_TIMEOUT_MS = 5000; @@ -95,226 +63,7 @@ function resolveDataPrefix(raw: string | undefined): string { return leading.endsWith("/") ? leading : `${leading}/`; } -/** Returns `true` when `value` is a plain key-value object suitable as a JSPB sparse pivot map. */ -function isPlainPivotObject(value: unknown): value is Record { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return false; - } - const proto: unknown = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} - -/** Reads a 1-based protobuf field from a JSPB `.qf` instance, dense array, or sparse pivot object. */ -function readJspbField(payload: unknown, fieldNumber: number): unknown { - if (!payload || typeof payload !== "object") { - return undefined; - } - let target: unknown = payload; - if (!Array.isArray(target)) { - const qf = readOwn(target, "qf"); - if (Array.isArray(qf)) { - target = qf; - } else { - const toJson = readOwn(target, "toJSON"); - if (typeof toJson === "function") { - try { - const serialized: unknown = toJson.call(target); - if (serialized && typeof serialized === "object") { - target = serialized; - } - } catch { - // Fall through to direct property inspection. - } - } - } - } - const sparseKey = String(fieldNumber); - if (!Array.isArray(target)) { - return readOwn(target, sparseKey); - } - const lastIndex = target.length - 1; - if (lastIndex < 0) { - return undefined; - } - const denseIndex = fieldNumber - 1; - const tail: unknown = target[lastIndex]; - const hasPivot = isPlainPivotObject(tail); - if (denseIndex < lastIndex) { - const denseVal: unknown = target[denseIndex]; - if (denseVal !== undefined && denseVal !== null) { - return denseVal; - } - return hasPivot ? readOwn(tail, sparseKey) : denseVal; - } - if (hasPivot) { - return readOwn(tail, sparseKey); - } - return denseIndex === lastIndex ? tail : undefined; -} - -/** Returns `true` when a JSPB boolean flag value explicitly disables eligibility (`false` or `0`). */ -function isDisabledJspbBool(value: unknown): boolean { - return value === false || value === 0; -} - -/** Evaluates `FLOW_APP_CONFIG` (`cPZSdc`) payload fields `31` (country) and `32` (age). */ -function evaluateAppConfigPayload( - payload: unknown, -): "ok" | "unsupported_country" | "age_restricted" | "invalid" { - if (!payload || typeof payload !== "object") { - return "invalid"; - } - if (isDisabledJspbBool(readJspbField(payload, 31))) { - return "unsupported_country"; - } - if (isDisabledJspbBool(readJspbField(payload, 32))) { - return "age_restricted"; - } - return "ok"; -} - -/** Evaluates `CHECK_TOOL_AVAILABILITY` (`KV2T2d`) field `1` (`Cla()`) for verified age restriction (`7`). */ -function evaluateToolAvailabilityPayload( - payload: unknown, -): "ok" | "age_restricted" { - if (!payload || typeof payload !== "object") { - return "ok"; - } - let rawCode: unknown = readJspbField(payload, 1); - if (rawCode === undefined) { - const cla = readOwn(payload, "Cla"); - if (typeof cla === "function") { - try { - rawCode = cla.call(payload); - } catch { - rawCode = undefined; - } - } - } - const code = - typeof rawCode === "number" && Number.isFinite(rawCode) - ? Math.trunc(rawCode) - : undefined; - if (code === 7) { - return "age_restricted"; - } - return "ok"; -} - -/** Returns `true` when `entry` is actively fetching or still awaiting its initial settlement. */ -function isQueryPending(entry: AngularQueryEntry | undefined): boolean { - if (!entry?.state) return false; - return ( - entry.state.status === "pending" || entry.state.fetchStatus === "fetching" - ); -} - -/** Returns `true` when a `QueryCache` error indicates HTTP 401 or gRPC `UNAUTHENTICATED` (`16`). */ -function isUnauthenticatedQueryError(err: unknown): boolean { - if (!err || typeof err !== "object") return false; - const um = readOwn(err, "um"); - const httpStatus = readOwn(err, "httpStatusCode"); - const status = readOwn(err, "status"); - const code = readOwn(err, "code"); - if (um === 401 || httpStatus === 401 || status === 401 || code === 16) { - return true; - } - if (status && typeof status === "object") { - const vf = readOwn(status, "vf"); - if (typeof vf === "function") { - try { - if (vf.call(status) === 16) return true; - } catch { - return false; - } - } - } - return false; -} - -/** Reads settled eligibility queries from Angular's `QueryCache` after awaiting active route guards. */ -async function checkAngularQueryEligibility(): Promise { - if (!hasAngularContext()) { - return null; - } - const start = Date.now(); - const settleDeadline = start + GUARD_SETTLE_WAIT_MS; - const hydrationDeadline = start + HYDRATION_CACHE_WAIT_MS; - - while (true) { - if (!isWorkspaceLocation(location.hostname, location.pathname)) { - return authResult(false, true, false, 0, "non_workspace_route"); - } - if (document.querySelector(SIGN_IN_SELECTOR)) { - return authResult(false, true, false, 0, "sign_in_prompt"); - } - - const cache = await ensureAngularQueryCache(); - const appQuery = readQueryCacheEntry(cache, APP_CONFIG_QUERY_KEY); - const toolQuery = readQueryCacheEntry(cache, TOOL_AVAILABILITY_QUERY_KEY); - const navigating = isRouterNavigating(); - const pending = isQueryPending(appQuery) || isQueryPending(toolQuery); - const now = Date.now(); - - if ((navigating || pending) && now < settleDeadline) { - await new Promise((resolve) => setTimeout(resolve, 50)); - continue; - } - if (!appQuery && !toolQuery && now < hydrationDeadline) { - await new Promise((resolve) => setTimeout(resolve, 50)); - continue; - } - - const authErr = - appQuery?.state?.error ?? - appQuery?.state?.failureReason ?? - toolQuery?.state?.error ?? - toolQuery?.state?.failureReason; - if (isUnauthenticatedQueryError(authErr)) { - return authResult(false, false, true, 401, "rpc_unauthenticated"); - } - - const toolData = - toolQuery?.state?.status === "success" ? toolQuery.state.data : undefined; - if (toolData !== undefined) { - const toolVerdict = evaluateToolAvailabilityPayload(toolData); - if (toolVerdict !== "ok") { - return authResult(false, true, false, 0, toolVerdict); - } - } - - const appData = - appQuery?.state?.status === "success" ? appQuery.state.data : undefined; - if (appData !== undefined) { - const appVerdict = evaluateAppConfigPayload(appData); - if (appVerdict === "unsupported_country" || appVerdict === "age_restricted") { - return authResult(false, true, false, 0, appVerdict); - } - } - - if ((!appQuery || !toolQuery) && now < hydrationDeadline) { - await new Promise((resolve) => setTimeout(resolve, 50)); - continue; - } - - if ( - appData !== undefined && - (toolData !== undefined || toolQuery?.state?.status === "error") - ) { - if (evaluateAppConfigPayload(appData) !== "ok") { - return null; - } - if (!isWorkspaceLocation(location.hostname, location.pathname)) { - return authResult(false, true, false, 0, "non_workspace_route"); - } - return authResult(true, false, false, 0, "ok"); - } - - return null; - } -} - -/** Inspects a batched `batchexecute` response body for `cPZSdc` and `KV2T2d` eligibility or auth errors. */ +/** Inspects one `batchexecute` response body for `FLOW_APP_CONFIG` or token expiration. */ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { let verifiedConfig = false; for (const rawLine of text.split(/\r?\n/)) { @@ -338,10 +87,7 @@ 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 && entry[1] !== TOOL_AVAILABILITY_RPC_ID) - ) { + if (entry[0] !== "wrb.fr" || entry[1] !== APP_CONFIG_RPC_ID) { continue; } const rpcErr = entry[5]; @@ -349,39 +95,33 @@ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { if (rpcErr[0] === 16) { return authResult(false, false, true, status, "rpc_unauthenticated"); } - if (entry[1] === APP_CONFIG_RPC_ID) { - return authResult( - false, - true, - false, - status, - `rpc_error_${rpcErr[0]}`, - ); - } - continue; + return authResult( + false, + true, + false, + status, + `rpc_error_${rpcErr[0]}`, + ); } if (typeof entry[2] !== "string") { continue; } - let parsedPayload: unknown; + let config: unknown; try { - parsedPayload = JSON.parse(entry[2]); + config = JSON.parse(entry[2]); } catch { continue; } - if (entry[1] === APP_CONFIG_RPC_ID) { - const verdict = evaluateAppConfigPayload(parsedPayload); - if (verdict === "unsupported_country" || verdict === "age_restricted") { - return authResult(false, true, false, status, verdict); - } - if (verdict === "ok") { - verifiedConfig = true; + if (Array.isArray(config)) { + if (config[30] === false) { + return authResult(false, true, false, status, "unsupported_country"); } - } else if (entry[1] === TOOL_AVAILABILITY_RPC_ID) { - const toolVerdict = evaluateToolAvailabilityPayload(parsedPayload); - if (toolVerdict !== "ok") { - return authResult(false, true, false, status, toolVerdict); + if (config[31] === false) { + return authResult(false, true, false, status, "age_restricted"); } + verifiedConfig = true; + } else if (config !== null && typeof config === "object") { + verifiedConfig = true; } } } @@ -394,7 +134,7 @@ function parseProbeEnvelope(text: string, status: number): AuthCheckResult { return authResult(true, false, false, status, "ok"); } -/** Verifies host, workspace route, `WIZ_global_data` tokens, Angular `QueryCache`, or a batched Flow RPC probe. */ +/** Verifies host, workspace route, `WIZ_global_data` tokens, and an HTTP 200 Flow probe. */ export async function checkAuth(): Promise { await waitForWizData(); @@ -422,13 +162,8 @@ export async function checkAuth(): Promise { return authResult(false, true, false, 0, "missing_wiz_token"); } - const cachedResult = await checkAngularQueryEligibility(); - if (cachedResult) { - return cachedResult; - } - const params = new URLSearchParams({ - rpcids: `${APP_CONFIG_RPC_ID},${TOOL_AVAILABILITY_RPC_ID}`, + rpcids: APP_CONFIG_RPC_ID, "source-path": location.pathname || "/", hl: "en", rt: "c", @@ -443,21 +178,9 @@ export async function checkAuth(): Promise { if (authuser) { params.set("authuser", authuser); } - const pageId = resolveFlowPageId(); - if (pageId) { - params.set("pageId", pageId); - } const reqPayload = JSON.stringify([ - [ - [APP_CONFIG_RPC_ID, "[]", null, "1"], - [ - TOOL_AVAILABILITY_RPC_ID, - JSON.stringify([FLOW_TOOL_AVAILABILITY_ID]), - null, - "2", - ], - ], + [[APP_CONFIG_RPC_ID, "[]", null, "generic"]], ]); const body = `f.req=${encodeURIComponent(reqPayload)}&at=${encodeURIComponent(xsrfToken)}`; const prefix = resolveDataPrefix(wiz.eptZe); diff --git a/ts/flow_route.ts b/ts/flow_route.ts index f6a6d78..4aa0a9b 100644 --- a/ts/flow_route.ts +++ b/ts/flow_route.ts @@ -1,7 +1,7 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Parse Google Flow URL prefixes, workspace route allowlists, and request identifiers. +// Parse Google Flow URL prefixes, non-workspace route denylists, and account query parameters. /** Parsed prefix and normalized route details of a Flow pathname. */ export interface StrippedFlowPath { @@ -37,8 +37,40 @@ const RESERVED_FLOW_SEGMENTS = new Set([ "404", "login", "debug", + "api", + "_", ]); +/** Non-workspace Flow routes matched by exact segment or segment prefix after prefix stripping. */ +const NON_WORKSPACE_SEGMENT_PREFIXES = [ + "/unsupported-country", + "/unsupported-browser", + "/unavailable", + "/age-restricted", + "/privacy", + "/credits-terms", + "/about", + "/flow/about", + "/academy", + "/shared/tool", + "/shared", + "/flow/shared/tool", + "/flow/shared", + "/tools/flow/shared/tool", + "/tools/flow/shared", + "/404", + "/login", + "/tools/flow/about", + "/tools/flow/login", + "/api", + "/_", +]; + +/** Returns `true` when `path` equals `prefix` or starts with `prefix` followed by `/`. */ +function hasSegmentPrefix(path: string, prefix: string): boolean { + return path === prefix || path.startsWith(`${prefix}/`); +} + /** Strips `/fx/tools/flow`, `/fx`, `/u/`, and `//global` prefixes from `pathname`. */ export function splitFlowPath( pathname: string = location.pathname, @@ -77,43 +109,17 @@ export function splitFlowPath( return { prefix, route, hasLabsFlowPrefix, pathAuthuser }; } -/** Returns `true` when a prefix-stripped lowercase `route` is a recognized Flow workspace path. */ +/** Returns `true` when a prefix-stripped lowercase `route` is outside the Flow non-workspace denylist. */ export function isWorkspaceFlowRoute(route: string): boolean { - if ( - route === "/" || - route === "/projects" || - route === "/search" || - route === "/changelogs" - ) { - return true; - } - if (!route.startsWith("/project/")) return false; - const [projectId, ...sub] = route.slice("/project/".length).split("/"); - if (!projectId) return false; - if (sub.length === 0) return true; - if (sub.length === 1) { - return ["character", "tools", "create-tool", "trash", "chat"].includes( - sub[0], - ); - } - if (sub.length === 2) { - return ( - Boolean(sub[1]) && - ["character", "scene", "edit", "tool", "collection", "chat"].includes( - sub[0], - ) - ); - } - if (sub.length === 3) { - return ( - (sub[0] === "collection" && Boolean(sub[1]) && sub[2] === "character") || - (sub[0] === "trash" && sub[1] === "collection" && Boolean(sub[2])) - ); + if (route === "/flow") { + return false; } - return false; + return !NON_WORKSPACE_SEGMENT_PREFIXES.some((prefix) => + hasSegmentPrefix(route, prefix), + ); } -/** Returns `true` when `hostname` and `pathname` target an allowlisted Flow workspace route. */ +/** Returns `true` when `hostname` and `pathname` target an active Flow workspace route. */ export function isWorkspaceLocation( hostname: string, pathname: string, @@ -130,25 +136,12 @@ export function isWorkspaceLocation( return isWorkspaceFlowRoute(stripped.route); } -/** Resolves the active `authuser` value from URL query, `/u/` prefix, or `WIZ_global_data`. */ +/** Resolves the active `authuser` value from the URL query or `/u/` prefix. */ export function resolveFlowAuthuser( search: string = location.search, pathname: string = location.pathname, ): string | null { const fromQuery = new URLSearchParams(search).get("authuser")?.trim(); if (fromQuery) return fromQuery; - const { pathAuthuser } = splitFlowPath(pathname); - if (pathAuthuser) return pathAuthuser; - const fromWiz = window.WIZ_global_data?.QrtxK; - return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; -} - -/** Resolves the active `pageId` value from URL query or `WIZ_global_data.S06Grb`. */ -export function resolveFlowPageId( - search: string = location.search, -): string | null { - const fromQuery = new URLSearchParams(search).get("pageId")?.trim(); - if (fromQuery) return fromQuery; - const fromWiz = window.WIZ_global_data?.S06Grb; - return typeof fromWiz === "string" && fromWiz.trim() ? fromWiz.trim() : null; + return splitFlowPath(pathname).pathAuthuser; } diff --git a/ts/types.ts b/ts/types.ts index 4ee9253..6e1c59b 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -20,10 +20,6 @@ export interface WizGlobalData { eptZe?: string; /** Encoded FIFE host configuration string. */ TSDtV?: string; - /** Active Google account index rendered by the server. */ - QrtxK?: string; - /** Delegated or organization page identifier for batchexecute calls. */ - S06Grb?: string; } /** Angular Router subset used for in-app navigation. */ @@ -36,48 +32,6 @@ export interface AngularRouter { options: unknown; } -/** State snapshot stored on one cached query entry in `QueryCache`. */ -export interface AngularQueryState { - /** Settlement status (`pending`, `success`, or `error`). */ - status?: string; - /** Active network status (`fetching`, `paused`, or `idle`). */ - fetchStatus?: string; - /** Decoded response payload or protobuf message instance. */ - data?: unknown; - /** Terminal error reported by the last failed fetch. */ - error?: unknown; - /** Intermediate failure reason recorded while retries remain active. */ - failureReason?: unknown; -} - -/** Cached query entry managed by Angular's `QueryCache`. */ -export interface AngularQueryEntry { - /** Unminified query key array. */ - queryKey?: readonly unknown[]; - /** Serialized query key hash string. */ - queryHash?: string; - /** Live query state snapshot. */ - state?: AngularQueryState; -} - -/** Subset of TanStack `QueryCache` exposed on Angular's `QueryClient`. */ -export interface AngularQueryCache { - /** Finds a single cached query matching `queryKey`. */ - find?: (filters: { queryKey: readonly unknown[]; exact?: boolean }) => AngularQueryEntry | undefined; - /** Looks up a cached query by its serialized `queryHash`. */ - get?: (queryHash: string) => AngularQueryEntry | undefined; - /** Lists all cached query entries. */ - getAll?: () => AngularQueryEntry[]; - /** Underlying hash-keyed query registry map. */ - queries?: Map; -} - -/** Subset of Angular's injected `QueryClient` holding `queryCache`. */ -export interface AngularQueryClient { - /** Active query cache instance. */ - queryCache: AngularQueryCache; -} - /** Destroyable Angular component or service lifecycle handle. */ export interface AngularLifecycleHandle { /** Lifecycle destroy marker in the Flow front end from 2026-11-18 on. */