diff --git a/src/auth.rs b/src/auth.rs index 596c885..1e0000f 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -12,40 +12,17 @@ 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::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; -/// 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 { @@ -61,82 +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'/')) -} - -/// 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()) - }) -} - -/// Returns `true` when `raw` points to a Google Flow workspace host and 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" { - return false; - } - let Some(host) = parsed.host_str().map(|h| h.to_ascii_lowercase()) else { - return false; - }; - 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") { - return false; - } - !is_non_workspace_flow_path(&clean_path) -} - /// Evaluates `checkAuth` once in the active page, retrying brief context resets during navigation. async fn eval_check_auth_once(engine: &ChromeEngine) -> Option { for _ in 0..3 { @@ -225,27 +126,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. -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 { - return false; - } - let clean = normalize_flow_path(parsed.path()); - let rel = strip_fx_prefix(&clean); - 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") @@ -289,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?; @@ -298,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; @@ -311,15 +210,27 @@ 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_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(); + if is_signed_in_flow_url(&final_url) { + return Ok(Some(signed_in_login_result( + "interactive-chrome", + cookies.len(), + final_url, + ))); + } + } + 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); + } + } } tokio::time::sleep(Duration::from_millis(500)).await; } @@ -327,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, @@ -339,7 +287,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!( @@ -348,17 +296,9 @@ async fn login_with_chrome( ); } if st.exited || st.has_google_auth_cookies { - if let Some(res) = finalize_promoted_login(engine, FLOW_URL).await? { - return Ok(res); - } - if st.exited { - anyhow::bail!("Sign-in window was closed before Google Sign-In completed."); - } + return promote_ready_login_chrome(engine, st, None).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 +314,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 +331,7 @@ async fn login_with_chrome( let clamped_secs = timeout_secs.clamp(15, 3600); let deadline = Instant::now() + Duration::from_secs(clamped_secs); + let mut last_flow_url: Option = None; loop { let Some(st) = engine.poll_login_chrome().await? else { @@ -405,24 +346,23 @@ async fn login_with_chrome( ); } + if let Some(observed) = st.flow_url.as_ref() { + last_flow_url = Some(observed.clone()); + } + 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(res) = finalize_promoted_login(engine, FLOW_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 { - if let Ok(Some(res)) = finalize_promoted_login(engine, FLOW_URL).await { - return Ok(res); + let target_url = last_flow_url.as_deref().unwrap_or(FLOW_URL); + 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!( @@ -488,10 +428,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 +446,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..a59dc00 100644 --- a/src/chrome.rs +++ b/src/chrome.rs @@ -11,6 +11,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::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}; @@ -53,7 +54,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 core Google Sign-In cookies were updated since launch. pub(crate) has_google_auth_cookies: bool, } @@ -328,24 +331,37 @@ 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 && is_flow_host_url(&url) { + if url.to_ascii_lowercase().contains("/fx/api/auth/") { + continue; + } + flow_checked = true; + if is_signed_in_flow_url(&url) { + probe.flow_url = Some(url); + } + } } } @@ -364,8 +380,8 @@ fn probe_cookies_db(scratch_cookies: &Path, min_webkit_us: i64) -> bool { }) else { return false; }; - for pair in rows.flatten() { - if is_google_auth_cookie_pair(&pair.0, &pair.1) { + for (host, name) in rows.flatten() { + if is_google_auth_cookie_pair(&host, &name) { return true; } } 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 110a532..77063cc 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -138,6 +138,8 @@ pub(crate) struct LoginPollStatus { pub(crate) exited: bool, /// Google Accounts rejection URL observed during sign-in, if any. pub(crate) rejected_url: Option, + /// Latest signed-in Google Flow workspace URL observed in profile history. + pub(crate) flow_url: Option, /// True when Google authentication cookies exist in the login profile. 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, })) } diff --git a/src/flow_url.rs b/src/flow_url.rs new file mode 100644 index 0000000..1f9035d --- /dev/null +++ b/src/flow_url.rs @@ -0,0 +1,217 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Parse and classify Google Flow hosts, prefixes, and workspace routes. + +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. + 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" + | "api" + | "_" + ) +} + +/// 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 non-grid editor or view subroute. +pub(crate) fn is_non_grid_project_subroute_segments(segs: &[&str]) -> bool { + match segs { + [ + "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 outside the Flow non-workspace denylist. +pub(crate) fn is_workspace_flow_route(route: &str) -> bool { + if route == "/flow" { + return false; + } + !NON_WORKSPACE_SEGMENT_PREFIXES + .iter() + .any(|prefix| has_segment_prefix(route, prefix)) +} + +/// 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; + } + 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 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)) +} + +/// 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 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/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 e11643e..adb6d77 100644 --- a/src/project.rs +++ b/src/project.rs @@ -13,11 +13,12 @@ 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::{ - 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 +89,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 +98,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 +151,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, @@ -511,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 5ce889c..a912574 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -6,62 +6,76 @@ 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 project URL. +/// 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; + } + 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()) +} + +/// 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()); + } + if !url.starts_with('/') { + return None; + } let path = url.split(['?', '#']).next()?; - let (_, project) = path.split_once("/project/")?; - let id = project.split('/').next()?.trim(); - (!id.is_empty()).then(|| id.to_string()) + project_id_from_path(path) } -/// 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 { +/// 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; }; - h.eq_ignore_ascii_case("flow.google.com") - || h.eq_ignore_ascii_case("labs.google") - || h.to_ascii_lowercase().ends_with(".labs.google") + !project_id.is_empty() && is_non_grid_project_subroute_segments(sub) } -/// Extracts the active route prefix before `/project/` from a Flow URL path. +/// Returns `true` when `url` points to a non-grid subroute inside `/project/`. +pub(crate) fn is_project_subroute_url(url: &str) -> bool { + 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; + } + let path = url.split(['?', '#']).next().unwrap_or_default(); + is_project_subroute_path(path) +} + +/// Extracts the active route prefix from a Flow URL path. fn flow_route_prefix(path: &str) -> String { + 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(); } - let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); - let mut prefix = Vec::new(); - let mut i = 0; - while i < segs.len() { - if segs[i..].starts_with(&["fx", "tools", "flow"]) { - 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()) - { - prefix.extend_from_slice(&["u", segs[i + 1]]); - i += 2; - } else if i + 1 < segs.len() - && segs[i + 1] == "global" - && !matches!( - segs[i], - "project" | "projects" | "about" | "shared" | "flow" | "tools" | "fx" | "u" - ) - { - prefix.extend_from_slice(&[segs[i], "global"]); - i += 2; - } else { - break; - } - } - if prefix.is_empty() { - String::new() - } else { - format!("/{}", prefix.join("/")) - } + String::new() } /// Builds a Google Flow `/project/` or subroute URL with active prefixes, `hl=en`, and `authuser`. 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 6c948c0..4614b49 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -11,6 +11,7 @@ import { normalizeFlowMediaUrl, readMediaUrl, } from "./dom"; +import { splitFlowPath } from "./flow_route"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; import { runtimeState } from "./state"; import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; @@ -179,9 +180,11 @@ function flowQueryParams(search: string = location.search): Record`. */ 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(/\/+$/, ""); @@ -194,34 +197,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`. */ diff --git a/ts/check_auth.ts b/ts/check_auth.ts index 7a94a33..d842474 100644 --- a/ts/check_auth.ts +++ b/ts/check_auth.ts @@ -3,6 +3,7 @@ // Verify Google Flow workspace access with route guards, Wiz tokens, and a read-only probe. +import { isWorkspaceLocation, resolveFlowAuthuser } from "./flow_route"; import type { AuthCheckResult } from "./types"; /** Read-only `FLOW_APP_CONFIG` RPC identifier in the Flow workspace route guard. */ @@ -17,77 +18,10 @@ const WIZ_READY_WAIT_MS = 1500; /** 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 { - 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")) { - return false; - } - return !isNonWorkspaceFlowPath(clean); -} - /** Builds an `AuthCheckResult` record from the active document metadata. */ function authResult( signedIn: boolean, @@ -240,6 +174,10 @@ 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 reqPayload = JSON.stringify([ [[APP_CONFIG_RPC_ID, "[]", null, "generic"]], diff --git a/ts/flow_route.ts b/ts/flow_route.ts new file mode 100644 index 0000000..4aa0a9b --- /dev/null +++ b/ts/flow_route.ts @@ -0,0 +1,147 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// 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 { + /** 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", + "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, +): 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 outside the Flow non-workspace denylist. */ +export function isWorkspaceFlowRoute(route: string): boolean { + if (route === "/flow") { + return false; + } + return !NON_WORKSPACE_SEGMENT_PREFIXES.some((prefix) => + hasSegmentPrefix(route, prefix), + ); +} + +/** Returns `true` when `hostname` and `pathname` target an active 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 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; + return splitFlowPath(pathname).pathAuthuser; +}