diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 4af3e7f..cc5472e 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -236,8 +236,10 @@ steel browser start ### Parameters -- `--stealth` (boolean, optional): Enable stealth mode (humanize interactions + auto CAPTCHA) -- `-p, --proxy` (string, optional): Use a residential proxy +- `--stealth` (boolean, optional): Enable stealth mode: humanized interactions, plus automatic CAPTCHA solving when your plan includes it +- `-p, --proxy` (string, optional): Route the session through your own proxy (http://user:pass@host:port) +- `--use-proxy` (boolean, optional): Use a Steel-managed residential proxy +- `--project` (string, optional): Project to create the session in, needed with an organization-wide API key. Defaults to STEEL_PROJECT_ID - `--timeout` (string, optional): Session timeout in milliseconds. Defaults to 900000 (15 minutes), which every plan allows (create-time only) - `--inactivity-timeout` (string, optional): Inactivity timeout in milliseconds: release the session when no command, CDP message, or remote input arrives for this long. Defaults to 600000 (10 minutes); pass 0 to disable (create-time only) - `--solve-captcha` (boolean, optional): Enable manual CAPTCHA solving on new sessions (create-time only) @@ -1283,6 +1285,7 @@ steel init ### Parameters - `--agent` (boolean, optional): Run in agent mode: auto-accept interactive prompts and print agent-friendly output. Designed for AI coding agents +- `--from` (string, optional): Coding client for targeted agent setup (opencode, claude-code, codex, pi) - `--skills` (string[], optional): Open the Steel skills installer flow. With no value, lets you choose skills interactively - `--no-skills` (boolean, optional): Skip Steel skill installation diff --git a/docs/references/steel-browser.md b/docs/references/steel-browser.md index 70821f3..6b08b7b 100644 --- a/docs/references/steel-browser.md +++ b/docs/references/steel-browser.md @@ -37,6 +37,8 @@ Main flags: - `--session ` - `--stealth` - `--proxy ` +- `--use-proxy` +- `--project ` - `--timeout ` - `--inactivity-timeout ` (default 600000; `0` turns it off) - `--solve-captcha` @@ -52,11 +54,20 @@ Flag semantics: - `stealthConfig.humanizeInteractions = true` - `stealthConfig.autoCaptchaSolving = true` - `solveCaptcha = true` + - If the plan refuses CAPTCHA solving (`plan_feature_unavailable` or + `deposit_required`), the session starts again without it and the output + carries a note in `data.notes`. Interactions are still humanized. - `--solve-captcha` enables manual CAPTCHA solving for new sessions: - `solveCaptcha = true` - `stealthConfig.autoCaptchaSolving` is not forced on -- `--proxy ` sets `proxyUrl` on session creation. The Sessions API may return - `proxySource: "external"` rather than echoing the proxy URL in responses. + - If the plan refuses it, the command fails. It is never dropped. +- `--proxy ` sets `proxyUrl` on session creation (your own proxy). It must be + a URL. The Sessions API may return `proxySource: "external"` rather than + echoing the proxy URL in responses. +- `--use-proxy` sets `useProxy = true` (a Steel residential proxy). + `--proxy residential` is read the same way, with a note. +- `--project ` sets `projectId`. An organization-wide API key needs it. + `STEEL_PROJECT_ID` sets it when the flag is absent. - `--namespace ` sets the credential namespace for the session. Credentials stored under this namespace will be available for injection. - `--credentials` enables credential injection for the session. Sends diff --git a/src/api/client.rs b/src/api/client.rs index 6322e52..959b402 100644 --- a/src/api/client.rs +++ b/src/api/client.rs @@ -49,6 +49,15 @@ pub enum ApiError { } impl ApiError { + pub fn body_str(&self, key: &str) -> Option<&str> { + match self { + Self::RequestFailed { + body: Some(body), .. + } => body.get(key).and_then(Value::as_str), + _ => None, + } + } + /// Check if this is a 404/410 (not found). Matches TS `isNotFoundApiError()`. pub const fn is_not_found(&self) -> bool { matches!(self, Self::RequestFailed { status, .. } if *status == 404 || *status == 410) diff --git a/src/api/session.rs b/src/api/session.rs index dc0bcef..e9f88bc 100644 --- a/src/api/session.rs +++ b/src/api/session.rs @@ -11,10 +11,13 @@ use crate::config::settings::ApiMode; const CLOUD_CONNECT_URL: &str = "wss://connect.steel.dev"; const CLOUD_VIEWER_URL: &str = "https://app.steel.dev/sessions"; -#[derive(Debug, Default)] +#[derive(Debug, Default, Clone)] pub struct CreateSessionOptions { pub stealth: bool, + pub stealth_without_captcha: bool, pub proxy_url: Option, + pub use_proxy: bool, + pub project_id: Option, pub timeout_ms: Option, pub inactivity_timeout_ms: Option, pub headless: Option, @@ -131,7 +134,12 @@ fn build_create_body(options: &CreateSessionOptions) -> Value { } } - if options.stealth { + if options.stealth && options.stealth_without_captcha { + obj.insert( + "stealthConfig".into(), + json!({"humanizeInteractions": true}), + ); + } else if options.stealth { obj.insert( "stealthConfig".into(), json!({"humanizeInteractions": true, "autoCaptchaSolving": true}), @@ -139,6 +147,17 @@ fn build_create_body(options: &CreateSessionOptions) -> Value { obj.insert("solveCaptcha".into(), json!(true)); } + if options.use_proxy { + obj.insert("useProxy".into(), json!(true)); + } + + if let Some(ref project_id) = options.project_id { + let trimmed = project_id.trim(); + if !trimmed.is_empty() { + obj.insert("projectId".into(), json!(trimmed)); + } + } + if options.solve_captcha { obj.insert("solveCaptcha".into(), json!(true)); } @@ -386,6 +405,29 @@ mod tests { assert!(body["stealthConfig"].is_object()); } + #[test] + fn create_body_stealth_without_captcha_keeps_humanizing_only() { + let body = build_create_body(&CreateSessionOptions { + stealth: true, + stealth_without_captcha: true, + ..Default::default() + }); + assert_eq!( + body, + json!({"stealthConfig": {"humanizeInteractions": true}}) + ); + } + + #[test] + fn create_body_steel_proxy_and_project() { + let body = build_create_body(&CreateSessionOptions { + use_proxy: true, + project_id: Some(" p-1 ".into()), + ..Default::default() + }); + assert_eq!(body, json!({"useProxy": true, "projectId": "p-1"})); + } + #[test] fn create_body_all_fields() { let body = build_create_body(&CreateSessionOptions { diff --git a/src/commands/browser/start.rs b/src/commands/browser/start.rs index 154e9ac..49ea55b 100644 --- a/src/commands/browser/start.rs +++ b/src/commands/browser/start.rs @@ -1,7 +1,7 @@ use clap::Parser; use serde_json::json; -use crate::api::client::SteelClient; +use crate::api::client::{ApiError, SteelClient}; use crate::api::session::CreateSessionOptions; use crate::browser::profile_store; use crate::browser::state::{self, BrowserSession}; @@ -13,14 +13,22 @@ pub const DEFAULT_INACTIVITY_TIMEOUT_MS: u64 = 600_000; #[derive(Parser)] pub struct Args { - /// Enable stealth mode (humanize interactions + auto CAPTCHA) + /// Enable stealth mode: humanized interactions, plus automatic CAPTCHA solving when your plan includes it #[arg(long)] pub stealth: bool, - /// Use a residential proxy - #[arg(short = 'p', long)] + /// Route the session through your own proxy (http://user:pass@host:port) + #[arg(short = 'p', long, value_name = "URL", conflicts_with = "use_proxy")] pub proxy: Option, + /// Use a Steel-managed residential proxy + #[arg(long = "use-proxy")] + pub use_proxy: bool, + + /// Project to create the session in, needed with an organization-wide API key. Defaults to STEEL_PROJECT_ID + #[arg(long, value_name = "ID")] + pub project: Option, + /// Session timeout in milliseconds. Defaults to 900000 (15 minutes), which every plan allows (create-time only) #[arg(long, alias = "session-timeout")] pub timeout: Option, @@ -66,10 +74,69 @@ pub fn default_options() -> CreateSessionOptions { CreateSessionOptions { timeout_ms: Some(DEFAULT_TIMEOUT_MS), inactivity_timeout_ms: Some(DEFAULT_INACTIVITY_TIMEOUT_MS), + project_id: project_from_env(), ..Default::default() } } +fn project_from_env() -> Option { + std::env::var("STEEL_PROJECT_ID") + .ok() + .filter(|value| !value.trim().is_empty()) +} + +#[derive(Debug, PartialEq, Eq)] +struct ProxyChoice { + url: Option, + steel: bool, + aliased: bool, +} + +const PROXY_URL_REQUIRED: &str = "--proxy takes a proxy URL such as http://user:pass@host:port. For a Steel residential proxy, use --use-proxy."; + +fn resolve_proxy(proxy: Option, use_proxy: bool) -> anyhow::Result { + let Some(value) = proxy + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + else { + return Ok(ProxyChoice { + url: None, + steel: use_proxy, + aliased: false, + }); + }; + if value.eq_ignore_ascii_case("residential") || value.eq_ignore_ascii_case("steel") { + return Ok(ProxyChoice { + url: None, + steel: true, + aliased: true, + }); + } + match url::Url::parse(&value) { + Ok(url) if url.has_host() => Ok(ProxyChoice { + url: Some(value), + steel: use_proxy, + aliased: false, + }), + _ => Err(invalid_input(PROXY_URL_REQUIRED)), + } +} + +fn captcha_refusal(err: &anyhow::Error, options: &CreateSessionOptions) -> Option<&'static str> { + if !options.stealth || options.solve_captcha || options.stealth_without_captcha { + return None; + } + let api = err.downcast_ref::()?; + if api.body_str("param") != Some("solveCaptcha") { + return None; + } + match api.body_str("code")? { + "plan_feature_unavailable" => Some("your plan does not include CAPTCHA solving"), + "deposit_required" => Some("CAPTCHA solving needs a paid balance on your plan"), + _ => None, + } +} + fn now_ms() -> Option { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -109,6 +176,15 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { ))); } let session_metadata = metadata::collect(args.metadata)?; + let proxy = resolve_proxy(args.proxy, args.use_proxy)?; + let mut notes = Vec::new(); + if proxy.aliased { + notes.push( + "--proxy takes a proxy URL, so a Steel residential proxy (--use-proxy) is used instead." + .to_string(), + ); + } + let project_id = args.project.or_else(project_from_env); let mut resolved_profile_id = None; let mut stored_browser_profile = None; @@ -129,7 +205,7 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { } let persist_profile = args.profile.is_some() && args.update_profile; - let proxy_enabled = args.proxy.is_some(); + let proxy_enabled = proxy.url.is_some() || proxy.steel; let namespace_set = args.namespace.is_some(); let metadata_set = !session_metadata.is_empty(); let timeout = args.timeout.unwrap_or(DEFAULT_TIMEOUT_MS); @@ -166,7 +242,10 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { let options = CreateSessionOptions { stealth: args.stealth, - proxy_url: args.proxy, + stealth_without_captcha: false, + proxy_url: proxy.url, + use_proxy: proxy.steel, + project_id: project_id.clone(), timeout_ms: Some(timeout), inactivity_timeout_ms, headless: args.headless, @@ -179,7 +258,24 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { metadata: session_metadata, }; - let (created, connect_url) = create(&client, &session_name, &options).await?; + let mut captcha_dropped = false; + let (created, connect_url) = match create(&client, &session_name, &options).await { + Ok(done) => done, + Err(err) => { + let Some(reason) = captcha_refusal(&err, &options) else { + return Err(err); + }; + captcha_dropped = true; + notes.push(format!( + "Started without CAPTCHA solving because {reason}. Interactions are still humanized." + )); + let without_captcha = CreateSessionOptions { + stealth_without_captcha: true, + ..options.clone() + }; + create(&client, &session_name, &without_captcha).await? + } + }; if let Some(ref profile_name) = args.profile && let Some(ref returned_profile_id) = created.profile_id @@ -195,6 +291,9 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { let mut properties = serde_json::Map::new(); properties.insert("stealth".into(), json!(args.stealth)); properties.insert("proxy_enabled".into(), json!(proxy_enabled)); + properties.insert("use_proxy".into(), json!(proxy.steel)); + properties.insert("project_set".into(), json!(project_id.is_some())); + properties.insert("stealth_captcha_dropped".into(), json!(captcha_dropped)); properties.insert("has_profile".into(), json!(args.profile.is_some())); properties.insert("persist_profile".into(), json!(persist_profile)); properties.insert("credentials".into(), json!(args.credentials)); @@ -204,7 +303,10 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { properties.insert("inactivity_timeout_ms".into(), json!(inactivity_timeout_ms)); crate::telemetry::track_event("browser_session_started", properties); - display_session_info(&created, connect_url.as_deref(), replaced.as_ref()); + for note in ¬es { + eprintln!("note: {note}"); + } + display_session_info(&created, connect_url.as_deref(), replaced.as_ref(), ¬es); Ok(()) } @@ -213,6 +315,7 @@ fn display_session_info( info: &BrowserSession, connect_url: Option<&str>, replaced: Option<&(String, bool)>, + notes: &[String], ) { let remaining = remaining_time_str(info); @@ -238,6 +341,9 @@ fn display_session_info( if let Some(ms) = info.inactivity_timeout_ms { data["inactivityTimeoutMs"] = json!(ms); } + if !notes.is_empty() { + data["notes"] = json!(notes); + } output::success_data(data); } else { println!("id: {}", info.id); diff --git a/src/util/output.rs b/src/util/output.rs index ab3ff2a..7716d4f 100644 --- a/src/util/output.rs +++ b/src/util/output.rs @@ -224,11 +224,14 @@ const fn class( const NETWORK_HINT: Option<&str> = Some("Check your network connection."); const LOCAL_STATE_HINT: Option<&str> = Some("Delete the file and retry."); +const PROJECT_HINT: Option<&str> = Some( + "This API key covers the whole organization. Pass --project to steel browser start, or set STEEL_PROJECT_ID.", +); const LOGIN_HINT: Option<&str> = Some( "If an agent runs this command, show the URL and code to the user and retry after they approve. STEEL_API_KEY also works.", ); -const fn classify_api(err: &crate::api::client::ApiError) -> ErrorClass { +fn classify_api(err: &crate::api::client::ApiError) -> ErrorClass { use crate::api::client::ApiError; match err { ApiError::DeviceAuth(_) => class( @@ -255,6 +258,14 @@ const fn classify_api(err: &crate::api::client::ApiError) -> ErrorClass { "api_redirect_refused", NETWORK_HINT, ), + ApiError::RequestFailed { .. } if err.body_str("code") == Some("project_required") => { + class( + exit_code::API_CLIENT, + "request_failed", + "api_request_failed", + PROJECT_HINT, + ) + } ApiError::RequestFailed { status, .. } => match *status { 401 => class( exit_code::AUTH, diff --git a/tests/browser_commands.rs b/tests/browser_commands.rs index 3ea1040..83e0835 100644 --- a/tests/browser_commands.rs +++ b/tests/browser_commands.rs @@ -828,3 +828,174 @@ async fn batch_sends_one_request() { ); assert_eq!(cli.state("s").unwrap()["snapshot"]["compact"], true); } + +async fn session_bodies(server: &MockServer) -> Vec { + server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/sessions") + .map(|r| serde_json::from_slice(&r.body).unwrap()) + .collect() +} + +async fn refuse_captcha(server: &MockServer, code: &str) { + Mock::given(method("POST")) + .and(path("/v1/sessions")) + .and(body_partial_json(json!({"solveCaptcha": true}))) + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error": "Bad Request", + "code": code, + "message": "Captcha solving is not available on the hobby plan.", + "param": "solveCaptcha" + }))) + .with_priority(1) + .mount(server) + .await; +} + +async fn accept_sessions(server: &MockServer) { + Mock::given(method("POST")) + .and(path("/v1/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(session_json())) + .with_priority(2) + .mount(server) + .await; +} + +#[tokio::test] +async fn stealth_starts_without_captcha_when_the_plan_refuses_it() { + for code in ["plan_feature_unavailable", "deposit_required"] { + let server = MockServer::start().await; + refuse_captcha(&server, code).await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let started = cli.run(&["browser", "start", "--stealth"]).await; + assert!(started.status.success(), "{started:?}"); + let out = json_out(&started); + assert_eq!(out["data"]["id"], ID); + assert!( + out["data"]["notes"][0] + .as_str() + .is_some_and(|note| note.contains("without CAPTCHA solving")) + ); + assert!(String::from_utf8_lossy(&started.stderr).contains("without CAPTCHA solving")); + let bodies = session_bodies(&server).await; + assert_eq!(bodies.len(), 2); + assert_eq!(bodies[0]["solveCaptcha"], true); + assert!(bodies[1].get("solveCaptcha").is_none()); + assert_eq!( + bodies[1]["stealthConfig"], + json!({"humanizeInteractions": true}) + ); + } +} + +#[tokio::test] +async fn an_explicit_captcha_request_is_never_dropped() { + let server = MockServer::start().await; + refuse_captcha(&server, "plan_feature_unavailable").await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let refused = cli + .run(&["browser", "start", "--stealth", "--solve-captcha"]) + .await; + assert!(!refused.status.success()); + assert_eq!(json_out(&refused)["error_code"], "request_failed"); + assert_eq!(session_bodies(&server).await.len(), 1); + assert!(cli.state("default").is_none()); +} + +#[tokio::test] +async fn proxy_takes_a_url_and_residential_means_a_steel_proxy() { + let server = MockServer::start().await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let aliased = cli + .run(&["browser", "start", "--proxy", "residential"]) + .await; + assert!(aliased.status.success(), "{aliased:?}"); + assert!( + json_out(&aliased)["data"]["notes"][0] + .as_str() + .is_some_and(|note| note.contains("--use-proxy")) + ); + + let steel = cli.run(&["browser", "start", "--use-proxy"]).await; + assert!(steel.status.success(), "{steel:?}"); + + let own = cli + .run(&[ + "browser", + "start", + "-p", + "http://user:pass@proxy.example:8080", + ]) + .await; + assert!(own.status.success(), "{own:?}"); + + let bodies = session_bodies(&server).await; + assert_eq!(bodies.len(), 3); + assert_eq!(bodies[0]["useProxy"], true); + assert!(bodies[0].get("proxyUrl").is_none()); + assert_eq!(bodies[1]["useProxy"], true); + assert_eq!(bodies[2]["proxyUrl"], "http://user:pass@proxy.example:8080"); + assert!(bodies[2].get("useProxy").is_none()); + + for value in ["proxy.example:8080", "not a url"] { + let invalid = cli.run(&["browser", "start", "--proxy", value]).await; + assert_eq!(json_out(&invalid)["error_code"], "invalid_input", "{value}"); + } + assert_eq!(session_bodies(&server).await.len(), 3); +} + +#[tokio::test] +async fn project_comes_from_the_flag_or_steel_project_id() { + let server = MockServer::start().await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let flagged = cli.run(&["browser", "start", "--project", "p-flag"]).await; + assert!(flagged.status.success(), "{flagged:?}"); + + let from_env = cli + .command(cli.config.path(), &["browser", "start"]) + .env("STEEL_PROJECT_ID", "p-env") + .output() + .await + .unwrap(); + assert!(from_env.status.success(), "{from_env:?}"); + + let bodies = session_bodies(&server).await; + assert_eq!(bodies[0]["projectId"], "p-flag"); + assert_eq!(bodies[1]["projectId"], "p-env"); +} + +#[tokio::test] +async fn an_organization_key_without_a_project_points_at_the_project_option() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1/sessions")) + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error": "Bad Request", + "code": "project_required", + "message": "This API key is scoped to the whole organization, so it binds to no project. Pass projectId to say which project this request is for.", + "param": "projectId" + }))) + .mount(&server) + .await; + let cli = Cli::new(&server); + + let refused = cli.run(&["browser", "start"]).await; + let out = json_out(&refused); + assert_eq!(out["error_code"], "request_failed"); + assert!( + out["hint"] + .as_str() + .is_some_and(|hint| hint.contains("--project")) + ); +} diff --git a/tests/cli_compat.rs b/tests/cli_compat.rs index 6cddf4e..c2a8bf9 100644 --- a/tests/cli_compat.rs +++ b/tests/cli_compat.rs @@ -293,6 +293,8 @@ fn browser_start_flags() { &[ flag("stealth"), flag_val_short("proxy", 'p'), + flag("use-proxy"), + flag_val("project"), flag_val("timeout"), flag_val("inactivity-timeout"), flag("solve-captcha"),