Skip to main content

vtcode_llm/copilot/auth/
mod.rs

1#![allow(
2    clippy::let_underscore_must_use,
3    reason = "Intentional compatibility, platform, or test-only suppression."
4)]
5
6use std::collections::HashMap;
7use std::io::{Read, Write};
8use std::path::{Path, PathBuf};
9use std::process::Stdio;
10use std::thread;
11use std::time::{Duration, Instant};
12
13use anyhow::{Context, Result, anyhow};
14use portable_pty::{CommandBuilder, PtySize, native_pty_system};
15use regex::Regex;
16use serde::Deserialize;
17use std::sync::LazyLock;
18use tokio::io::{AsyncRead, AsyncReadExt, BufReader};
19use tokio::sync::mpsc;
20use tokio::time::timeout;
21use url::Url;
22use vtcode_config::auth::CopilotAuthConfig;
23
24use vtcode_commons::ansi::strip_ansi;
25
26use super::command::{
27    ResolvedCopilotCommand, STRIPPED_RUNTIME_ENV_VARS, cached_which, copilot_command_available, resolve_copilot_command,
28};
29use super::types::{COPILOT_AUTH_DOC_PATH, CopilotAuthEvent, CopilotAuthStatus};
30use crate::process_env::{
31    COPILOT_AUTH_ENV_VARS, GITHUB_CLI_AUTH_ENV_VARS, provider_tokio_command, sanitize_pty_command_environment,
32};
33
34const DEFAULT_HOST_URL: &str = "https://github.com";
35const ENV_AUTH_VARS: &[&str] = &["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
36static DEVICE_FLOW_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
37    Regex::new(r"(?i)visit\s+(https?://\S+)\s+and\s+enter code\s+([A-Z0-9-]+)").expect("device flow regex must compile")
38});
39
40pub async fn login(config: &CopilotAuthConfig, workspace_root: &Path) -> Result<()> {
41    login_with_events(config, workspace_root, |_| Ok(())).await
42}
43
44pub async fn login_with_events<F>(config: &CopilotAuthConfig, workspace_root: &Path, mut on_event: F) -> Result<()>
45where
46    F: FnMut(CopilotAuthEvent) -> Result<()>,
47{
48    let resolved = resolve_copilot_command(config).context("invalid copilot command")?;
49    if let Err(err) = ensure_command_available(&resolved) {
50        emit_missing_command_guidance(config, &mut on_event)?;
51        on_event(CopilotAuthEvent::Failure { message: err.to_string() })?;
52        return Err(err);
53    }
54
55    let host = resolve_copilot_host(config)?;
56    let args = login_command_args(&host);
57
58    run_captured_command(&resolved, workspace_root, &args, "copilot login", CommandKind::Login, &mut on_event).await?;
59
60    let account = probe_auth_status(config, Some(workspace_root))
61        .await
62        .message
63        .as_deref()
64        .and_then(extract_account_from_status_message)
65        .map(ToString::to_string);
66    on_event(CopilotAuthEvent::Success { account })?;
67    Ok(())
68}
69
70pub async fn logout(config: &CopilotAuthConfig, workspace_root: &Path) -> Result<()> {
71    logout_with_events(config, workspace_root, |_| Ok(())).await
72}
73
74pub async fn logout_with_events<F>(config: &CopilotAuthConfig, workspace_root: &Path, mut on_event: F) -> Result<()>
75where
76    F: FnMut(CopilotAuthEvent) -> Result<()>,
77{
78    let resolved = resolve_copilot_command(config).context("invalid copilot command")?;
79    if let Err(err) = ensure_command_available(&resolved) {
80        emit_missing_command_guidance(config, &mut on_event)?;
81        on_event(CopilotAuthEvent::Failure { message: err.to_string() })?;
82        return Err(err);
83    }
84
85    let host = resolve_copilot_host(config)?;
86    let interactive_result = run_interactive_logout_command(&resolved, workspace_root, &host)
87        .await
88        .with_context(|| "copilot logout started an interactive Copilot CLI session");
89
90    if let Err(interactive_err) = interactive_result {
91        let args = logout_command_args();
92        let direct_logout = run_captured_command(
93            &resolved,
94            workspace_root,
95            &args,
96            "copilot logout",
97            CommandKind::Logout,
98            &mut on_event,
99        )
100        .await;
101
102        match direct_logout {
103            Ok(()) => {}
104            Err(err) if should_retry_logout_interactively(&err.to_string()) => {
105                return Err(interactive_err);
106            }
107            Err(err) => {
108                return Err(err).with_context(|| format!("interactive copilot logout failed: {interactive_err}"));
109            }
110        }
111    }
112
113    on_event(CopilotAuthEvent::Success { account: None })?;
114    Ok(())
115}
116
117pub async fn probe_auth_status(config: &CopilotAuthConfig, workspace_root: Option<&Path>) -> CopilotAuthStatus {
118    let host = match resolve_copilot_host(config) {
119        Ok(host) => host,
120        Err(err) => return CopilotAuthStatus::auth_flow_failed(err.to_string()),
121    };
122
123    let resolved = match resolve_copilot_command(config) {
124        Ok(resolved) => resolved,
125        Err(err) => return CopilotAuthStatus::auth_flow_failed(err.to_string()),
126    };
127
128    if !copilot_command_available(&resolved) {
129        return CopilotAuthStatus::server_unavailable(format!(
130            "GitHub Copilot CLI command `{}` was not found. Install `copilot`, set `VTCODE_COPILOT_COMMAND`, or configure `[auth.copilot].command`.",
131            resolved.display(),
132        ));
133    }
134
135    let auth_source = match detect_auth_source(&host, workspace_root).await {
136        Ok(source) => source,
137        Err(err) => return CopilotAuthStatus::auth_flow_failed(err.to_string()),
138    };
139
140    match auth_source {
141        Some(source) => CopilotAuthStatus::authenticated(Some(source.message(&host))),
142        None => CopilotAuthStatus::unauthenticated(Some(format!(
143            "No GitHub Copilot authentication source found for {}. Run `vtcode login copilot`, or set one of {}. `gh auth login` is only used as an optional fallback.",
144            host.gh_hostname,
145            ENV_AUTH_VARS.join(", ")
146        ))),
147    }
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151enum CommandKind {
152    Login,
153    Logout,
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157enum CapturedStream {
158    Stdout,
159    Stderr,
160}
161
162#[derive(Debug)]
163struct CapturedLine {
164    stream: CapturedStream,
165    text: String,
166}
167
168async fn run_captured_command<F>(
169    resolved: &ResolvedCopilotCommand,
170    workspace_root: &Path,
171    extra_args: &[String],
172    action_name: &str,
173    kind: CommandKind,
174    on_event: &mut F,
175) -> Result<()>
176where
177    F: FnMut(CopilotAuthEvent) -> Result<()>,
178{
179    let mut command = resolved.command(Some(workspace_root), extra_args);
180    command
181        .stdin(Stdio::null())
182        .stdout(Stdio::piped())
183        .stderr(Stdio::piped())
184        .kill_on_drop(true);
185
186    let mut child = command
187        .spawn()
188        .with_context(|| format!("failed to spawn `{}`", resolved.display()))?;
189    let stdout = child.stdout.take().ok_or_else(|| anyhow!("{action_name} stdout unavailable"))?;
190    let stderr = child.stderr.take().ok_or_else(|| anyhow!("{action_name} stderr unavailable"))?;
191
192    let (line_tx, mut line_rx) = mpsc::unbounded_channel();
193    spawn_line_reader(stdout, CapturedStream::Stdout, line_tx.clone());
194    spawn_line_reader(stderr, CapturedStream::Stderr, line_tx);
195    let mut state = CapturedCommandState::default();
196
197    let status = match timeout(resolved.auth_timeout, async {
198        let wait_result: Result<std::process::ExitStatus> = loop {
199            tokio::select! {
200                status = child.wait() => {
201                    break status.with_context(|| format!("{action_name} process failed"));
202                }
203                maybe_line = line_rx.recv() => {
204                    let Some(line) = maybe_line else {
205                        continue;
206                    };
207                    state.handle_line(kind, line, on_event)?;
208                }
209            }
210        };
211        wait_result
212    })
213    .await
214    {
215        Ok(status) => status?,
216        Err(_) => {
217            let _ = child.start_kill();
218            let message = format!("{action_name} timed out after {} seconds", resolved.auth_timeout.as_secs());
219            on_event(CopilotAuthEvent::Failure { message: message.clone() })?;
220            return Err(anyhow!(message));
221        }
222    };
223
224    while let Ok(line) = line_rx.try_recv() {
225        state.handle_line(kind, line, on_event)?;
226    }
227
228    if status.success() {
229        Ok(())
230    } else {
231        let message = state.failure_message(action_name, status);
232        on_event(CopilotAuthEvent::Failure { message: message.clone() })?;
233        Err(anyhow!(message))
234    }
235}
236
237#[derive(Default)]
238struct CapturedCommandState {
239    emitted_verification_code: bool,
240    emitted_waiting_message: bool,
241    last_safe_message: Option<String>,
242}
243
244impl CapturedCommandState {
245    fn handle_line<F>(&mut self, kind: CommandKind, line: CapturedLine, on_event: &mut F) -> Result<()>
246    where
247        F: FnMut(CopilotAuthEvent) -> Result<()>,
248    {
249        let normalized = normalize_captured_line(&line.text);
250        let trimmed = normalized.trim();
251        if trimmed.is_empty() {
252            return Ok(());
253        }
254
255        if matches!(kind, CommandKind::Logout)
256            && matches!(line.stream, CapturedStream::Stdout)
257            && trimmed.to_ascii_lowercase().contains("non-interactive mode")
258        {
259            self.record_safe_message(trimmed.to_string());
260            return Ok(());
261        }
262
263        if matches!(kind, CommandKind::Login)
264            && let Some(event) = parse_login_event(trimmed)
265        {
266            match &event {
267                CopilotAuthEvent::VerificationCode { .. } if self.emitted_verification_code => {
268                    return Ok(());
269                }
270                CopilotAuthEvent::VerificationCode { .. } => {
271                    self.emitted_verification_code = true;
272                }
273                CopilotAuthEvent::Progress { message }
274                    if message.eq_ignore_ascii_case("Waiting for authorization") && self.emitted_waiting_message =>
275                {
276                    return Ok(());
277                }
278                CopilotAuthEvent::Progress { message } if message.eq_ignore_ascii_case("Waiting for authorization") => {
279                    self.emitted_waiting_message = true;
280                }
281                _ => {}
282            }
283            return on_event(event);
284        }
285
286        if let Some(message) = sanitize_cli_line(trimmed, line.stream) {
287            self.record_safe_message(message);
288        }
289        Ok(())
290    }
291
292    fn record_safe_message(&mut self, message: String) {
293        let is_low_signal = is_low_signal_cli_hint(&message);
294        match self.last_safe_message.as_ref() {
295            Some(existing) if !is_low_signal_cli_hint(existing) && is_low_signal => {}
296            _ => {
297                self.last_safe_message = Some(message);
298            }
299        }
300    }
301
302    fn failure_message(&self, action_name: &str, status: std::process::ExitStatus) -> String {
303        if let Some(message) = self.last_safe_message.as_deref() {
304            format!("{action_name} exited with status {status}: {message}")
305        } else {
306            format!("{action_name} exited with status {status}")
307        }
308    }
309}
310
311fn spawn_line_reader<R>(reader: R, stream: CapturedStream, line_tx: mpsc::UnboundedSender<CapturedLine>)
312where
313    R: AsyncRead + Unpin + Send + 'static,
314{
315    tokio::spawn(async move {
316        let mut reader = BufReader::new(reader);
317        let mut buffer = Vec::new();
318        let mut chunk = [0_u8; 1024];
319
320        loop {
321            match reader.read(&mut chunk).await {
322                Ok(0) => break,
323                Ok(read) => {
324                    buffer.extend_from_slice(&chunk[..read]);
325                    for text in drain_complete_lines(&mut buffer) {
326                        let _ = line_tx.send(CapturedLine { stream, text });
327                    }
328                }
329                Err(_) => return,
330            }
331        }
332
333        if !buffer.is_empty() {
334            let text = String::from_utf8_lossy(&buffer).into_owned();
335            let _ = line_tx.send(CapturedLine { stream, text });
336        }
337    });
338}
339
340fn drain_complete_lines(buffer: &mut Vec<u8>) -> Vec<String> {
341    let mut lines = Vec::new();
342    let mut start = 0usize;
343    let mut index = 0usize;
344
345    while index < buffer.len() {
346        let byte = buffer[index];
347        if byte == b'\n' || byte == b'\r' {
348            let line = String::from_utf8_lossy(&buffer[start..index]).into_owned();
349            lines.push(line);
350
351            if byte == b'\r' && buffer.get(index + 1) == Some(&b'\n') {
352                index += 1;
353            }
354            index += 1;
355            start = index;
356            continue;
357        }
358        index += 1;
359    }
360
361    if start > 0 {
362        buffer.drain(..start);
363    }
364
365    lines
366}
367
368fn parse_login_event(line: &str) -> Option<CopilotAuthEvent> {
369    if let Some((url, user_code)) = parse_device_flow_code(line) {
370        return Some(CopilotAuthEvent::VerificationCode { url, user_code });
371    }
372
373    let lower = line.to_ascii_lowercase();
374    if lower.contains("waiting for authorization") {
375        return Some(CopilotAuthEvent::Progress { message: "Waiting for authorization".to_string() });
376    }
377    if lower.contains("opening browser") || lower.contains("opened browser") {
378        return Some(CopilotAuthEvent::Progress {
379            message: "Opened the browser for GitHub device authorization".to_string(),
380        });
381    }
382    None
383}
384
385fn parse_device_flow_code(line: &str) -> Option<(String, String)> {
386    let captures = DEVICE_FLOW_LINE_RE.captures(line)?;
387    let url = captures.get(1)?.as_str().trim_end_matches(['.', ',', ')', ']']).to_string();
388    let code = captures
389        .get(2)?
390        .as_str()
391        .trim_matches(|ch: char| matches!(ch, '.' | ',' | ':' | ';'))
392        .to_string();
393    (!url.is_empty() && !code.is_empty()).then_some((url, code))
394}
395
396fn normalize_captured_line(line: &str) -> String {
397    strip_ansi(line)
398        .chars()
399        .filter(|ch| {
400            !matches!(
401                ch,
402                '\u{0000}'..='\u{0008}'
403                    | '\u{000B}'
404                    | '\u{000C}'
405                    | '\u{000E}'..='\u{001F}'
406                    | '\u{007F}'
407            )
408        })
409        .collect()
410}
411
412fn login_command_args(host: &CopilotHost) -> Vec<String> {
413    let mut args = vec!["login".to_string()];
414    if !host.is_default() {
415        args.push("--host".to_string());
416        args.push(host.url.clone());
417    }
418    args
419}
420
421fn logout_command_args() -> Vec<String> {
422    vec!["logout".to_string()]
423}
424
425fn sanitize_cli_line(line: &str, stream: CapturedStream) -> Option<String> {
426    let lower = line.to_ascii_lowercase();
427    if lower.contains("copilot_github_token")
428        || lower.contains("gh_token")
429        || lower.contains("github_token")
430        || lower.contains("auth-token-env")
431    {
432        return Some("GitHub Copilot CLI reported an authentication configuration issue.".to_string());
433    }
434    if lower.contains("secitemcopymatching failed") {
435        return Some("GitHub Copilot CLI failed to access the macOS Keychain while clearing credentials.".to_string());
436    }
437
438    match stream {
439        CapturedStream::Stdout => None,
440        CapturedStream::Stderr => Some(line.to_string()),
441    }
442}
443
444fn is_low_signal_cli_hint(line: &str) -> bool {
445    let trimmed = line.trim();
446    trimmed.eq_ignore_ascii_case("Try 'copilot --help' for more information.")
447}
448
449fn extract_account_from_status_message(message: &str) -> Option<&str> {
450    let login = message.split(" for ").nth(1)?.split(" on ").next()?.trim();
451    (!login.is_empty()).then_some(login)
452}
453
454fn should_retry_logout_interactively(message: &str) -> bool {
455    message
456        .to_ascii_lowercase()
457        .contains("for non-interactive mode, use the -p or --prompt option")
458}
459
460async fn run_interactive_logout_command(
461    resolved: &ResolvedCopilotCommand,
462    workspace_root: &Path,
463    host: &CopilotHost,
464) -> Result<()> {
465    let resolved = resolved.clone();
466    let workspace_root = workspace_root.to_path_buf();
467    let host = host.clone();
468    tokio::task::spawn_blocking(move || blocking_interactive_logout_command(&resolved, &workspace_root, &host))
469        .await
470        .context("failed to join interactive copilot logout task")?
471}
472
473fn blocking_interactive_logout_command(
474    resolved: &ResolvedCopilotCommand,
475    workspace_root: &Path,
476    host: &CopilotHost,
477) -> Result<()> {
478    let pty_system = native_pty_system();
479    let pair = pty_system
480        .openpty(PtySize {
481            rows: 24,
482            cols: 80,
483            pixel_width: 0,
484            pixel_height: 0,
485        })
486        .context("failed to allocate PTY for interactive copilot logout")?;
487
488    let mut builder = CommandBuilder::new(&resolved.program);
489    for arg in &resolved.args {
490        builder.arg(arg);
491    }
492    builder.cwd(workspace_root);
493    sanitize_pty_command_environment(&mut builder, COPILOT_AUTH_ENV_VARS);
494    for env_var in STRIPPED_RUNTIME_ENV_VARS {
495        builder.env_remove(env_var);
496    }
497    builder.env("TERM", "xterm-256color");
498    builder.env("COLUMNS", "80");
499    builder.env("LINES", "24");
500
501    let mut child = pair
502        .slave
503        .spawn_command(builder)
504        .with_context(|| format!("failed to spawn `{}`", resolved.display()))?;
505    let mut killer = child.clone_killer();
506    drop(pair.slave);
507
508    let mut reader = pair
509        .master
510        .try_clone_reader()
511        .context("failed to clone PTY reader for copilot logout")?;
512    let mut writer = pair
513        .master
514        .take_writer()
515        .context("failed to take PTY writer for copilot logout")?;
516
517    let writer_thread = thread::spawn(move || -> Result<()> {
518        writer
519            .write_all(b"/logout\n")
520            .context("failed to send /logout to Copilot CLI")?;
521        writer.flush().context("failed to flush /logout to Copilot CLI")?;
522        thread::sleep(Duration::from_millis(250));
523        writer.write_all(b"/exit\n").context("failed to send /exit to Copilot CLI")?;
524        writer.flush().context("failed to flush /exit to Copilot CLI")?;
525        Ok(())
526    });
527
528    let (line_tx, line_rx) = std::sync::mpsc::channel();
529    let reader_thread = thread::spawn(move || -> Result<()> {
530        let mut chunk = [0_u8; 1024];
531        let mut buffer = Vec::new();
532        loop {
533            match reader.read(&mut chunk) {
534                Ok(0) => break,
535                Ok(read) => {
536                    buffer.extend_from_slice(&chunk[..read]);
537                    for text in drain_complete_lines(&mut buffer) {
538                        let _ = line_tx.send(text);
539                    }
540                }
541                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
542                Err(error) => {
543                    return Err(error).context("failed to read interactive copilot logout output");
544                }
545            }
546        }
547
548        if !buffer.is_empty() {
549            let text = String::from_utf8_lossy(&buffer).into_owned();
550            let _ = line_tx.send(text);
551        }
552
553        Ok(())
554    });
555
556    let (wait_tx, wait_rx) = std::sync::mpsc::channel();
557    let wait_thread = thread::spawn(move || {
558        let status = child.wait();
559        let _ = wait_tx.send(());
560        status
561    });
562
563    let start = Instant::now();
564    let mut last_auth_check = Instant::now();
565    let mut auth_cleared = false;
566    let mut state = CapturedCommandState::default();
567    let wait_granularity = Duration::from_millis(100);
568
569    loop {
570        while let Ok(text) = line_rx.try_recv() {
571            state.handle_line(
572                CommandKind::Logout,
573                CapturedLine { stream: CapturedStream::Stderr, text },
574                &mut |_| Ok(()),
575            )?;
576        }
577
578        if wait_rx.try_recv().is_ok() {
579            break;
580        }
581
582        if last_auth_check.elapsed() >= Duration::from_millis(250) {
583            last_auth_check = Instant::now();
584            if stored_auth_source(host)?.is_none() {
585                auth_cleared = true;
586                let _ = killer.kill();
587                break;
588            }
589        }
590
591        if start.elapsed() >= resolved.auth_timeout {
592            let _ = killer.kill();
593            let _ = writer_thread.join();
594            let _ = reader_thread.join();
595            let _ = wait_thread.join();
596            return Err(anyhow!("copilot logout timed out after {} seconds", resolved.auth_timeout.as_secs()));
597        }
598
599        thread::sleep(wait_granularity);
600    }
601
602    let status = wait_thread
603        .join()
604        .map_err(|panic| anyhow!("interactive copilot logout wait thread panicked: {panic:?}"))?;
605
606    let writer_result = writer_thread
607        .join()
608        .map_err(|panic| anyhow!("interactive copilot logout writer thread panicked: {panic:?}"))?;
609
610    let reader_result = reader_thread
611        .join()
612        .map_err(|panic| anyhow!("interactive copilot logout reader thread panicked: {panic:?}"))?;
613
614    if auth_cleared {
615        return Ok(());
616    }
617
618    let status = status.context("failed to wait for interactive copilot logout process")?;
619    writer_result.context("failed to write interactive copilot logout commands")?;
620    reader_result.context("failed to read interactive copilot logout output")?;
621
622    while let Ok(text) = line_rx.try_recv() {
623        state
624            .handle_line(CommandKind::Logout, CapturedLine { stream: CapturedStream::Stderr, text }, &mut |_| Ok(()))?;
625    }
626
627    if stored_auth_source(host)?.is_none() {
628        return Ok(());
629    }
630
631    let exit_status = format_portable_exit_status(status);
632    let failure = if let Some(message) = state.last_safe_message.as_deref() {
633        format!("copilot logout exited with status {exit_status}: {message}")
634    } else {
635        format!("copilot logout exited with status {exit_status}")
636    };
637    Err(anyhow!(failure))
638}
639
640fn format_portable_exit_status(status: portable_pty::ExitStatus) -> String {
641    status
642        .signal()
643        .map(|signal| format!("signal {signal}"))
644        .unwrap_or_else(|| status.exit_code().to_string())
645}
646
647fn ensure_command_available(resolved: &ResolvedCopilotCommand) -> Result<()> {
648    if copilot_command_available(resolved) {
649        return Ok(());
650    }
651
652    Err(anyhow!(
653        "GitHub Copilot CLI command `{}` was not found. Install `copilot`, set `VTCODE_COPILOT_COMMAND`, or configure `[auth.copilot].command`. See `{COPILOT_AUTH_DOC_PATH}`.",
654        resolved.display(),
655    ))
656}
657
658fn emit_missing_command_guidance<F>(config: &CopilotAuthConfig, on_event: &mut F) -> Result<()>
659where
660    F: FnMut(CopilotAuthEvent) -> Result<()>,
661{
662    let Some(lines) = missing_copilot_command_help_lines(config)? else {
663        return Ok(());
664    };
665
666    for line in lines {
667        on_event(CopilotAuthEvent::Progress { message: line })?;
668    }
669
670    Ok(())
671}
672
673fn missing_copilot_command_help_lines(config: &CopilotAuthConfig) -> Result<Option<Vec<String>>> {
674    let resolved = resolve_copilot_command(config).context("invalid copilot command")?;
675    Ok(missing_copilot_command_help_lines_with(
676        &resolved.display(),
677        copilot_command_available(&resolved),
678        cached_which("gh"),
679    ))
680}
681
682fn missing_copilot_command_help_lines_with(
683    command_display: &str,
684    copilot_available: bool,
685    gh_available: bool,
686) -> Option<Vec<String>> {
687    if copilot_available {
688        return None;
689    }
690
691    let mut lines = vec![
692        format!(
693            "GitHub Copilot login/logout requires the configured Copilot CLI command `{command_display}` to be runnable."
694        ),
695        "Install `copilot`, then rerun `/login copilot`, `/logout copilot`, or `vtcode login copilot`.".to_string(),
696        format!(
697            "If the CLI is installed outside PATH, set `VTCODE_COPILOT_COMMAND` or `[auth.copilot].command`. See `{COPILOT_AUTH_DOC_PATH}`."
698        ),
699    ];
700
701    if gh_available {
702        lines.push(
703            "`gh` is optional fallback only. VT Code still requires the official `copilot` CLI for login/logout."
704                .to_string(),
705        );
706    } else {
707        lines.push(
708            "`gh` is also not installed. That is okay for login/logout: VT Code only uses `gh` as an optional fallback when probing existing GitHub auth."
709                .to_string(),
710        );
711    }
712
713    Some(lines)
714}
715
716async fn detect_auth_source(host: &CopilotHost, workspace_root: Option<&Path>) -> Result<Option<CopilotAuthSource>> {
717    if let Some(source) = env_auth_source_with(|name| std::env::var(name).ok()) {
718        return Ok(Some(source));
719    }
720
721    if let Some(source) = stored_auth_source(host)? {
722        return Ok(Some(source));
723    }
724
725    if github_cli_auth_available(host, workspace_root).await? {
726        return Ok(Some(CopilotAuthSource::GitHubCli));
727    }
728
729    Ok(None)
730}
731
732fn env_auth_source_with<F>(mut read_var: F) -> Option<CopilotAuthSource>
733where
734    F: FnMut(&str) -> Option<String>,
735{
736    ENV_AUTH_VARS.iter().find_map(|name| {
737        read_var(name)
738            .as_deref()
739            .map(str::trim)
740            .filter(|value| !value.is_empty())
741            .map(|_| CopilotAuthSource::Environment(name))
742    })
743}
744
745fn stored_auth_source(host: &CopilotHost) -> Result<Option<CopilotAuthSource>> {
746    let Some(config_path) = copilot_config_path() else {
747        return Ok(None);
748    };
749    if !config_path.exists() {
750        return Ok(None);
751    }
752
753    let config_text =
754        std::fs::read_to_string(&config_path).with_context(|| format!("failed to read {}", config_path.display()))?;
755    let config: CopilotCliConfig =
756        serde_json::from_str(&config_text).with_context(|| format!("failed to parse {}", config_path.display()))?;
757
758    if let Some(user) = config
759        .logged_in_users
760        .iter()
761        .find(|user| user.host_matches(host))
762        .or_else(|| config.last_logged_in_user.as_ref().filter(|user| user.host_matches(host)))
763    {
764        return Ok(Some(CopilotAuthSource::StoredCredentials { login: user.login.clone() }));
765    }
766
767    let token_login = config
768        .copilot_tokens
769        .keys()
770        .find_map(|key| copilot_token_login_for_host(host, key));
771    let token_host_match = token_login.is_some()
772        || config
773            .copilot_tokens
774            .keys()
775            .any(|key| copilot_token_key_matches_host(host, key));
776
777    if token_host_match {
778        return Ok(Some(CopilotAuthSource::StoredCredentials {
779            login: token_login.or_else(|| config.last_logged_in_user.and_then(|user| user.login)),
780        }));
781    }
782
783    Ok(None)
784}
785
786async fn github_cli_auth_available(host: &CopilotHost, workspace_root: Option<&Path>) -> Result<bool> {
787    if !cached_which("gh") {
788        return Ok(false);
789    }
790
791    let mut command = provider_tokio_command("gh", workspace_root, GITHUB_CLI_AUTH_ENV_VARS);
792    command
793        .arg("auth")
794        .arg("status")
795        .arg("--hostname")
796        .arg(&host.gh_hostname)
797        .stdout(Stdio::null())
798        .stderr(Stdio::null())
799        .kill_on_drop(true);
800
801    let mut child = command
802        .spawn()
803        .with_context(|| format!("failed to spawn `gh auth status --hostname {}`", host.gh_hostname))?;
804
805    let status = match timeout(Duration::from_secs(5), child.wait()).await {
806        Ok(status) => status.context("`gh auth status` failed")?,
807        Err(_) => {
808            let _ = child.start_kill();
809            return Ok(false);
810        }
811    };
812
813    Ok(status.success())
814}
815
816fn copilot_config_path() -> Option<PathBuf> {
817    let base_dir = std::env::var_os("COPILOT_HOME")
818        .filter(|value| !value.is_empty())
819        .map(PathBuf::from)
820        .or_else(|| dirs::home_dir().map(|home| home.join(".copilot")))?;
821    Some(base_dir.join("config.json"))
822}
823
824fn resolve_copilot_host(config: &CopilotAuthConfig) -> Result<CopilotHost> {
825    let raw = config
826        .host
827        .as_deref()
828        .map(str::trim)
829        .filter(|value| !value.is_empty())
830        .map(ToString::to_string)
831        .or_else(|| {
832            std::env::var("GH_HOST")
833                .ok()
834                .map(|value| value.trim().to_string())
835                .filter(|value| !value.is_empty())
836        })
837        .unwrap_or_else(|| DEFAULT_HOST_URL.to_string());
838
839    CopilotHost::parse(&raw)
840}
841
842#[derive(Debug, Clone, PartialEq, Eq)]
843struct CopilotHost {
844    url: String,
845    gh_hostname: String,
846}
847
848impl CopilotHost {
849    fn parse(value: &str) -> Result<Self> {
850        let trimmed = value.trim();
851        if trimmed.is_empty() {
852            return Self::parse(DEFAULT_HOST_URL);
853        }
854
855        let normalized = if trimmed.contains("://") {
856            trimmed.to_string()
857        } else {
858            format!("https://{trimmed}")
859        };
860
861        let parsed = Url::parse(&normalized).with_context(|| format!("invalid GitHub Copilot host `{trimmed}`"))?;
862        let hostname = parsed
863            .host_str()
864            .ok_or_else(|| anyhow!("GitHub Copilot host `{trimmed}` is missing a hostname"))?;
865
866        let mut url = format!("{}://{}", parsed.scheme(), hostname);
867        if let Some(port) = parsed.port() {
868            url.push(':');
869            url.push_str(&port.to_string());
870        }
871        let path = parsed.path().trim_end_matches('/');
872        if !path.is_empty() && path != "/" {
873            url.push_str(path);
874        }
875
876        Ok(Self { url, gh_hostname: hostname.to_string() })
877    }
878
879    fn is_default(&self) -> bool {
880        self.url == DEFAULT_HOST_URL
881    }
882
883    fn matches_config_host(&self, value: &str) -> bool {
884        Self::parse(value)
885            .map(|candidate| candidate.url == self.url || candidate.gh_hostname == self.gh_hostname)
886            .unwrap_or_else(|_| value.trim().eq_ignore_ascii_case(&self.gh_hostname))
887    }
888}
889
890fn copilot_token_key_matches_host(host: &CopilotHost, key: &str) -> bool {
891    let trimmed = key.trim();
892    if trimmed.is_empty() {
893        return false;
894    }
895    if host.matches_config_host(trimmed) {
896        return true;
897    }
898
899    trimmed
900        .rsplit_once(':')
901        .map(|(candidate_host, _)| host.matches_config_host(candidate_host))
902        .unwrap_or(false)
903}
904
905fn copilot_token_login_for_host(host: &CopilotHost, key: &str) -> Option<String> {
906    let trimmed = key.trim();
907    if trimmed.is_empty() || !copilot_token_key_matches_host(host, trimmed) {
908        return None;
909    }
910
911    let (candidate_host, login) = trimmed.rsplit_once(':')?;
912    host.matches_config_host(candidate_host)
913        .then(|| login.trim().to_string())
914        .filter(|login| !login.is_empty())
915}
916
917#[derive(Debug)]
918enum CopilotAuthSource {
919    Environment(&'static str),
920    StoredCredentials { login: Option<String> },
921    GitHubCli,
922}
923
924impl CopilotAuthSource {
925    fn message(&self, host: &CopilotHost) -> String {
926        match self {
927            Self::Environment(name) => format!("Using {name} for GitHub Copilot authentication."),
928            Self::StoredCredentials { login: Some(login) } => {
929                format!("Using Copilot CLI stored credentials for {login} on {}.", host.gh_hostname)
930            }
931            Self::StoredCredentials { login: None } => {
932                format!("Using Copilot CLI stored credentials on {}.", host.gh_hostname)
933            }
934            Self::GitHubCli => {
935                format!("Using GitHub CLI authentication fallback on {}.", host.gh_hostname)
936            }
937        }
938    }
939}
940
941#[derive(Debug, Default, Deserialize)]
942struct CopilotCliConfig {
943    #[serde(default)]
944    logged_in_users: Vec<CopilotCliUser>,
945    #[serde(default)]
946    last_logged_in_user: Option<CopilotCliUser>,
947    #[serde(default)]
948    copilot_tokens: HashMap<String, String>,
949}
950
951#[derive(Debug, Clone, Default, Deserialize)]
952struct CopilotCliUser {
953    #[serde(default)]
954    host: Option<String>,
955    #[serde(default)]
956    login: Option<String>,
957}
958
959impl CopilotCliUser {
960    fn host_matches(&self, host: &CopilotHost) -> bool {
961        self.host
962            .as_deref()
963            .map(|candidate| host.matches_config_host(candidate))
964            .unwrap_or(false)
965    }
966}
967
968#[cfg(test)]
969mod tests;