Skip to content
Merged
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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "lexmount-browser"
version = "1.3.0"
version = "1.4.0"
edition = "2024"
license = "MIT"
description = "Native Rust SDK and CLI for Lexmount cloud browsers"
Expand Down
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,8 @@ automatic action retries. These changes require a new CLI release; published
Explicit page selection is introduced in version 1.2.0. Check that the installed
binary's `browser-cli action --help` lists `--target-id`; the published 1.1.15
binary does not have it. The package version and both bootstrap scripts target
1.3.0 together. Merging or building this source does not publish release assets:
bootstrap can install 1.3.0 only after its binaries and checksums are published
1.4.0 together. Merging or building this source does not publish release assets:
bootstrap can install 1.4.0 only after its binaries and checksums are published
to COS. Until then, use a source build for local verification.

Every `action` command accepts an optional `--target-id`. Obtain the page's CDP
Expand Down Expand Up @@ -263,7 +263,7 @@ overwrite an existing release with changed binaries.
`skills/lexmount-browser/scripts/bootstrap.ps1` and `bootstrap.sh`.
2. Run `.github/scripts/test-release-version.ps1` with Windows PowerShell 5.1
or PowerShell 7, then `.github/scripts/verify-release-version.ps1 -ReleaseTag
v1.3.0` (substitute the intended version). Complete CI and merge the PR.
v1.4.0` (substitute the intended version). Complete CI and merge the PR.
3. Create the matching tag **on that merged commit**. Typing a new tag or
release title in GitHub does not update any source version. The release
workflow rejects inconsistent versions before building, signing or uploading.
Expand Down Expand Up @@ -306,3 +306,20 @@ variables.
Linux x86_64 uses the static musl release and the same `scripts/bootstrap.sh` and `scripts/doctor.sh` as macOS. Linux ARM64 is not currently a published target.

`browser-cli auth login --no-open` prints the authorization URL on stderr and waits for the callback; stdout remains the final JSON result. The default login attempts to open a browser, but keeps waiting if the desktop opener is missing. On a headless/SSH host, forward the printed callback port from your desktop using `ssh -L PORT:127.0.0.1:PORT HOST`, then open the printed URL on your desktop. Keep the login process running until it completes. Do not post authorization URLs or credentials in chat.

### Device login for SSH / headless Linux

`browser-cli auth login --device` prints a console address and short code. Open it
on a phone or another computer, sign in, enter the code and approve the request.
The terminal polls over HTTPS and saves credentials automatically (0600 on Unix).
No inbound port or SSH forwarding is required. The console must have device-login
support deployed before using this mode.

`auth login` automatically selects device mode over SSH or on Linux without
DISPLAY/WAYLAND_DISPLAY. Use `--browser` to force local loopback login; `--no-open`
retains manual loopback behavior. CI should supply credentials instead of starting
interactive login; explicit `--device` is available when a human is present.
`--project-id` verifies the approved account's project before saving credentials.
An expired, denied or consumed request requires a new login; API keys are never
printed. Ctrl+C stops polling. The console authorization request expires in ten
minutes even if the terminal is closed.
12 changes: 12 additions & 0 deletions skills/lexmount-browser/references/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,15 @@ Use `browser-cli auth logout` to remove only the local credential file. Environm
Linux x86_64 uses the static musl release and the same `scripts/bootstrap.sh` and `scripts/doctor.sh` as macOS. Linux ARM64 is not currently a published target.

`browser-cli auth login --no-open` prints the authorization URL on stderr and waits for the callback; stdout remains the final JSON result. The default login attempts to open a browser, but keeps waiting if the desktop opener is missing. On a headless/SSH host, forward the printed callback port from your desktop using `ssh -L PORT:127.0.0.1:PORT HOST`, then open the printed URL on your desktop. Keep the login process running until it completes. Do not post authorization URLs or credentials in chat.

## Device authorization

Use `browser-cli auth login --device` on a machine without a desktop browser.
Ask the human to open the displayed console URL on another device and enter the
short code. The CLI waits for explicit approval, then stores the credential. Never
ask them to send their password or API key in chat. This requires the console's
`/api/connect/device/authorize` and `/api/connect/device/token` endpoints.

SSH and headless Linux choose this automatically; `--browser` forces loopback
login, while `--no-open` preserves manual loopback login. CI should use preconfigured
credentials. Denial or expiry stops login; do not silently retry a denied request.
2 changes: 1 addition & 1 deletion skills/lexmount-browser/scripts/bootstrap.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function Invoke-Tls12Download {
}
}

$version = if ($env:LEXMOUNT_BROWSER_CLI_VERSION) { $env:LEXMOUNT_BROWSER_CLI_VERSION } else { "1.3.0" }
$version = if ($env:LEXMOUNT_BROWSER_CLI_VERSION) { $env:LEXMOUNT_BROWSER_CLI_VERSION } else { "1.4.0" }
$downloadBaseUrl = if ($env:LEXMOUNT_BROWSER_CLI_DOWNLOAD_BASE_URL) { $env:LEXMOUNT_BROWSER_CLI_DOWNLOAD_BASE_URL.TrimEnd('/') } else { "https://cli-bin-1377899528.cos.ap-nanjing.myqcloud.com/releases/browser-cli" }
$architecture = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
if ($architecture -ne "AMD64") { throw "Only Windows x64 is supported" }
Expand Down
2 changes: 1 addition & 1 deletion skills/lexmount-browser/scripts/bootstrap.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu

version="${LEXMOUNT_BROWSER_CLI_VERSION:-1.3.0}"
version="${LEXMOUNT_BROWSER_CLI_VERSION:-1.4.0}"
download_base_url="${LEXMOUNT_BROWSER_CLI_DOWNLOAD_BASE_URL:-https://cli-bin-1377899528.cos.ap-nanjing.myqcloud.com/releases/browser-cli}"
repo="${download_base_url%/}/v${version}"
case "$(uname -s)-$(uname -m)" in
Expand Down
206 changes: 201 additions & 5 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,37 @@ pub fn status(path: Option<&Path>) -> Result<CredentialStatus> {

pub fn save_credentials(credentials: &Credentials, path: Option<&Path>) -> Result<PathBuf> {
let path = credentials_path(path)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
// Never truncate through a symlink or expose a newly written key under the
// process umask before chmod. Rename a private file in the same directory.
if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(Error::Config(
"Refusing to save credentials through a symlink".into(),
));
}
fs::write(&path, serde_json::to_vec_pretty(credentials)?)?;
let temporary = parent.join(format!(".browser-cli-{}.tmp", random_urlsafe(16)));
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let result = (|| -> std::io::Result<()> {
let mut file = options.open(&temporary)?;
file.write_all(&serde_json::to_vec_pretty(credentials)?)?;
file.sync_all()?;
drop(file);
fs::rename(&temporary, &path)
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result?;
Ok(path)
}

Expand Down Expand Up @@ -355,6 +377,9 @@ fn extract_api_key(payload: &Value) -> Option<Credentials> {
.or_else(|| payload.get("api_key"))
.and_then(Value::as_str);
if let (Some(project_id), Some(api_key)) = (project_id, api_key) {
if project_id.trim().is_empty() || api_key.trim().is_empty() {
continue;
}
let scopes = value
.get("scopes")
.or_else(|| value.get("scope"))
Expand Down Expand Up @@ -405,8 +430,179 @@ fn is_internal_api_base_url(value: &str) -> bool {
host.contains(".svc.") || host.ends_with(".svc") || host.ends_with(".cluster.local")
}

/// Device authorization needs only outbound HTTPS; no loopback listener or opener.
pub fn device_login(
project_id: Option<&str>,
client_name: &str,
connect_base_url: &str,
timeout: Duration,
path: Option<&Path>,
) -> Result<Value> {
let base = Url::parse(connect_base_url).map_err(|e| Error::Config(e.to_string()))?;
let loopback = matches!(base.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"));
if base.scheme() != "https" && !(base.scheme() == "http" && loopback) {
return Err(Error::Config("device login requires HTTPS".into()));
}
let started = Instant::now();
let client = reqwest::blocking::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(15))
.build()?;
let response = client
.post(base.join("/api/connect/device/authorize").unwrap())
.json(&json!({"client_name":client_name}))
.send()?;
if !response.status().is_success() {
return Err(Error::Authentication(format!(
"Device login could not start (HTTP {}). The console must support device authorization.",
response.status()
)));
}
let payload: Value = response.json()?;
let secret = payload["device_code"]
.as_str()
.filter(|s| !s.is_empty())
.ok_or_else(|| Error::Authentication("Missing device code".into()))?;
let code = payload["user_code"]
.as_str()
.ok_or_else(|| Error::Authentication("Missing user code".into()))?;
let verify = base
.join(
payload["verification_uri"]
.as_str()
.unwrap_or("/connect/device"),
)
.map_err(|e| Error::Config(e.to_string()))?;
if verify.origin() != base.origin() {
return Err(Error::Authentication(
"Verification page must use the selected console origin".into(),
));
}
let lifetime = timeout.min(Duration::from_secs(
payload["expires_in"].as_u64().unwrap_or(600),
));
let mut interval = payload["interval"].as_u64().unwrap_or(5).max(1);
eprintln!(
"Open on your phone or another computer: {verify}\nEnter code: {code}\nWaiting for approval ({} seconds). Ctrl+C to cancel.",
lifetime.as_secs()
);
loop {
let remaining = lifetime.saturating_sub(started.elapsed());
if remaining.is_zero() {
return Err(Error::Timeout(
"Device authorization expired; run auth login again".into(),
));
}
thread::sleep(Duration::from_secs(interval).min(remaining));
let remaining = lifetime.saturating_sub(started.elapsed());
if remaining.is_zero() {
continue;
}
let response = match client
.post(base.join("/api/connect/device/token").unwrap())
.timeout(remaining.min(Duration::from_secs(15)))
.json(&json!({"device_code":secret}))
.send()
{
Ok(response) => response,
Err(error) if error.is_timeout() || error.is_connect() => {
interval = interval.saturating_mul(2).min(30);
continue;
}
Err(error) => return Err(error.into()),
};
let status = response.status();
if status.is_server_error() {
interval = interval.saturating_mul(2).min(30);
continue;
}
let payload: Value = response.json()?;
if !status.is_success() {
match payload["error"].as_str() {
Some("authorization_pending") => continue,
Some("slow_down") => {
interval = interval.saturating_add(5);
continue;
}
Some("access_denied") => {
return Err(Error::Authentication("Device authorization denied".into()));
}
Some("expired_token") => {
return Err(Error::Authentication(
"Device authorization expired; run auth login again".into(),
));
}
_ => {
return Err(Error::Authentication(
"Device authorization failed; run auth login again".into(),
));
}
}
}
let mut credential = extract_api_key(&payload)
.ok_or_else(|| Error::Authentication("Invalid device credential response".into()))?;
if project_id.is_some_and(|id| id != credential.project_id) {
return Err(Error::Authentication(
"Authorized project does not match --project-id; credentials were not saved".into(),
));
}
if is_internal_api_base_url(&credential.api_base_url)
|| Url::parse(&credential.api_base_url).map_or(true, |u| {
u.scheme() != "https"
|| u.host_str().is_none()
|| !u.username().is_empty()
|| u.password().is_some()
})
{
return Err(Error::Authentication("Invalid device API base URL".into()));
}
credential.connect_base_url = Some(connect_base_url.trim_end_matches('/').to_owned());
let saved = save_credentials(&credential, path)?;
return Ok(
json!({"authenticated":true,"credentials_saved":true,"credentials_file":saved,
"project_id":credential.project_id,"api_base_url":credential.api_base_url,"api_key_redacted":true}),
);
}
}

pub fn prefers_device_login() -> bool {
std::env::var_os("SSH_CONNECTION").is_some()
|| std::env::var_os("SSH_TTY").is_some()
|| (cfg!(target_os = "linux")
&& std::env::var_os("DISPLAY").is_none()
&& std::env::var_os("WAYLAND_DISPLAY").is_none())
}

#[cfg(test)]
mod tests {
#[test]
#[cfg(unix)]
fn credential_save_rejects_symlink_and_replaces_file_privately() {
use std::os::unix::{fs::PermissionsExt, fs::symlink};
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("target");
std::fs::write(&target, "original").unwrap();
let link = dir.path().join("credentials");
symlink(&target, &link).unwrap();
let credentials =
super::extract_api_key(&serde_json::json!({"project_id":"p","api_key":"secret"}))
.unwrap();
assert!(super::save_credentials(&credentials, Some(&link)).is_err());
assert_eq!(std::fs::read_to_string(&target).unwrap(), "original");
super::save_credentials(&credentials, Some(&target)).unwrap();
assert_eq!(
std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
0o600
);
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2);
}
#[test]
fn empty_credentials_are_rejected() {
assert!(
super::extract_api_key(&serde_json::json!({"project_id":"", "api_key":""})).is_none()
);
}

use super::*;

#[test]
Expand Down
41 changes: 32 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,16 @@ enum AuthCommand {
client_name: String,
#[arg(long, default_value = auth::DEFAULT_CONNECT_BASE_URL)]
connect_base_url: String,
#[arg(long, default_value_t = 300)]
#[arg(long, default_value_t = 600)]
timeout_seconds: u64,
#[arg(long)]
no_open: bool,
/// Authorize on another device, without a local browser.
#[arg(long, conflicts_with_all = ["no_open", "browser"])]
device: bool,
/// Force local browser / loopback login even over SSH.
#[arg(long)]
browser: bool,
#[arg(long)]
credentials_file: Option<PathBuf>,
},
Expand Down Expand Up @@ -424,15 +430,32 @@ fn run_auth(command: AuthCommand) -> Result<Value> {
connect_base_url,
timeout_seconds,
no_open,
device,
browser,
credentials_file,
} => auth::login_with_client_name(
project_id.as_deref(),
&client_name,
&connect_base_url,
Duration::from_secs(timeout_seconds),
!no_open,
credentials_file.as_deref(),
),
} => {
if device || (!no_open && !browser && auth::prefers_device_login()) {
if !device && std::env::var_os("CI").is_some() {
return Err(Error::Authentication("Configure credentials for CI, or explicitly request interactive --device login".into()));
}
auth::device_login(
project_id.as_deref(),
&client_name,
&connect_base_url,
Duration::from_secs(timeout_seconds),
credentials_file.as_deref(),
)
} else {
auth::login_with_client_name(
project_id.as_deref(),
&client_name,
&connect_base_url,
Duration::from_secs(timeout_seconds),
!no_open,
credentials_file.as_deref(),
)
}
}
AuthCommand::Logout { credentials_file } => {
Ok(json!({"removed":auth::logout(credentials_file.as_deref())?}))
}
Expand Down
Loading
Loading