use std::io::{BufRead, IsTerminal};
use std::time::{Duration, Instant};
use anyhow::{anyhow, Context};
use base64::Engine as _;
use serde::Deserialize;
const TENANT: &str = "login.docker.com";
const CLIENT_ID: &str = "L4v0dmlNBpYUjGGab0C2JtgTgXr1Qz4d";
const AUDIENCE: &str = "https://hub.docker.com";
fn tenant_url() -> String {
format!("https://{TENANT}")
}
fn user_agent() -> String {
format!(
"llmman:{}:{}-{}",
env!("CARGO_PKG_VERSION").replace('.', "_"),
std::env::consts::OS,
std::env::consts::ARCH,
)
}
#[derive(Deserialize)]
struct DeviceCodeResponse {
device_code: String,
user_code: String,
verification_uri_complete: String,
expires_in: u64,
interval: u64,
}
#[derive(Deserialize, Default)]
struct ErrorBody {
error_description: Option<String>,
}
#[derive(Deserialize)]
struct TokenResponse {
access_token: Option<String>,
error: Option<String>,
#[serde(default)]
error_description: String,
}
pub struct DeviceLoginResult {
pub username: String,
pub password: String,
}
pub fn login_device() -> anyhow::Result<Option<DeviceLoginResult>> {
let client = reqwest::blocking::Client::builder()
.user_agent(user_agent())
.build()
.context("build http client")?;
let state = match get_device_code(&client) {
Ok(s) if !s.user_code.is_empty() => s,
_ => return Ok(None),
};
println!();
println!("USING WEB-BASED LOGIN");
println!();
println!(
"i Info \u{2192} To sign in with credentials on the command line, use 'llmman login -u <username>'"
);
println!();
println!();
println!(
"Your one-time device confirmation code is: {}",
state.user_code
);
let display_url = state
.verification_uri_complete
.split('?')
.next()
.unwrap_or(&state.verification_uri_complete);
println!("Press ENTER to open your browser or submit your device code here: {display_url}");
println!();
println!("Waiting for authentication in the browser\u{2026}");
if std::io::stdin().is_terminal() {
let uri = state.verification_uri_complete.clone();
std::thread::spawn(move || {
let mut line = String::new();
let _ = std::io::stdin().lock().read_line(&mut line);
let _ = open_browser(&uri);
});
}
let token = wait_for_device_token(&client, &state)?;
let access_token = token
.access_token
.ok_or_else(|| anyhow!("missing access_token in device token response"))?;
let username = username_from_jwt(&access_token)
.ok_or_else(|| anyhow!("could not determine Hub username from access token"))?;
let password = get_auto_pat(&client, &access_token)?;
Ok(Some(DeviceLoginResult { username, password }))
}
fn get_device_code(client: &reqwest::blocking::Client) -> anyhow::Result<DeviceCodeResponse> {
let resp = client
.post(format!("{}/oauth/device/code", tenant_url()))
.form(&[
("client_id", CLIENT_ID),
("audience", AUDIENCE),
("scope", "openid offline_access"),
])
.timeout(Duration::from_secs(15))
.send()
.context("request device code")?;
if !resp.status().is_success() {
let status = resp.status();
let desc = resp
.json::<ErrorBody>()
.unwrap_or_default()
.error_description
.unwrap_or_default();
anyhow::bail!("unexpected response from tenant: {status} {desc}");
}
resp.json().context("parse device code response")
}
fn wait_for_device_token(
client: &reqwest::blocking::Client,
state: &DeviceCodeResponse,
) -> anyhow::Result<TokenResponse> {
let deadline = Instant::now() + Duration::from_secs(state.expires_in);
let interval = Duration::from_secs(state.interval.max(1));
loop {
std::thread::sleep(interval);
if Instant::now() >= deadline {
anyhow::bail!("timed out waiting for device token");
}
let resp = client
.post(format!("{}/oauth/token", tenant_url()))
.form(&[
("client_id", CLIENT_ID),
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
("device_code", state.device_code.as_str()),
])
.timeout(Duration::from_secs(60))
.send()
.context("poll device token")?;
let token: TokenResponse = resp.json().context("parse device token response")?;
match token.error.as_deref() {
Some("authorization_pending") => continue,
Some(_) => {
anyhow::bail!(
"failed waiting for authentication: {}",
token.error_description
);
}
None => return Ok(token),
}
}
}
fn get_auto_pat(client: &reqwest::blocking::Client, access_token: &str) -> anyhow::Result<String> {
#[derive(Deserialize)]
struct PatResponse {
data: PatData,
}
#[derive(Deserialize)]
struct PatData {
token: String,
}
let resp = client
.post("https://hub.docker.com/v2/access-tokens/desktop-generate")
.bearer_auth(access_token)
.timeout(Duration::from_secs(15))
.send()
.context("request auto-generated PAT")?;
if resp.status() != reqwest::StatusCode::CREATED {
anyhow::bail!("unexpected response from Hub: {}", resp.status());
}
let body: PatResponse = resp.json().context("parse PAT response")?;
Ok(body.data.token)
}
fn username_from_jwt(token: &str) -> Option<String> {
let payload_b64 = token.split('.').nth(1)?;
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(payload_b64)
.ok()?;
let claims: serde_json::Value = serde_json::from_slice(&payload).ok()?;
claims
.get("https://hub.docker.com")?
.get("username")?
.as_str()
.map(str::to_string)
}
fn open_browser(url: &str) -> anyhow::Result<()> {
#[cfg(target_os = "macos")]
{
std::process::Command::new("open").arg(url).status()?;
}
#[cfg(target_os = "windows")]
{
std::process::Command::new("cmd")
.args(["/C", "start", "", url])
.status()?;
}
#[cfg(all(unix, not(target_os = "macos")))]
{
for tool in ["xdg-open", "x-www-browser", "www-browser"] {
if std::process::Command::new(tool).arg(url).status().is_ok() {
break;
}
}
}
Ok(())
}