Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

cua-auth: branded sign-in callback page for the CLI and Cua Spaces (#5434)

Francesco Bonacci5762b42aff89
diff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.ts
index 4063a93ead..a96c852394 100644
--- a/apps/cua-spaces-desktop/src/main.ts
+++ b/apps/cua-spaces-desktop/src/main.ts
@@ -127,6 +127,8 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcu
// start (Edge's first run) must not find the port closed while the app
// still offers its link.
process.env.CUA_OIDC_LOGIN_TIMEOUT_SECS ??= "600";
+ // The browser's sign-in page says where to go back to.
+ process.env.CUA_AUTH_RETURN_TO ??= "Cua Spaces";
const native = await loadNative(dir);
// False without a browser here: the sign-in then uses the device flow.
const openUrl = async (url: string) => {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
index e9bac58bd1..c84e1fc29d 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
@@ -234,6 +234,8 @@ public final class LiveAccount: AccountRunning, @unchecked Sendable {
}
public func beginSignIn() async throws -> SignInAttempt {
+ // The browser's sign-in page says where to go back to (the SDK reads it).
+ setenv("CUA_AUTH_RETURN_TO", "Cua Spaces", 0)
let attempt = try await auth.beginLogin(flow: nil)
let url = URL(string: attempt.url())
if let url {
diff --git a/apps/cua-spaces/src-tauri/src/auth.rs b/apps/cua-spaces/src-tauri/src/auth.rs
index 06cb84f127..7def51b655 100644
--- a/apps/cua-spaces/src-tauri/src/auth.rs
+++ b/apps/cua-spaces/src-tauri/src/auth.rs
@@ -69,10 +69,13 @@ impl SessionHandle {
/// Starts a sign-in (browser, else device code).
pub async fn begin_login(&self) -> Result<PendingLogin, String> {
- self.session
+ let mut pending = self
+ .session
.begin_login(Flow::Auto)
.await
- .map_err(|e| e.to_string())
+ .map_err(|e| e.to_string())?;
+ pending.return_to = Some(cua_auth::ReturnTo::App("Cua Spaces".into()));
+ Ok(pending)
}
/// Stores freshly issued credentials; returns the display identity.
diff --git a/libs/cua/crates/cua-auth/src/callback.html b/libs/cua/crates/cua-auth/src/callback.html
new file mode 100644
index 0000000000..7ced2af7b6
--- /dev/null
+++ b/libs/cua/crates/cua-auth/src/callback.html
@@ -0,0 +1,86 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="color-scheme" content="light dark">
+<meta name="referrer" content="no-referrer">
+<link rel="icon" href="data:,">
+<title>{{title}}</title>
+<style>
+:root {
+ --background: oklch(0.979 0.003 264.5);
+ --foreground: oklch(0.22 0.01 264);
+ --muted: oklch(0.945 0.004 264);
+ --muted-foreground: oklch(0.47 0.012 264);
+ --border: oklch(0.9 0.006 264);
+ --destructive: oklch(0.52 0.2 27);
+ --font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif;
+ --font-mono: ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace;
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --background: oklch(0.209 0.009 264.4);
+ --foreground: oklch(0.94 0.005 264);
+ --muted: oklch(0.27 0.01 264);
+ --muted-foreground: oklch(0.72 0.012 264);
+ --border: oklch(1 0 0 / 0.09);
+ --destructive: oklch(0.72 0.17 25);
+ }
+}
+* { box-sizing: border-box; }
+html, body { height: 100%; margin: 0; }
+body {
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ background: var(--background);
+ color: var(--foreground);
+ font: 15px/1.55 var(--font-sans);
+ -webkit-font-smoothing: antialiased;
+}
+main { width: 100%; max-width: 380px; text-align: center; }
+/* The Cua key: the app icon's blue keycap with the stacked Cua mark, inlined as a
+ 192 px WebP so the page stays offline. Rendered by
+ apps/cua-spaces-macos/scripts/dmg-art/key.html (#5441). */
+.key {
+ display: block;
+ width: 88px;
+ height: 88px;
+ margin: 0 auto 24px;
+ filter: drop-shadow(0 10px 14px rgb(0 0 0 / 0.18));
+ animation: press 520ms cubic-bezier(0.32, 0.72, 0, 1) 120ms both;
+}
+@media (prefers-color-scheme: dark) {
+ .key { filter: drop-shadow(0 10px 16px rgb(0 0 0 / 0.5)); }
+}
+@keyframes press {
+ 40% { transform: translateY(3px); }
+}
+h1 { margin: 0 0 8px; font-size: 24px; line-height: 1.25; font-weight: 600; letter-spacing: -0.01em; }
+.error h1 { color: var(--destructive); }
+p { margin: 0 0 6px; color: var(--muted-foreground); }
+p.account { color: var(--foreground); }
+code {
+ font: 0.9em var(--font-mono);
+ padding: 2px 6px;
+ border-radius: 6px;
+ background: var(--muted);
+ border: 1px solid var(--border);
+ color: var(--foreground);
+ white-space: nowrap;
+}
+@media (prefers-reduced-motion: reduce) {
+ .key { animation: none; }
+}
+</style>
+</head>
+<body>
+<main class="{{kind}}">
+<img class="key" alt="" aria-hidden="true" width="88" height="88" src="data:image/webp;base64,UklGRo4ZAABXRUJQVlA4WAoAAAAQAAAAvwAAvwAAQUxQSKYHAAABoIftkyFJisha27Zt27Zt27Z9tn1ztm3bWttWVcbzdGf1dFdkxr8XEZAgSW7bADhAq707ByKLhP7wP04RET2lYnYyc17if5eHotqqWDT/W1VbdOu1cPrAxvHfQc6Kaurmrdt7fdrnhy9RPJ57a1EJUCiergrpFq3Qd13at6fJiFoHgSaif0YCoGC6ntmuMuQs1mfxoz+eMm19P9A6/CsQbRcqKc+sjxm98t2m3//NoUS6lE4MArolozAkKgx1Dzlqt5/++GeHzP+UoZtU1NdpPSg5OrZwGytWd9jGJ749QenqJpmC83XcT6jQC9lmKlyx/9q0Xy+GqqXRxlKNPr3iuTuEYqJuDbLkLt1l2o6X/j4bsk1PN7XCbw+em0NJ2DZb9vI9J2965sfj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Uzv6m5qDnVe5j+OmdXyS4KV69aaIcUQecED8xcgOBGNu2A50qQk+eH9EfRaqk+btmXHoJBZPw93OsUlao7wiywzCmefZw4JcQ4Jo4Cf6mPlbjN+yykpP7SIiSEi+e+xogYKrwOZKpmJjIiuhCn8MrGvOujgcNLlQfK4fZCfyxFUrEVY6ezDUtBoucybpDajnl0+Cprb5sLs23MyC1gOnuVIqitKJ1BRgxvr2tuVgDEOECdLUl+S8rQjoOH/tXU1rLiVyunOaNM1wrGZXKJeN0y+D7g4s0HaCg9qNUQBx6vi2F6JrmDTNroNAoGnMvH4Jg4aEw6nBebyGo9cBhg+dkV+zPoYNvaX2WgKKkMXR+iZExuxjJ+vgIi5cUatMgpYfcpfiI9tKjFVQ9RxHy60f0jwb9pBpQB6L4zW++Dun55mS6CvkmwwRZKM09ukv9wugsPP8Hju+AgZ7mXloeCnYgBeQXaz19cSEbefbxy0GqRjV9/Xx2hW0Pb6PQU9QXbQoqliwKVbb4eX/Dz/K4hoVdIpmWKrY8OVKyZPvKPk4C2p78F+QB7k5fakUpBeNpU/i4c0yCcsZfFSYoJFb191SHAPEivzPS1WmLDyeCIYF7NFCrEWn2fltGshcQkO6dvQlhi3iIdvHkd7KCx0igrgd06TguAuDkAAAAAAAAAAAAA==">
+<h1>{{heading}}</h1>
+{{body}}
+</main>
+{{script}}
+</body>
+</html>
diff --git a/libs/cua/crates/cua-auth/src/callback_page.rs b/libs/cua/crates/cua-auth/src/callback_page.rs
new file mode 100644
index 0000000000..244455cef4
--- /dev/null
+++ b/libs/cua/crates/cua-auth/src/callback_page.rs
@@ -0,0 +1,195 @@
+//! The page the browser shows on the loopback sign-in redirect. One
+//! self-contained template (inline CSS and mark, no network requests) for
+//! the CLI and the apps. It never shows anything from the redirect's query
+//! string: the code and state stay out of the page, and the provider's error
+//! text goes to the caller instead.
+
+const TEMPLATE: &str = include_str!("callback.html");
+
+/// Where the person goes back to once the browser part is done; it words the
+/// callback page.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ReturnTo {
+ /// `cua auth login` and other CLI commands.
+ Terminal,
+ /// An app, by its display name ("Cua Spaces").
+ App(String),
+}
+
+impl ReturnTo {
+ /// `CUA_AUTH_RETURN_TO`: `terminal`, or the display name of the app that
+ /// started sign-in. Unset: neither (the page names no destination).
+ pub fn from_env() -> Option<Self> {
+ let v = std::env::var("CUA_AUTH_RETURN_TO").ok()?;
+ match v.trim() {
+ "" => None,
+ "terminal" => Some(ReturnTo::Terminal),
+ name => Some(ReturnTo::App(name.to_string())),
+ }
+ }
+}
+
+/// What the callback page reports.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum Outcome {
+ /// Signed in, as this email when the tokens carry one.
+ SignedIn(Option<String>),
+ /// The person declined at the provider (`access_denied`).
+ Cancelled,
+ /// The redirect belongs to an earlier attempt (state mismatch).
+ Stale,
+ /// The provider would not exchange the code (it expired or was used).
+ Expired,
+ /// Anything else: a provider error, a missing code, a failed exchange.
+ Failed,
+}
+
+fn escape(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ '\'' => out.push_str("&#39;"),
+ c => out.push(c),
+ }
+ }
+ out
+}
+
+/// The page for `outcome`.
+pub(crate) fn render(outcome: &Outcome, to: Option<&ReturnTo>) -> String {
+ let retry = match to {
+ Some(ReturnTo::Terminal) => "To try again, run <code>cua auth login</code>.".to_string(),
+ Some(ReturnTo::App(app)) => format!("To try again, sign in from {}.", escape(app)),
+ None => "To try again, start sign-in again where you began.".to_string(),
+ };
+ let (kind, title, heading, body) = match outcome {
+ Outcome::SignedIn(email) => {
+ let account = email
+ .as_deref()
+ .filter(|e| !e.is_empty())
+ .map(|e| format!("<p class=\"account\">{}</p>\n", escape(e)))
+ .unwrap_or_default();
+ let next = match to {
+ Some(ReturnTo::Terminal) => {
+ "You can close this tab and return to your terminal.".to_string()
+ }
+ Some(ReturnTo::App(app)) => {
+ format!("You can close this tab and return to {}.", escape(app))
+ }
+ None => "You can close this tab.".to_string(),
+ };
+ (
+ "signed-in",
+ "Signed in to Cua",
+ "You're signed in",
+ format!("{account}<p>{next}</p>"),
+ )
+ }
+ Outcome::Cancelled => (
+ "error",
+ "Sign-in cancelled - Cua",
+ "Sign-in was cancelled",
+ format!("<p>Cua didn't get access to your account.</p>\n<p>{retry}</p>"),
+ ),
+ Outcome::Stale => (
+ "error",
+ "Sign-in out of date - Cua",
+ "This sign-in is out of date",
+ format!(
+ "<p>This page is from an earlier sign-in attempt, so Cua ignored it. If you started again, finish in the newest tab.</p>\n<p>{retry}</p>"
+ ),
+ ),
+ Outcome::Expired => (
+ "error",
+ "Sign-in expired - Cua",
+ "This sign-in expired",
+ format!(
+ "<p>It took too long to finish, or the link was already used.</p>\n<p>{retry}</p>"
+ ),
+ ),
+ Outcome::Failed => {
+ let details = match to {
+ Some(ReturnTo::Terminal) => " The details are in your terminal.".to_string(),
+ Some(ReturnTo::App(app)) => format!(" The details are in {}.", escape(app)),
+ None => String::new(),
+ };
+ (
+ "error",
+ "Sign-in failed - Cua",
+ "Sign-in didn't finish",
+ format!("<p>Cua couldn't complete the sign-in.{details}</p>\n<p>{retry}</p>"),
+ )
+ }
+ };
+ // Browsers only let a script close a tab a script opened; elsewhere this
+ // does nothing and the page stays.
+ let script = if kind == "signed-in" {
+ "<script>setTimeout(function () { window.close(); }, 1500);</script>"
+ } else {
+ ""
+ };
+ TEMPLATE
+ .replace("{{title}}", title)
+ .replace("{{kind}}", kind)
+ .replace("{{heading}}", heading)
+ .replace("{{script}}", script)
+ .replace("{{body}}", &body)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn all(email: Option<&str>) -> Vec<Outcome> {
+ vec![
+ Outcome::SignedIn(email.map(String::from)),
+ Outcome::Cancelled,
+ Outcome::Stale,
+ Outcome::Expired,
+ Outcome::Failed,
+ ]
+ }
+
+ #[test]
+ fn every_page_is_self_contained_and_filled_in() {
+ for to in [
+ None,
+ Some(ReturnTo::Terminal),
+ Some(ReturnTo::App("Cua Spaces".into())),
+ ] {
+ for o in all(Some("[email protected]")) {
+ let p = render(&o, to.as_ref());
+ assert!(p.starts_with("<!doctype html>"), "{o:?}");
+ assert!(!p.contains("{{"), "unfilled placeholder in {o:?}");
+ assert!(!p.contains("http://") && !p.contains("https://"), "{o:?}");
+ assert!(p.contains("prefers-reduced-motion"));
+ }
+ }
+ }
+
+ #[test]
+ fn words_the_destination() {
+ let t = Some(ReturnTo::Terminal);
+ let app = Some(ReturnTo::App("Cua Spaces".into()));
+ let ok = Outcome::SignedIn(Some("[email protected]".into()));
+ let p = render(&ok, t.as_ref());
+ assert!(p.contains("You're signed in") && p.contains("[email protected]"));
+ assert!(p.contains("return to your terminal") && p.contains("window.close()"));
+ assert!(render(&ok, app.as_ref()).contains("return to Cua Spaces"));
+ let p = render(&Outcome::Cancelled, t.as_ref());
+ assert!(p.contains("<code>cua auth login</code>") && !p.contains("window.close()"));
+ assert!(render(&Outcome::Expired, app.as_ref()).contains("sign in from Cua Spaces"));
+ }
+
+ #[test]
+ fn escapes_the_email_and_app_name() {
+ let to = ReturnTo::App("<b>".into());
+ let p = render(&Outcome::SignedIn(Some("<x>@e.com".into())), Some(&to));
+ assert!(p.contains("&lt;x&gt;@e.com") && p.contains("return to &lt;b&gt;."));
+ assert!(!p.contains("<x>") && !p.contains("<b>"));
+ }
+}
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index 8561edcbe3..b61cc922fc 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -90,11 +90,15 @@ pub enum Error {
/// Result alias.
pub type Result<T, E = Error> = std::result::Result<T, E>;
+mod callback_page;
#[allow(dead_code)]
mod chunked;
#[cfg(target_os = "macos")]
mod macos_keychain;
+use callback_page::Outcome;
+pub use callback_page::ReturnTo;
+
/// What to do when the login keychain cannot be used without a prompt this
/// session cannot show (an SSH session).
pub const KEYCHAIN_LOCKED_HINT: &str = "the macOS login keychain cannot be used from this session \
@@ -1664,6 +1668,9 @@ pub struct PendingLogin {
pub user_code: Option<String>,
/// Why the flow differs from the one asked for (fallback), if it does.
pub note: Option<String>,
+ /// Browser flow: where the callback page tells the person to go back to.
+ /// Starts from [`ReturnTo::from_env`].
+ pub return_to: Option<ReturnTo>,
oidc: Oidc,
token_endpoint: String,
pending: Pending,
@@ -1759,6 +1766,7 @@ async fn begin_pkce(oidc: &Oidc, d: &Discovery) -> Result<PendingLogin, String>
url,
user_code: None,
note: None,
+ return_to: ReturnTo::from_env(),
oidc: oidc.clone(),
token_endpoint: d.token_endpoint.clone(),
pending: Pending::Pkce {
@@ -1803,6 +1811,7 @@ async fn begin_device(oidc: &Oidc, d: &Discovery) -> Result<PendingLogin> {
url: verify,
user_code: (!user_code.is_empty()).then_some(user_code),
note: None,
+ return_to: ReturnTo::from_env(),
oidc: oidc.clone(),
token_endpoint: d.token_endpoint.clone(),
pending: Pending::Device {
@@ -1827,9 +1836,10 @@ impl PendingLogin {
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(300);
- let code = tokio::time::timeout(
+ let to = self.return_to.as_ref();
+ let (code, mut browser) = tokio::time::timeout(
Duration::from_secs(secs),
- await_callback(&listener, &state),
+ await_callback(&listener, &state, to),
)
.await
.map_err(|_| {
@@ -1838,7 +1848,7 @@ impl PendingLogin {
.into(),
)
})??;
- let (status, v) = self
+ let exchanged = self
.oidc
.form(
&self.token_endpoint,
@@ -1850,14 +1860,25 @@ impl PendingLogin {
("code_verifier", &verifier),
],
)
- .await?;
- if status != 200 {
- return Err(Error::Unauthenticated(describe(
+ .await;
+ // Keycloak: the code expired or was already redeemed.
+ let invalid_grant =
+ matches!(&exchanged, Ok((_, v)) if v["error"] == "invalid_grant");
+ let creds = match exchanged {
+ Ok((200, v)) => Credentials::from_token_response(&v),
+ Ok((status, v)) => Err(Error::Unauthenticated(describe(
&v,
&format!("token request failed (HTTP {status})"),
- )));
- }
- Credentials::from_token_response(&v)
+ ))),
+ Err(e) => Err(e),
+ };
+ let (status, outcome) = match &creds {
+ Ok(c) => ("200 OK", Outcome::SignedIn(c.identity().email)),
+ Err(_) if invalid_grant => ("400 Bad Request", Outcome::Expired),
+ Err(_) => ("502 Bad Gateway", Outcome::Failed),
+ };
+ respond_page(&mut browser, status, &outcome, to).await;
+ creds
}
Pending::Device {
device_code,
@@ -1909,28 +1930,30 @@ impl PendingLogin {
}
}
-const CALLBACK_OK: &str = "<!doctype html><meta charset=utf-8><title>Cua</title><body style=\"font-family:system-ui;margin:4em\"><h1>Signed in to Cua</h1><p>You can close this tab and return to the app.</p></body>";
-
-/// Escapes text for an HTML body (the callback page echoes the provider's
-/// error description, which arrives in the redirect's query string).
-fn html_escape(s: &str) -> String {
- let mut out = String::with_capacity(s.len());
- for c in s.chars() {
- match c {
- '&' => out.push_str("&amp;"),
- '<' => out.push_str("&lt;"),
- '>' => out.push_str("&gt;"),
- '"' => out.push_str("&quot;"),
- '\'' => out.push_str("&#39;"),
- c => out.push(c),
- }
- }
- out
+async fn respond_page(
+ sock: &mut tokio::net::TcpStream,
+ status: &str,
+ outcome: &Outcome,
+ to: Option<&ReturnTo>,
+) {
+ use tokio::io::AsyncWriteExt;
+ let body = callback_page::render(outcome, to);
+ let resp = format!(
+ "HTTP/1.1 {status}\r\ncontent-type: text/html; charset=utf-8\r\ncache-control: no-store\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = sock.write_all(resp.as_bytes()).await;
+ let _ = sock.shutdown().await;
}
/// Serves the loopback redirect until a request carries our `state` and a
-/// code (or an error). Bounded in connections and bytes.
-async fn await_callback(listener: &tokio::net::TcpListener, state: &str) -> Result<String> {
+/// code (or an error). Bounded in connections and bytes. Returns the code
+/// and the browser's connection, answered once the code is exchanged.
+async fn await_callback(
+ listener: &tokio::net::TcpListener,
+ state: &str,
+ to: Option<&ReturnTo>,
+) -> Result<(String, tokio::net::TcpStream)> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
for _ in 0..64 {
let (mut sock, _) = listener.accept().await.map_err(http_err)?;
@@ -1951,29 +1974,16 @@ async fn await_callback(listener: &tokio::net::TcpListener, state: &str) -> Resu
.unwrap_or("/")
.to_string();
let parsed = url::Url::parse(&format!("http://127.0.0.1{target}")).ok();
- let respond = |status: &str, body: &str| {
- format!(
- "HTTP/1.1 {status}\r\ncontent-type: text/html; charset=utf-8\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
- body.len()
- )
- };
let Some(u) = parsed.filter(|u| u.path() == "/callback") else {
let _ = sock
- .write_all(respond("404 Not Found", "not found").as_bytes())
+ .write_all(b"HTTP/1.1 404 Not Found\r\ncontent-type: text/plain\r\ncontent-length: 9\r\nconnection: close\r\n\r\nnot found")
.await;
continue;
};
let q: std::collections::HashMap<String, String> = u.query_pairs().into_owned().collect();
if q.get("state").map(String::as_str) != Some(state) {
- let _ = sock
- .write_all(
- respond(
- "400 Bad Request",
- "Sign-in state mismatch; start again with cua auth login.",
- )
- .as_bytes(),
- )
- .await;
+ // An earlier attempt's tab: keep waiting for this one.
+ respond_page(&mut sock, "400 Bad Request", &Outcome::Stale, to).await;
continue;
}
if let Some(e) = q.get("error") {
@@ -1981,28 +1991,19 @@ async fn await_callback(listener: &tokio::net::TcpListener, state: &str) -> Resu
.get("error_description")
.cloned()
.unwrap_or_else(|| e.clone());
- let _ = sock
- .write_all(
- respond(
- "400 Bad Request",
- &format!("Sign-in failed: {}", html_escape(&msg)),
- )
- .as_bytes(),
- )
- .await;
+ let outcome = if e == "access_denied" {
+ Outcome::Cancelled
+ } else {
+ Outcome::Failed
+ };
+ respond_page(&mut sock, "400 Bad Request", &outcome, to).await;
return Err(Error::Unauthenticated(format!("sign-in failed: {msg}")));
}
let Some(code) = q.get("code").filter(|c| !c.is_empty()).cloned() else {
- let _ = sock
- .write_all(respond("400 Bad Request", "missing code").as_bytes())
- .await;
+ respond_page(&mut sock, "400 Bad Request", &Outcome::Failed, to).await;
continue;
};
- let _ = sock
- .write_all(respond("200 OK", CALLBACK_OK).as_bytes())
- .await;
- let _ = sock.shutdown().await;
- return Ok(code);
+ return Ok((code, sock));
}
Err(Error::Unauthenticated(
"too many unexpected requests on the sign-in callback".into(),
@@ -2520,14 +2521,6 @@ mod tests {
}
}
- #[test]
- fn callback_error_text_is_html_escaped() {
- assert_eq!(
- html_escape("<script>x('a\"b')</script>&"),
- "&lt;script&gt;x(&#39;a&quot;b&#39;)&lt;/script&gt;&amp;"
- );
- }
-
#[test]
fn pkce_challenge_matches_rfc7636_appendix_b() {
assert_eq!(
diff --git a/libs/cua/crates/cua-auth/tests/flows.rs b/libs/cua/crates/cua-auth/tests/flows.rs
index 2edb1ab348..69a185c820 100644
--- a/libs/cua/crates/cua-auth/tests/flows.rs
+++ b/libs/cua/crates/cua-auth/tests/flows.rs
@@ -193,13 +193,28 @@ async fn browser_login_with_pkce_then_refresh_and_logout() {
assert!(p.user_code.is_none() && p.note.is_none());
let u = url::Url::parse(&p.url).unwrap();
let q: std::collections::HashMap<String, String> = u.query_pairs().into_owned().collect();
- let cb = format!("{}?code=code-1&state={}", q["redirect_uri"], q["state"]);
- let browser = tokio::spawn(async move { reqwest::get(cb).await.unwrap().status().as_u16() });
- let creds = tokio::time::timeout(std::time::Duration::from_secs(20), p.complete())
+ let state = q["state"].clone();
+ let redirect = q["redirect_uri"].clone();
+ let done = tokio::spawn(tokio::time::timeout(
+ std::time::Duration::from_secs(20),
+ p.complete(),
+ ));
+ // An earlier attempt's tab gets the out-of-date page and is ignored.
+ let r = reqwest::get(format!("{redirect}?code=stale-code&state=stale-state"))
.await
- .unwrap()
.unwrap();
- assert_eq!(browser.await.unwrap(), 200);
+ assert_eq!(r.status().as_u16(), 400);
+ let page = r.text().await.unwrap();
+ assert!(page.contains("out of date"), "{page}");
+ assert!(!page.contains("stale-code") && !page.contains("stale-state"));
+ let cb = format!("{redirect}?code=code-1&state={state}");
+ let r = reqwest::get(cb).await.unwrap();
+ let (status, page) = (r.status().as_u16(), r.text().await.unwrap());
+ let creds = done.await.unwrap().unwrap().unwrap();
+ assert_eq!(status, 200);
+ // The page names the account but never echoes the code or state.
+ assert!(page.contains("You're signed in") && page.contains("[email protected]"));
+ assert!(!page.contains("code-1") && !page.contains(&state), "{page}");
let id = s.install(creds).await.unwrap();
assert_eq!(id.email.as_deref(), Some("[email protected]"));
assert!(s.access_token(false).await.unwrap().contains('.'));
diff --git a/libs/cua/crates/cua-cli/src/auth.rs b/libs/cua/crates/cua-cli/src/auth.rs
index adcdaa527d..9b260b888f 100644
--- a/libs/cua/crates/cua-cli/src/auth.rs
+++ b/libs/cua/crates/cua-cli/src/auth.rs
@@ -63,7 +63,8 @@ pub async fn login(opts: &LoginOptions, out: &mut dyn Write) -> Result<i32, CuaE
// Fail before the user approves anything when the session could not be
// saved afterwards (the macOS login keychain from an SSH session).
s.store().check_writable().map_err(auth_err)?;
- let pending = s.begin_login(flow).await.map_err(auth_err)?;
+ let mut pending = s.begin_login(flow).await.map_err(auth_err)?;
+ pending.return_to = Some(cua_auth::ReturnTo::Terminal);
if let Some(note) = &pending.note {
line(out, format!("{}.", note.trim_end_matches('.')));
}
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index f2d2579a6c..bbd48f5d12 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -980,7 +980,8 @@ impl AccountTokens for SetupTokens {
/// Signs in for `cua host setup` without storing the session.
async fn sign_in_for_setup(flow: cua_auth::Flow) -> cua_host::Result<String> {
let unauth = |e: cua_auth::Error| cua_host::Error::Unauthenticated(e.to_string());
- let pending = auth::session().begin_login(flow).await.map_err(unauth)?;
+ let mut pending = auth::session().begin_login(flow).await.map_err(unauth)?;
+ pending.return_to = Some(cua_auth::ReturnTo::Terminal);
eprintln!("Sign in to cua.ai to register this machine (the session is not stored here):");
eprintln!(" {}", pending.url);
if let Some(code) = &pending.user_code {
diff --git a/libs/cua/crates/cua-cli/tests/agents_login.rs b/libs/cua/crates/cua-cli/tests/agents_login.rs
index c5dff87a6c..d3d2878d53 100644
--- a/libs/cua/crates/cua-cli/tests/agents_login.rs
+++ b/libs/cua/crates/cua-cli/tests/agents_login.rs
@@ -162,7 +162,12 @@ async fn browser_pkce_login_then_onboards_the_named_agents() {
.await
.unwrap();
assert_eq!(r.status().as_u16(), 200);
- assert!(r.text().await.unwrap().contains("Signed in to Cua"));
+ let page = r.text().await.unwrap();
+ assert!(page.contains("You're signed in") && page.contains("return to your terminal"));
+ assert!(
+ !page.contains("code-1") && !page.contains(&q["state"]),
+ "{page}"
+ );
let status = tokio::time::timeout(Duration::from_secs(60), child.wait())
.await