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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
308 changes: 256 additions & 52 deletions src/auth.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -597,7 +597,6 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), interactive)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -619,28 +618,13 @@ async fn run_login_set(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
}
}

save_profile_secret(&profile_name, &api_key)?;
let _ = delete_profile_oauth_refresh_token(&profile_name);
let _ = delete_profile_oauth_access_token(&profile_name);

let stored_api_url = Some(selected_api_url.clone());
let stored_app_url = base.app_url.clone();

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: stored_api_url,
app_url: stored_app_url,
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(&api_key)),
},
);
save_auth_store(&store)?;
commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url.clone(),
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand DownExpand Up@@ -747,7 +731,6 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
let selected_org = select_login_org(login_orgs.clone(), base.org_name.as_deref(), true)?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let mut store = load_auth_store()?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
Expand All@@ -767,32 +750,14 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
bail!("login cancelled");
}

let refresh_token = oauth_tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(&profile_name, refresh_token)?;
save_profile_oauth_access_token(&profile_name, &oauth_tokens.access_token)?;
let _ = delete_profile_secret(&profile_name);
let oauth_access_expires_at = determine_oauth_access_expiry_epoch(&oauth_tokens);
let jwt_id = decode_jwt_identity(&oauth_tokens.access_token);

store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(selected_api_url.clone()),
app_url: Some(app_url.clone()),
org_name: selected_org.as_ref().map(|org| org.name.clone()),
oauth_client_id: Some(client_id.clone()),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)?;
commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url.clone(),
app_url.clone(),
client_id.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

if let Some(org) = selected_org.as_ref() {
ui::print_command_status(
Expand All@@ -816,6 +781,199 @@ async fn run_login_oauth(base: &BaseArgs, args: AuthLoginArgs) -> Result<()> {
Ok(())
}

pub async fn login_interactive(base: &mut BaseArgs) -> Result<String> {
let methods = ["OAuth (browser)", "API key"];
let selected = ui::fuzzy_select("Select login method", &methods, 0)?;

if selected == 0 {
login_interactive_oauth(base).await
} else {
login_interactive_api_key(base).await
}
}

async fn login_interactive_api_key(base: &mut BaseArgs) -> Result<String> {
let api_key = prompt_api_key()?;

let login_app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let login_orgs = fetch_login_orgs(&api_key, &login_app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_api_key_profile(
&profile_name,
&api_key,
selected_api_url,
base.app_url.clone(),
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

async fn login_interactive_oauth(base: &mut BaseArgs) -> Result<String> {
let api_url = base
.api_url
.clone()
.unwrap_or_else(|| DEFAULT_API_URL.to_string());
let app_url = base
.app_url
.clone()
.unwrap_or_else(|| DEFAULT_APP_URL.to_string());
let provisional_profile = base
.profile
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("default");
let client_id = default_oauth_client_id(provisional_profile);

let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let state = generate_random_token(32)?;

let listener = TcpListener::bind(("127.0.0.1", 0))
.await
.context("failed to bind oauth callback listener")?;
let callback_port = listener
.local_addr()
.context("failed to read callback listener address")?
.port();
let redirect_uri = format!("http://127.0.0.1:{callback_port}/callback");
let oauth_client = build_oauth_client(&api_url, &client_id, Some(&redirect_uri))?;
let (authorize_url, _) = oauth_client
.authorize_url(|| CsrfToken::new(state.clone()))
.add_scope(Scope::new(OAUTH_SCOPE.to_string()))
.set_pkce_challenge(pkce_challenge)
.url();
let authorize_url = authorize_url.to_string();

let _ = open::that(&authorize_url);
eprintln!("Complete authorization in your browser.");
eprintln!("{}", dialoguer::console::style(&authorize_url).dim());

let callback = collect_oauth_callback(listener, is_ssh_session()).await?;
if let Some(error) = callback.error {
bail!("oauth authorization failed: {error}");
}
let auth_code = callback
.code
.ok_or_else(|| anyhow::anyhow!("no authorization code received"))?;
if callback.state.is_none() {
bail!("oauth callback missing state; paste the full callback URL (or code=...&state=...)");
}
if callback.state.as_deref() != Some(state.as_str()) {
bail!("oauth state mismatch; please try again");
}

let oauth_tokens = exchange_oauth_authorization_code(
&api_url,
&client_id,
&redirect_uri,
&auth_code,
pkce_verifier,
)
.await?;

let login_orgs = fetch_login_orgs(&oauth_tokens.access_token, &app_url).await?;
let selected_org = select_login_org_simple(login_orgs.clone(), base.org_name.as_deref())?;
let selected_api_url =
resolve_profile_api_url(base.api_url.clone(), selected_org.as_ref(), &login_orgs)?;
let profile_name = resolve_profile_name(
base.profile.as_deref(),
selected_org.as_ref().map(|org| org.name.as_str()),
false,
)?;

commit_oauth_profile(
&profile_name,
&oauth_tokens,
selected_api_url,
app_url,
client_id,
selected_org.as_ref().map(|org| org.name.clone()),
)?;

base.profile = Some(profile_name.clone());
Ok(profile_name)
}

fn commit_api_key_profile(
profile_name: &str,
api_key: &str,
api_url: String,
app_url: Option<String>,
org_name: Option<String>,
) -> Result<()> {
save_profile_secret(profile_name, api_key)?;
let _ = delete_profile_oauth_refresh_token(profile_name);
let _ = delete_profile_oauth_access_token(profile_name);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::ApiKey,
api_url: Some(api_url),
app_url,
org_name,
oauth_client_id: None,
oauth_access_expires_at: None,
user_name: None,
email: None,
api_key_hint: Some(obscure_api_key(api_key)),
},
);
save_auth_store(&store)
}

fn commit_oauth_profile(
profile_name: &str,
tokens: &OAuthTokenResponse,
api_url: String,
app_url: String,
client_id: String,
org_name: Option<String>,
) -> Result<()> {
let refresh_token = tokens.refresh_token.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"oauth token response did not include a refresh_token; cannot create persistent oauth profile"
)
})?;
save_profile_oauth_refresh_token(profile_name, refresh_token)?;
save_profile_oauth_access_token(profile_name, &tokens.access_token)?;
let _ = delete_profile_secret(profile_name);

let oauth_access_expires_at = determine_oauth_access_expiry_epoch(tokens);
let jwt_id = decode_jwt_identity(&tokens.access_token);

let mut store = load_auth_store()?;
store.profiles.insert(
profile_name.to_string(),
AuthProfile {
auth_kind: AuthKind::Oauth,
api_url: Some(api_url),
app_url: Some(app_url),
org_name,
oauth_client_id: Some(client_id),
oauth_access_expires_at,
user_name: jwt_id.name,
email: jwt_id.email,
api_key_hint: None,
},
);
save_auth_store(&store)
}

