Skip to main content

artifactize_core/auth/
codex.rs

1//! CLI and desktop presentation of the provider's Codex sign-in.
2
3use std::{io::Write, path::Path};
4use tokio::sync::oneshot;
5
6use artifactize_provider::auth::codex as provider;
7pub use provider::{
8    AUTH_FILE_VARIABLE, AUTH_URL_VARIABLE, CALLBACK_PATH, CALLBACK_PORT, CallbackPort, FileExpiry,
9    Prompt, Status, StoredExpiry, Timestamp, auth_file, auth_root,
10};
11
12use super::{credential_location, storage::Tokens, writable_credential_location};
13
14/// Sign in interactively and save artifactize's own tokens. The sign-in URL goes to
15/// stderr, also with --json.
16pub async fn login(state: Option<&Path>, repo: Option<&Path>) -> Result<(), String> {
17    // Refuse before reading the terminal: where the tokens go and the sign-in root.
18    credential_location(state, repo, Tokens::Codex)?;
19    auth_root()?;
20    let terminal = crate::platform::stdin_is_terminal();
21    let pasted = if terminal {
22        let (send, receive) = oneshot::channel();
23        // Detached: a sign-in finished in the browser leaves this read unanswered.
24        std::thread::Builder::new()
25            .name("codex-login-input".into())
26            .spawn(move || {
27                for line in std::io::stdin().lines() {
28                    match line {
29                        Ok(line) if line.trim().is_empty() => continue,
30                        Ok(line) => {
31                            let _ = send.send(line);
32                        }
33                        Err(_) => {}
34                    }
35                    break;
36                }
37            })
38            .map_err(|error| format!("Cannot start Codex sign-in input: {error}"))?;
39        Some(receive)
40    } else {
41        None
42    };
43    login_with(state, repo, pasted, true, CallbackPort::Registered, |prompt| {
44        let mut err = std::io::stderr().lock();
45        let _ = writeln!(err, "Open this URL to sign in with Codex:\n{}", prompt.url);
46        if !prompt.callback {
47            let _ = writeln!(
48                err,
49                "Port {CALLBACK_PORT} is in use (another sign-in, such as the Codex CLI or app, may hold it), so the browser cannot return here."
50            );
51        }
52        if terminal {
53            let _ = writeln!(
54                err,
55                "When the browser cannot return here, paste the full URL it was sent to (starting http://localhost:{CALLBACK_PORT}{CALLBACK_PATH}?code=) and press Enter. Find it in the browser's address bar after the failed load, or in DevTools → Network if the page keeps loading."
56            );
57        }
58    })
59    .await
60}
61
62pub async fn login_with(
63    state: Option<&Path>,
64    repo: Option<&Path>,
65    pasted: Option<oneshot::Receiver<String>>,
66    browser: bool,
67    callback_port: CallbackPort,
68    show: impl FnOnce(&Prompt),
69) -> Result<(), String> {
70    let location = writable_credential_location(state, repo, Tokens::Codex)?;
71    let open = browser.then_some(crate::platform::program::open_desktop);
72    provider::login_with(&location, pasted, open, callback_port, show).await
73}
74
75pub fn status(state: Option<&Path>, repo: Option<&Path>) -> Result<Status, String> {
76    let location = credential_location(state, repo, Tokens::Codex);
77    provider::status(location.as_ref().map_err(String::as_str))
78}
79
80pub async fn logout(state: Option<&Path>, repo: Option<&Path>) -> Result<bool, String> {
81    let location = writable_credential_location(state, repo, Tokens::Codex)?;
82    provider::logout(Ok(&location)).await
83}
84
85#[cfg(all(test, unix))] // Only Unix opens via an external program the fixture can replace.
86mod tests;