Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
263 changes: 104 additions & 159 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -61,82 +38,6 @@ pub(crate) struct LoginParams {
pub(crate) cookies: Option<Vec<Map<String, Value>>>,
}

/// 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<Value> {
for _ in 0..3 {
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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<anyhow::Error> {
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<Option<Value>> {
engine.promote_login_chrome(start_url).await?;
Expand All @@ -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;
Expand All @@ -311,22 +210,71 @@ 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;
}
engine.shutdown().await;
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<Value> {
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,
Expand All @@ -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!(
Expand All @@ -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?;
Expand All @@ -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,
Expand All @@ -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<String> = None;

loop {
let Some(st) = engine.poll_login_chrome().await? else {
Expand All @@ -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!(
Expand Down Expand Up @@ -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",
Expand All @@ -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,
}));
}
Expand Down
Loading
Loading