fn oauth_ignored_api_key_warning(base: &BaseArgs) -> Option<String> {
let api_key = base.api_key.as_deref()?.trim();
if api_key.is_empty() {
Expand DownExpand Up@@ -1395,6 +1553,49 @@ fn select_login_org(
))
}

/// Simplified org selector for the wizard — shows only org names (no UUIDs or API URLs).
/// Auto-selects when there is only one org. Falls back to non-interactive if TTY is unavailable.
fn select_login_org_simple(
mut orgs: Vec<LoginOrgInfo>,
requested_org_name: Option<&str>,
) -> Result<Option<LoginOrgInfo>> {
if orgs.is_empty() {
bail!("no organizations found for this credential");
}
orgs.sort_by(|a, b| {
a.name
.to_ascii_lowercase()
.cmp(&b.name.to_ascii_lowercase())
});

if let Some(name) = requested_org_name {
let selected = orgs
.iter()
.find(|org| org.name.eq_ignore_ascii_case(name))
.cloned();
return selected.map(Some).ok_or_else(|| {
let available = orgs
.iter()
.map(|org| org.name.as_str())
.collect::<Vec<_>>()
.join(", ");
anyhow::anyhow!("org '{name}' not found. Available: {available}")
});
}

if orgs.len() == 1 {
return Ok(Some(orgs.into_iter().next().expect("org exists")));
}

let labels: Vec<&str> = orgs.iter().map(|o| o.name.as_str()).collect();
let selection = ui::fuzzy_select("Select organization", &labels, 0)?;
Ok(Some(
orgs.into_iter()
.nth(selection)
.expect("selected index should be in range"),
))
}

fn resolve_profile_api_url(
explicit_api_url: Option<String>,
selected_org: Option<&LoginOrgInfo>,
Expand DownExpand Up@@ -1530,8 +1731,11 @@ async fn collect_oauth_callback(
}

async fn wait_for_oauth_callback_or_stdin(listener: TcpListener) -> Result<OAuthCallbackParams> {
println!("Waiting for OAuth callback...");
println!("If localhost callback does not complete, paste code=...&state=... and press Enter.");
eprintln!("Waiting for browser authorization...");
eprintln!(
"{}",
dialoguer::console::style("Paste code=...&state=... if callback doesn't complete").dim()
);

let callback_fut = wait_for_oauth_callback(listener);
tokio::pin!(callback_fut);
Expand Down
Loading
Loading