From 122e9911b4b6f8d6e7d6eb3cf92145f01293a47c Mon Sep 17 00:00:00 2001 From: freelw Date: Tue, 17 Nov 2026 16:50:15 +0800 Subject: [PATCH 1/2] fix: support Linux skill installation and headless login --- .github/workflows/ci.yml | 5 +- README.md | 7 ++ docs/linux-support.md | 9 ++ skills/lexmount-browser/SKILL.md | 4 +- .../references/authentication.md | 7 ++ skills/lexmount-browser/scripts/bootstrap.sh | 3 +- skills/lexmount-browser/scripts/doctor.sh | 3 +- src/auth.rs | 32 ++++++- tests/linux_bootstrap.py | 21 +++++ tests/login_linux.rs | 94 +++++++++++++++++++ 10 files changed, 174 insertions(+), 11 deletions(-) create mode 100644 docs/linux-support.md create mode 100755 tests/linux_bootstrap.py create mode 100644 tests/login_linux.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b831cae..9787a69 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,10 +56,11 @@ jobs: output="$(PATH="$test_dir/fake-path:/usr/bin:/bin" "$test_dir/skill/scripts/doctor.sh")" status=$? set -e - test "$status" -eq 2 - test "$output" = '{"ok":false,"error":"unsupported_platform","message":"This Skill supports macOS arm64 through scripts/doctor.sh and Windows x64 through scripts/doctor.ps1."}' + test "$status" -eq 1 + test "$output" = '{"ok":false,"error":"command_not_found","message":"Skill-local browser-cli is missing. Run scripts/bootstrap.sh first."}' ! grep -q 'command -v browser-cli' skills/lexmount-browser/scripts/doctor.sh ! grep -q 'Get-Command browser-cli' skills/lexmount-browser/scripts/doctor.ps1 + - run: ./tests/linux_bootstrap.py - name: Verify runtime packaging contract run: | ! grep -R -E 'python3[[:space:]]|python[[:space:]]+-m|uv[[:space:]]' scripts skills .github/workflows diff --git a/README.md b/README.md index ed99b9b..b6dc22e 100644 --- a/README.md +++ b/README.md @@ -299,3 +299,10 @@ Tencent Cloud COS through the `cos-release` GitHub environment. It requires `TENCENT_CLOUD_SECRET_ID` and `TENCENT_CLOUD_SECRET_KEY` secrets plus `COS_BUCKET`, `COS_REGION`, `COS_PUBLIC_BASE_URL`, and `COS_OBJECT_PREFIX` variables. + + +### Linux and SSH login + +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. diff --git a/docs/linux-support.md b/docs/linux-support.md new file mode 100644 index 0000000..1933119 --- /dev/null +++ b/docs/linux-support.md @@ -0,0 +1,9 @@ +# Linux support audit + +The current release builds a static Linux x86_64 musl binary, but the bundled Skill bootstrap and doctor scripts rejected Linux. Both now select the published Linux target. The doctor retains Skill-local binary isolation rather than falling back to an unrelated executable on PATH. Linux ARM64 remains unsupported by the release pipeline. + +The loopback PKCE login previously had two unusable paths on headless Linux: browser-opening failure aborted login, and `--no-open` waited without exposing the URL. Login now emits its URL and SSH callback forwarding guidance to stderr before waiting; a missing opener falls back to manual authorization. Stdout remains machine-readable final JSON. This does not automate account consent or reuse another user's credentials. + +Unrelated callbacks (including an incorrect state) no longer terminate the pending flow. The callback page acknowledges receipt and asks the user to confirm CLI completion, rather than claiming that credential exchange has already succeeded. + +Validation covers a real CLI child process, loopback callback, local mock credential exchange, missing desktop opener, no-open login, and Linux bootstrap with checksum-verified fixtures. These tests do not substitute for a human completing real website consent on a Linux desktop or SSH workstation. No release is published by this change. diff --git a/skills/lexmount-browser/SKILL.md b/skills/lexmount-browser/SKILL.md index efaeb60..3ff4d26 100644 --- a/skills/lexmount-browser/SKILL.md +++ b/skills/lexmount-browser/SKILL.md @@ -16,7 +16,7 @@ Do not infer `` from the working directory. Select the native Rust binary for the current platform: -- macOS arm64: run `sh "/scripts/bootstrap.sh"` when `/bin/browser-cli` is missing, then invoke `"/bin/browser-cli"`. +- Linux x86_64 and macOS arm64: run `sh "/scripts/bootstrap.sh"` when `/bin/browser-cli` is missing, then invoke `"/bin/browser-cli"`. - Windows x64: run `& "\scripts\bootstrap.ps1"` in PowerShell when `\bin\browser-cli.exe` is missing, then invoke `& "\bin\browser-cli.exe"`. Both bootstrap scripts download the fixed release version from Tencent Cloud COS and verify its SHA-256 digest. @@ -29,7 +29,7 @@ Do not run the binary for the other platform. Both platform binaries emit JSON. ## Setup 1. Resolve `` from this `SKILL.md` and select the matching platform paths above. -2. Run the Skill-local bootstrap script if the binary is missing. Then run `sh "/scripts/doctor.sh"` on macOS arm64. On Windows, invoke the installed binary's `doctor` command directly, not `scripts/doctor.ps1`: PowerShell uses `& "\bin\browser-cli.exe" doctor`; Bash/Git Bash uses `"/bin/browser-cli.exe" doctor` with forward slashes in the absolute path. In WorkBuddy on Windows, prefer its Bash tool when available: its PowerShell tool can return only an exit code and omit the JSON. Keep the tool's normal permissions and sandbox. +2. Run the Skill-local bootstrap script if the binary is missing. Then run `sh "/scripts/doctor.sh"` on Linux x86_64 or macOS arm64. On Windows, invoke the installed binary's `doctor` command directly, not `scripts/doctor.ps1`: PowerShell uses `& "\bin\browser-cli.exe" doctor`; Bash/Git Bash uses `"/bin/browser-cli.exe" doctor` with forward slashes in the absolute path. In WorkBuddy on Windows, prefer its Bash tool when available: its PowerShell tool can return only an exit code and omit the JSON. Keep the tool's normal permissions and sandbox. 3. If credentials are missing, run `browser-cli auth login`. Pass `--client-name ""` when the current Agent has a user-facing name; otherwise the CLI uses `Agent`. Let the user approve in their browser. Never ask them to paste an API key into chat. 4. After changing credentials, run `browser-cli doctor` again; otherwise use the doctor result already obtained. Continue only when its actual JSON reports `ready_for_browser_actions: true`. An exit code without that JSON is not a readiness result; see [Windows diagnostic output](references/troubleshooting.md#windows-diagnostic-output). diff --git a/skills/lexmount-browser/references/authentication.md b/skills/lexmount-browser/references/authentication.md index 6fb346a..797d7eb 100644 --- a/skills/lexmount-browser/references/authentication.md +++ b/skills/lexmount-browser/references/authentication.md @@ -21,3 +21,10 @@ The file is mode `0600` on Unix. The CLI redacts the API key from all JSON outpu For managed environments, the SDK also accepts `LEXMOUNT_API_KEY`, `LEXMOUNT_PROJECT_ID`, optional `LEXMOUNT_BASE_URL`, and optional `LEXMOUNT_REGION`. Do not ask users to paste secret values into an Agent chat. Use `browser-cli auth logout` to remove only the local credential file. Environment variables are managed outside the CLI. + + +### Linux and SSH login + +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. diff --git a/skills/lexmount-browser/scripts/bootstrap.sh b/skills/lexmount-browser/scripts/bootstrap.sh index 36beb4d..ec5e8f4 100755 --- a/skills/lexmount-browser/scripts/bootstrap.sh +++ b/skills/lexmount-browser/scripts/bootstrap.sh @@ -5,8 +5,9 @@ version="${LEXMOUNT_BROWSER_CLI_VERSION:-1.3.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 + Linux-x86_64) target="x86_64-unknown-linux-musl" ;; Darwin-arm64) target="aarch64-apple-darwin" ;; - *) echo "Unsupported platform: $(uname -s) $(uname -m). This release supports macOS arm64 and Windows x86_64." >&2; exit 2 ;; + *) echo "Unsupported platform: $(uname -s) $(uname -m). This release supports Linux x86_64, macOS arm64 and Windows x86_64." >&2; exit 2 ;; esac asset="browser-cli-v${version}-${target}" diff --git a/skills/lexmount-browser/scripts/doctor.sh b/skills/lexmount-browser/scripts/doctor.sh index c0f8882..f5b0bb1 100755 --- a/skills/lexmount-browser/scripts/doctor.sh +++ b/skills/lexmount-browser/scripts/doctor.sh @@ -1,8 +1,9 @@ #!/bin/sh set -eu case "$(uname -s)-$(uname -m)" in + Linux-x86_64) ;; Darwin-arm64) ;; - *) echo '{"ok":false,"error":"unsupported_platform","message":"This Skill supports macOS arm64 through scripts/doctor.sh and Windows x64 through scripts/doctor.ps1."}'; exit 2 ;; + *) echo '{"ok":false,"error":"unsupported_platform","message":"This Skill supports Linux x86_64 and macOS arm64 through scripts/doctor.sh and Windows x64 through scripts/doctor.ps1."}'; exit 2 ;; esac skill_dir="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" if [ -x "$skill_dir/bin/browser-cli" ]; then exec "$skill_dir/bin/browser-cli" doctor; fi diff --git a/src/auth.rs b/src/auth.rs index 51c1186..86d7c07 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -19,7 +19,7 @@ use crate::{Error, Result}; pub const DEFAULT_CONNECT_BASE_URL: &str = "https://browser.lexmount.cn"; pub const DEFAULT_CLIENT_NAME: &str = "Agent"; pub const DEFAULT_SCOPES: &[&str] = &["browser:sessions", "browser:contexts", "browser:actions"]; -const LOGIN_SUCCESS_PAGE: &str = "Lexmount connected

