1use super::*;
3use sha2::{Digest, Sha256};
4use std::{
5 collections::BTreeMap,
6 ffi::OsStr,
7 io::{self, Write},
8};
9use tokio::{
10 io::{AsyncReadExt, AsyncWriteExt},
11 net::TcpListener,
12 sync::oneshot,
13};
14
15pub(super) const CALLBACK_WRITE_TIMEOUT: Duration = Duration::from_secs(2);
17
18pub(super) const CALLBACK_READ_TIMEOUT: Duration = Duration::from_secs(5);
20
21pub(super) const LOGIN_TIMEOUT: Duration = Duration::from_secs(300);
24
25pub(super) const OAUTH_STATE_BYTES: usize = 16;
28
29pub(super) const PKCE_VERIFIER_BYTES: usize = 32;
32
33pub(super) const SCOPE: &str = "openid profile email offline_access";
34
35pub(super) const CALLBACK_PATH: &str = "/auth/callback";
36
37pub(super) const CALLBACK_PORT: u16 = 1455;
40
41pub(super) fn random(bytes: usize) -> Result<Vec<u8>, String> {
42 let mut value = vec![0; bytes];
43 getrandom::fill(&mut value).map_err(|_| "Cannot obtain secure randomness.".to_owned())?;
44 Ok(value)
45}
46
47pub(super) struct Pending {
49 pub(super) verifier: String,
50 pub(super) state: crate::types::OAuthState,
51}
52
53impl Pending {
54 pub(super) fn new() -> Result<Self, String> {
55 let state: String = random(OAUTH_STATE_BYTES)?
56 .iter()
57 .map(|byte| format!("{byte:02x}"))
58 .collect();
59 Ok(Self {
60 verifier: URL_SAFE_NO_PAD.encode(random(PKCE_VERIFIER_BYTES)?),
61 state: state.parse().expect("generated OAuth state is valid"),
62 })
63 }
64
65 pub(super) fn challenge(&self) -> String {
66 URL_SAFE_NO_PAD.encode(Sha256::digest(self.verifier.as_bytes()))
67 }
68
69 pub(super) fn authorize_url(&self, root: &Url, redirect_uri: &str) -> Result<Url, String> {
70 let mut url = endpoint(root, "authorize")?;
71 url.query_pairs_mut().extend_pairs([
72 ("response_type", "code"),
73 ("client_id", CLIENT_ID),
74 ("redirect_uri", redirect_uri),
75 ("scope", SCOPE),
76 ("code_challenge", &self.challenge()),
77 ("code_challenge_method", "S256"),
78 ("state", &self.state),
79 ("id_token_add_organizations", "true"),
80 ("codex_cli_simplified_flow", "true"),
81 ("originator", ORIGINATOR),
82 ]);
83 Ok(url)
84 }
85
86 pub(super) fn pasted(&self, input: &str) -> Result<String, String> {
89 let input = input.trim();
90 let (code, state) = if let Ok(url) = Url::parse(input) {
91 let pairs: BTreeMap<_, _> = url.query_pairs().into_owned().collect();
92 (pairs.get("code").cloned(), pairs.get("state").cloned())
93 } else if let Some((code, state)) = input.split_once('#') {
94 (Some(code.to_owned()), Some(state.to_owned()))
95 } else if input.contains("code=") {
96 let pairs: BTreeMap<_, _> = url::form_urlencoded::parse(input.as_bytes())
97 .into_owned()
98 .collect();
99 (pairs.get("code").cloned(), pairs.get("state").cloned())
100 } else {
101 (Some(input.to_owned()), None)
102 };
103 if state.is_some_and(|state| state != self.state) {
104 return Err("Codex sign-in state mismatch.".into());
105 }
106 code.filter(|code| !code.is_empty())
107 .ok_or_else(|| "The pasted input has no authorization code.".into())
108 }
109
110 pub(super) fn callback(
112 &self,
113 target: &str,
114 ) -> (&'static str, &'static str, Option<Result<String, String>>) {
115 let Ok(url) = Url::parse(&format!("http://localhost{target}")) else {
116 return ("400 Bad Request", "Invalid callback.", None);
117 };
118 if url.path() != CALLBACK_PATH {
119 return ("404 Not Found", "Not found.", None);
120 }
121 let mut parameters = BTreeMap::new();
122 for (key, value) in url.query_pairs().into_owned() {
123 if parameters.insert(key, value).is_some() {
124 return ("400 Bad Request", "Duplicate callback parameter.", None);
125 }
126 }
127 if parameters.get("state").map(String::as_str) != Some(self.state.as_str()) {
128 return ("400 Bad Request", "State mismatch.", None);
129 }
130 if let Some(error) = parameters.get("error") {
131 let error: String = error
132 .chars()
133 .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
134 .take(MAX_OAUTH_ERROR_CHARS)
135 .collect();
136 return (
137 "400 Bad Request",
138 "Codex sign-in was not completed. Return to artifactize.",
139 Some(Err(format!("Codex sign-in failed ({error})."))),
140 );
141 }
142 match parameters.get("code").filter(|code| !code.is_empty()) {
143 Some(code) => (
144 "200 OK",
145 "Signed in to Codex. Return to artifactize; you can close this page.",
146 Some(Ok(code.clone())),
147 ),
148 None => ("400 Bad Request", "Missing authorization code.", None),
149 }
150 }
151
152 pub(super) async fn serve(&self, listener: TcpListener) -> Result<String, String> {
155 const MAX_CALLBACK_HEADER_BYTES: usize = 16 * 1024;
158 let port = listener.local_addr().map_err(|e| e.to_string())?.port();
159 let hosts = [
160 format!("localhost:{port}"),
161 format!("127.0.0.1:{port}"),
162 format!("[::1]:{port}"),
163 ];
164 loop {
165 let (mut stream, _) = listener.accept().await.map_err(|e| e.to_string())?;
166 let head = tokio::time::timeout(CALLBACK_READ_TIMEOUT, async {
167 let mut head = Vec::new();
168 let mut byte = [0];
169 while !head.ends_with(b"\r\n\r\n") && head.len() < MAX_CALLBACK_HEADER_BYTES {
170 if stream.read(&mut byte).await? == 0 {
171 break;
172 }
173 head.push(byte[0]);
174 }
175 Ok::<_, std::io::Error>(head)
176 })
177 .await;
178 let Ok(Ok(head)) = head else { continue };
179 let head = String::from_utf8_lossy(&head);
180 let line: Vec<_> = head
181 .lines()
182 .next()
183 .unwrap_or("")
184 .split_whitespace()
185 .collect();
186 let host: Vec<_> = head
187 .lines()
188 .skip(1)
189 .filter_map(|line| line.split_once(':'))
190 .filter(|(name, _)| name.eq_ignore_ascii_case("host"))
191 .map(|(_, value)| value.trim())
192 .collect();
193 let valid = head.ends_with("\r\n\r\n")
194 && line.len() == 3
195 && line[0] == "GET"
196 && matches!(line[2], "HTTP/1.0" | "HTTP/1.1")
197 && host.len() == 1
198 && hosts.iter().any(|expected| expected == host[0])
199 && line[1].starts_with('/')
200 && !line[1].starts_with("//");
201 let (status, body, result) = if valid {
202 self.callback(line[1])
203 } else {
204 ("400 Bad Request", "Invalid callback.", None)
205 };
206 let response = format!(
207 "HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
208 body.len()
209 );
210 let _ = tokio::time::timeout(
211 CALLBACK_WRITE_TIMEOUT,
212 stream.write_all(response.as_bytes()),
213 )
214 .await;
215 if let Some(result) = result {
216 return result;
217 }
218 }
219 }
220
221 pub(super) async fn wait(
223 &self,
224 listener: Option<Callback>,
225 pasted: Option<oneshot::Receiver<String>>,
226 ) -> Result<String, String> {
227 let callback = async {
228 match listener {
229 Some(listener) => listener.wait(self).await,
230 None => std::future::pending().await,
231 }
232 };
233 let pasted = async {
234 match pasted {
235 Some(receiver) => match receiver.await {
236 Ok(input) => self.pasted(&input),
237 Err(_) => std::future::pending().await,
238 },
239 None => std::future::pending().await,
240 }
241 };
242 tokio::time::timeout(LOGIN_TIMEOUT, async {
243 tokio::select! {
244 result = callback => result,
245 result = pasted => result,
246 }
247 })
248 .await
249 .map_err(|_| "Codex sign-in timed out; run `artifactize login codex` again.".to_owned())?
250 }
251}
252
253#[derive(Debug, Clone, Serialize)]
256#[serde(rename_all = "camelCase")]
257pub struct Prompt {
258 pub url: String,
259 pub callback: bool,
260}
261
262pub async fn login(state: Option<&Path>, repo: Option<&Path>) -> Result<(), String> {
265 Storage::new(state, repo, Tokens::Codex)?;
267 auth_root()?;
268 let terminal = crate::platform::stdin_is_terminal();
269 let pasted = if terminal {
270 let (send, receive) = oneshot::channel();
271 std::thread::Builder::new()
273 .name("codex-login-input".into())
274 .spawn(move || {
275 for line in std::io::stdin().lines() {
276 match line {
277 Ok(line) if line.trim().is_empty() => continue,
278 Ok(line) => {
279 let _ = send.send(line);
280 }
281 Err(_) => {}
282 }
283 break;
284 }
285 })
286 .map_err(|error| format!("Cannot start Codex sign-in input: {error}"))?;
287 Some(receive)
288 } else {
289 None
290 };
291 login_with(state, repo, pasted, true, |prompt| {
292 let mut err = std::io::stderr().lock();
293 let _ = writeln!(err, "Open this URL to sign in with Codex:\n{}", prompt.url);
294 if !prompt.callback {
295 let _ = writeln!(
296 err,
297 "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."
298 );
299 }
300 if terminal {
301 let _ = writeln!(
302 err,
303 "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."
304 );
305 }
306 })
307 .await
308}
309
310pub async fn login_with(
315 state: Option<&Path>,
316 repo: Option<&Path>,
317 pasted: Option<oneshot::Receiver<String>>,
318 browser: bool,
319 show: impl FnOnce(&Prompt),
320) -> Result<(), String> {
321 let storage = Storage::new(state, repo, Tokens::Codex)?;
323 let root = auth_root()?;
324 let listener = Callback::bind(CALLBACK_PORT)
325 .map_err(|error| format!("Cannot bind Codex sign-in callback: {error}"))?;
326 let redirect_uri = format!("http://localhost:{CALLBACK_PORT}{CALLBACK_PATH}");
327 sign_in(
328 &storage,
329 &root,
330 listener,
331 &redirect_uri,
332 pasted,
333 browser,
334 |url, callback| {
335 show(&Prompt {
336 url: url.to_string(),
337 callback,
338 })
339 },
340 )
341 .await
342}
343
344pub(super) async fn sign_in(
345 storage: &Storage,
346 root: &Url,
347 listener: Option<Callback>,
348 redirect_uri: &str,
349 pasted: Option<oneshot::Receiver<String>>,
350 browser: bool,
351 show: impl FnOnce(&Url, bool),
352) -> Result<(), String> {
353 let open = browser.then_some(crate::platform::program::open_desktop);
354 sign_in_opening(storage, root, listener, redirect_uri, pasted, open, show).await
355}
356
357pub(super) async fn sign_in_opening(
359 storage: &Storage,
360 root: &Url,
361 listener: Option<Callback>,
362 redirect_uri: &str,
363 pasted: Option<oneshot::Receiver<String>>,
364 open: Option<impl AsyncFnOnce(&OsStr) -> io::Result<()>>,
365 show: impl FnOnce(&Url, bool),
366) -> Result<(), String> {
367 if listener.is_none() && pasted.is_none() {
368 return Err(format!(
369 "Port {CALLBACK_PORT} is in use and there is no terminal to paste the redirect URL into; finish the other sign-in and try again."
370 ));
371 }
372 let pending = Pending::new()?;
373 let url = pending.authorize_url(root, redirect_uri)?;
374 show(&url, listener.is_some());
375 let opened = async {
376 if let Some(open) = open {
377 open_browser(&url, open).await;
378 }
379 };
380 let (code, ()) = tokio::join!(pending.wait(listener, pasted), opened);
383 let code = code?;
384 let tokens = token_request(
385 root,
386 &[
387 ("grant_type", "authorization_code"),
388 ("client_id", CLIENT_ID),
389 ("code", &code),
390 ("code_verifier", &pending.verifier),
391 ("redirect_uri", redirect_uri),
392 ],
393 None,
394 )
395 .await
396 .map_err(|error| error.message)?;
397 let credentials = credentials(tokens, now()?)?;
398 let _lock = storage.lock(LOCK).await?;
399 storage.save(CREDENTIALS, &credentials)
400}
401
402pub(super) async fn open_browser(url: &Url, open: impl AsyncFnOnce(&OsStr) -> io::Result<()>) {
403 let _ = open(OsStr::new(url.as_str())).await;
405}