Lexmount connected

You can close this window and return to your agent.

"; +const LOGIN_SUCCESS_PAGE: &str = "Lexmount authorization received

Authorization received

Return to your agent to confirm login completed.

"; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Credentials { @@ -181,8 +181,16 @@ pub fn login_with_client_name( &state, &challenge, )?; - if open_browser { - open::that(url.as_str()).map_err(|e| Error::Io(std::io::Error::other(e)))?; + // Progress belongs on stderr so stdout remains a single command result. + eprintln!("Open this URL in a browser on this machine to authorize:\n{url}"); + eprintln!( + "For SSH, forward the callback port {} to this machine before opening the URL.", + listener.local_addr()?.port() + ); + if open_browser && let Err(error) = open::that(url.as_str()) { + eprintln!( + "Could not open a local browser ({error}). Open the URL manually; waiting for authorization." + ); } let started = Instant::now(); @@ -200,6 +208,20 @@ pub fn login_with_client_name( .ok_or_else(|| Error::Config("invalid OAuth callback request".into()))?; let callback = Url::parse(&format!("http://127.0.0.1{target}")) .map_err(|e| Error::Config(format!("invalid OAuth callback: {e}")))?; + if callback.path() != "/callback" + || callback + .query_pairs() + .find(|(key, _)| key == "state") + .map(|(_, value)| value.into_owned()) + .as_deref() + != Some(state.as_str()) + { + let _ = stream.write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + if started.elapsed() >= timeout { + return Err(Error::Timeout("OAuth callback was not received".into())); + } + continue; + } write!( stream, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", @@ -212,7 +234,7 @@ pub fn login_with_client_name( thread::sleep(Duration::from_millis(100)) } Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { - return Err(Error::Timeout("OAuth callback was not received".into())); + return Err(Error::Timeout("OAuth callback was not received. On SSH/headless Linux, open the authorization URL in your desktop browser with the callback port forwarded to this machine.".into())); } Err(e) => return Err(e.into()), } @@ -429,7 +451,7 @@ mod tests { .to_ascii_lowercase() .contains("workbuddy") ); - assert!(LOGIN_SUCCESS_PAGE.contains("return to your agent")); + assert!(LOGIN_SUCCESS_PAGE.contains("Return to your agent")); } #[test] diff --git a/tests/linux_bootstrap.py b/tests/linux_bootstrap.py new file mode 100755 index 0000000..d5cc1ef --- /dev/null +++ b/tests/linux_bootstrap.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +import tempfile,pathlib,subprocess,os,shutil +root=pathlib.Path(__file__).resolve().parents[1] / 'skills/lexmount-browser/scripts' +with tempfile.TemporaryDirectory() as t: + p=pathlib.Path(t); scripts=p/'skill/scripts';scripts.mkdir(parents=True); fake=p/'path';fake.mkdir();out=p/'install' + for n in ['bootstrap.sh','doctor.sh']:shutil.copy(root/n,scripts/n) + (fake/'uname').write_text('#!/bin/sh\ncase "$1" in -s) echo Linux;; -m) echo x86_64;; esac\n') + (fake/'curl').write_text('''#!/bin/sh +while [ "$#" -gt 0 ]; do case "$1" in https:*) url="$1";; -o) shift; output="$1";; esac; shift; done +case "$url" in + *SHA256SUMS) printf '%s %s\\n' "$(openssl dgst -sha256 "$FIXTURE" | awk '{print $NF}')" 'browser-cli-v1.3.0-x86_64-unknown-linux-musl' > "$output";; + *x86_64-unknown-linux-musl) cp "$FIXTURE" "$output";; + *) exit 9;; +esac +''') + fixture=p/'binary';fixture.write_text('#!/bin/sh\necho browser-cli-fixture\n') + for f in fake.iterdir():f.chmod(0o755) + env=dict(os.environ,PATH=str(fake)+':/usr/bin:/bin',FIXTURE=str(fixture),LEXMOUNT_BROWSER_CLI_INSTALL_DIR=str(out)) + r=subprocess.run(['sh',str(scripts/'bootstrap.sh')],env=env,capture_output=True,text=True);assert r.returncode==0,r.stderr + assert (out/'browser-cli').exists() + print('Linux bootstrap selected musl asset, verified checksum, installed and executed fixture: PASS') diff --git a/tests/login_linux.rs b/tests/login_linux.rs new file mode 100644 index 0000000..173a4a3 --- /dev/null +++ b/tests/login_linux.rs @@ -0,0 +1,94 @@ +#[allow(dead_code)] +mod support; +use httpmock::prelude::*; +use serde_json::json; +use std::{ + io::{BufRead, BufReader, Read}, + process::Stdio, +}; + +fn login_fixture(no_open: bool) { + let server = MockServer::start(); + let exchange = server.mock(|when, then| { + when.method(POST).path("/api/connect/codex/exchange"); + then.status(200).json_body(json!({"project_id":"fixture", "api_key":"fixture-secret", "api_base_url":"https://api.example.test"})); + }); + let dir = tempfile::tempdir().unwrap(); + let credentials = dir.path().join("credentials.json"); + let mut cmd = support::command( + &server.base_url(), + dir.path(), + &[ + "auth", + "login", + "--timeout-seconds", + "5", + "--connect-base-url", + &server.base_url(), + "--credentials-file", + credentials.to_str().unwrap(), + ], + ); + if no_open { + cmd.arg("--no-open"); + } else { + cmd.env("PATH", dir.path()) + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .env_remove("BROWSER"); + } + cmd.stderr(Stdio::piped()); + let mut child = cmd.spawn().unwrap(); + let mut reader = BufReader::new(child.stderr.take().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert!(line.contains("Open this URL"), "{line}"); + line.clear(); + reader.read_line(&mut line).unwrap(); + let url = url::Url::parse(line.trim()).unwrap(); + let params: std::collections::HashMap<_, _> = url.query_pairs().collect(); + let mut callback = url::Url::parse(¶ms["redirect_uri"]).unwrap(); + let http = reqwest::blocking::Client::builder() + .no_proxy() + .build() + .unwrap(); + assert_eq!(http.get(callback.clone()).send().unwrap().status(), 400); + callback + .query_pairs_mut() + .append_pair("state", ¶ms["state"]) + .append_pair("code", "test-code"); + reqwest::blocking::Client::builder() + .no_proxy() + .build() + .unwrap() + .get(callback) + .send() + .unwrap(); + let output = child.wait_with_output().unwrap(); + let mut remaining_stderr = String::new(); + reader.read_to_string(&mut remaining_stderr).unwrap(); + if !no_open { + assert!( + remaining_stderr.contains("Could not open a local browser"), + "{remaining_stderr}" + ); + } + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + assert!(!String::from_utf8_lossy(&output.stdout).contains("fixture-secret")); + assert!(credentials.exists()); + exchange.assert(); +} + +#[test] +fn manual_login_prints_url_and_completes_without_desktop() { + login_fixture(true); +} +#[cfg(target_os = "linux")] +#[test] +fn missing_desktop_opener_falls_back_to_manual_login() { + login_fixture(false); +} From d4410f2403c93bb48a17baf4b53ff279f8993710 Mon Sep 17 00:00:00 2001 From: freelw Date: Tue, 17 Nov 2026 20:30:19 +0800 Subject: [PATCH 2/2] feat: device-code login for SSH and headless Linux (#41) * feat: authorize headless terminals with device codes * fix: save credentials atomically and reject unsafe device credentials * chore: bump browser-cli and bootstrap defaults to 1.4.0 --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 23 +- .../references/authentication.md | 12 + skills/lexmount-browser/scripts/bootstrap.ps1 | 2 +- skills/lexmount-browser/scripts/bootstrap.sh | 2 +- src/auth.rs | 206 +++++++++++++++++- src/main.rs | 41 +++- tests/device_login.rs | 106 +++++++++ tests/linux_bootstrap.py | 2 +- tests/login_linux.rs | 3 +- 11 files changed, 378 insertions(+), 23 deletions(-) create mode 100644 tests/device_login.rs diff --git a/Cargo.lock b/Cargo.lock index b447e46..c83b99f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1240,7 +1240,7 @@ checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760" [[package]] name = "lexmount-browser" -version = "1.3.0" +version = "1.4.0" dependencies = [ "base64 0.22.1", "clap", diff --git a/Cargo.toml b/Cargo.toml index d748389..bc7e7b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/README.md b/README.md index b6dc22e..386b5fa 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. @@ -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. diff --git a/skills/lexmount-browser/references/authentication.md b/skills/lexmount-browser/references/authentication.md index 797d7eb..37da266 100644 --- a/skills/lexmount-browser/references/authentication.md +++ b/skills/lexmount-browser/references/authentication.md @@ -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. diff --git a/skills/lexmount-browser/scripts/bootstrap.ps1 b/skills/lexmount-browser/scripts/bootstrap.ps1 index a3385e9..5a42335 100644 --- a/skills/lexmount-browser/scripts/bootstrap.ps1 +++ b/skills/lexmount-browser/scripts/bootstrap.ps1 @@ -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" } diff --git a/skills/lexmount-browser/scripts/bootstrap.sh b/skills/lexmount-browser/scripts/bootstrap.sh index ec5e8f4..195e25d 100755 --- a/skills/lexmount-browser/scripts/bootstrap.sh +++ b/skills/lexmount-browser/scripts/bootstrap.sh @@ -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 diff --git a/src/auth.rs b/src/auth.rs index 86d7c07..7f23478 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -118,15 +118,37 @@ pub fn status(path: Option<&Path>) -> Result { pub fn save_credentials(credentials: &Credentials, path: Option<&Path>) -> Result { 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) } @@ -355,6 +377,9 @@ fn extract_api_key(payload: &Value) -> Option { .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")) @@ -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 { + 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] diff --git a/src/main.rs b/src/main.rs index c501857..c5c26b1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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, }, @@ -424,15 +430,32 @@ fn run_auth(command: AuthCommand) -> Result { 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())?})) } diff --git a/tests/device_login.rs b/tests/device_login.rs new file mode 100644 index 0000000..c4922f7 --- /dev/null +++ b/tests/device_login.rs @@ -0,0 +1,106 @@ +#[allow(dead_code)] +mod support; +use httpmock::prelude::*; +use serde_json::json; + +fn fixture(error: Option<&str>, auto: bool, mismatch: bool) { + fixture_url(error, auto, mismatch, "https://api.example.test"); +} +fn fixture_url(error: Option<&str>, auto: bool, mismatch: bool, api_url: &str) { + let server = MockServer::start(); + let create = server.mock(|when, then| { + when.method(POST).path("/api/connect/device/authorize"); + then.status(200).json_body(json!({"device_code":"private-device-secret", "user_code":"ABCD-EFGH", "verification_uri":"/connect/device", "expires_in":3,"interval":1})); + }); + let poll = server.mock(|when, then| { + when.method(POST).path("/api/connect/device/token").json_body(json!({"device_code":"private-device-secret"})); + if let Some(error) = error { + then.status(400).json_body(json!({"error":error})); + } else { + then.status(200).json_body(json!({"project_id":"fixture", "api_key":"fixture-api-secret", "api_base_url":api_url})); + } + }); + let dir = tempfile::tempdir().unwrap(); + let credential = dir.path().join("device.json"); + let mut command = support::command( + &server.base_url(), + dir.path(), + &[ + "auth", + "login", + "--connect-base-url", + &server.base_url(), + "--credentials-file", + credential.to_str().unwrap(), + ], + ); + command.env_remove("CI"); + if auto { + command.env("SSH_CONNECTION", "fixture"); + } else { + command.arg("--device"); + } + if mismatch { + command.args(["--project-id", "another-project"]); + } + let output = command.output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("ABCD-EFGH")); + for secret in ["private-device-secret", "fixture-api-secret"] { + assert!(!stdout.contains(secret)); + assert!(!stderr.contains(secret)); + } + assert_eq!( + output.status.success(), + error.is_none() && !mismatch && api_url.starts_with("https://"), + "{stdout} {stderr}" + ); + assert_eq!( + credential.exists(), + error.is_none() && !mismatch && api_url.starts_with("https://") + ); + #[cfg(unix)] + if credential.exists() { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(credential).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + create.assert(); + assert!(poll.hits() >= 1); +} +#[test] +fn device_success_saves_private_credentials() { + fixture(None, false, false); +} +#[test] +fn ssh_selects_device_flow() { + fixture(None, true, false); +} +#[test] +fn denial_does_not_save_credentials() { + fixture(Some("access_denied"), false, false); +} +#[test] +fn expiry_does_not_save_credentials() { + fixture(Some("expired_token"), false, false); +} +#[test] +fn pending_stops_at_deadline() { + fixture(Some("authorization_pending"), false, false); +} +#[test] +fn slow_down_stops_at_deadline() { + fixture(Some("slow_down"), false, false); +} +#[test] +fn project_mismatch_does_not_save_credentials() { + fixture(None, false, true); +} + +#[test] +fn plaintext_api_origin_is_rejected() { + fixture_url(None, false, false, "http://api.example.test"); +} diff --git a/tests/linux_bootstrap.py b/tests/linux_bootstrap.py index d5cc1ef..9206149 100755 --- a/tests/linux_bootstrap.py +++ b/tests/linux_bootstrap.py @@ -8,7 +8,7 @@ (fake/'curl').write_text('''#!/bin/sh while [ "$#" -gt 0 ]; do case "$1" in https:*) url="$1";; -o) shift; output="$1";; esac; shift; done case "$url" in - *SHA256SUMS) printf '%s %s\\n' "$(openssl dgst -sha256 "$FIXTURE" | awk '{print $NF}')" 'browser-cli-v1.3.0-x86_64-unknown-linux-musl' > "$output";; + *SHA256SUMS) printf '%s %s\\n' "$(openssl dgst -sha256 "$FIXTURE" | awk '{print $NF}')" 'browser-cli-v1.4.0-x86_64-unknown-linux-musl' > "$output";; *x86_64-unknown-linux-musl) cp "$FIXTURE" "$output";; *) exit 9;; esac diff --git a/tests/login_linux.rs b/tests/login_linux.rs index 173a4a3..1c31335 100644 --- a/tests/login_linux.rs +++ b/tests/login_linux.rs @@ -32,7 +32,8 @@ fn login_fixture(no_open: bool) { if no_open { cmd.arg("--no-open"); } else { - cmd.env("PATH", dir.path()) + cmd.arg("--browser") + .env("PATH", dir.path()) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") .env_remove("BROWSER");