1use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::time::Duration;
9
10use cpa_common::json::GoValue;
11use cpa_core::config::Config;
12use cpa_core::gostr::GoStr;
13
14use crate::claude_login::{Interaction, parse_callback_input};
15use crate::codex_oauth::{CodexOAuth, LoginOptions};
16use crate::codex_siwc::Tokens;
17
18pub const CALLBACK_PORT: u16 = 1455;
20
21#[derive(Debug, PartialEq, Eq)]
23pub enum BindError {
24 Log(String),
26 Print(String),
28 PortInUse,
31}
32
33type GoMap = BTreeMap<String, GoValue>;
34
35fn decode(data: &[u8]) -> Result<Option<GoMap>, String> {
38 match GoValue::parse_f64(data).map(GoValue::into_object) {
39 Some(Ok(map)) => Ok(Some(map)),
40 Some(Err(GoValue::Null)) => Ok(None),
41 Some(Err(_)) => Err("json: cannot unmarshal into Go value of type map[string]interface {}".into()),
42 None => Err("invalid JSON".into()),
43 }
44}
45
46fn go_str<'a>(map: Option<&'a GoMap>, key: &str) -> &'a str {
47 match map.and_then(|m| m.get(key)) {
48 Some(GoValue::String(s)) => s,
49 _ => "",
50 }
51}
52
53fn validate(meta: Option<&GoMap>) -> Result<(), String> {
55 if !go_str(meta, "type").trim().go_eq_fold("codex") {
56 return Err("siwc-bind: credential type must be codex".into());
57 }
58 for key in ["access_token", "refresh_token"] {
59 if go_str(meta, key).trim().is_empty() {
60 return Err(format!("siwc-bind: codex credential requires a non-empty {key}"));
61 }
62 }
63 Ok(())
64}
65
66pub fn resolve(auth_dir: &Path, target: &str) -> Result<PathBuf, String> {
70 let raw = target.trim();
71 if raw.is_empty() {
72 return Err("siwc-bind: missing codex credential file path".into());
73 }
74 if auth_dir.to_string_lossy().trim().is_empty() {
75 return Err("siwc-bind: auth-dir is not configured".into());
76 }
77 let dir = go_abs(auth_dir)
81 .and_then(std::fs::canonicalize)
82 .map(plain_path)
83 .map_err(|e| format!("siwc-bind: failed to resolve real auth-dir: {e}"))?;
84 let candidate = if Path::new(raw).is_absolute() {
85 PathBuf::from(raw)
86 } else if raw.contains(['/', '\\']) || raw == "." || raw == ".." {
87 return Err("siwc-bind: expected an absolute path or bare filename".into());
88 } else {
89 dir.join(raw)
90 };
91 let candidate = std::fs::canonicalize(candidate)
92 .map(plain_path)
93 .map_err(|e| format!("siwc-bind: failed to resolve credential file: {e}"))?;
94 if candidate
95 .strip_prefix(&dir)
96 .map_or(true, |rel| rel.as_os_str().is_empty())
97 {
98 return Err("siwc-bind: credential file must belong to auth-dir".into());
99 }
100 if !std::fs::metadata(&candidate).is_ok_and(|m| m.is_file()) {
101 return Err("siwc-bind: credential target must be an existing regular file".into());
102 }
103 let data = std::fs::read(&candidate)
104 .map_err(|e| format!("siwc-bind: failed to read credential file {}: {e}", candidate.display()))?;
105 let meta = decode(&data).map_err(|_| format!("siwc-bind: invalid credential JSON in {}", candidate.display()))?;
106 validate(meta.as_ref())?;
107 Ok(candidate)
108}
109
110pub fn device_id(path: &Path) -> Result<String, String> {
113 let data = std::fs::read(path).map_err(|e| format!("failed to read credential file: {e}"))?;
114 let meta = decode(&data).map_err(|e| format!("invalid credential JSON: {e}"))?;
115 if let Some(GoValue::Object(siwc)) = meta.as_ref().and_then(|m| m.get("siwc"))
116 && let Some(GoValue::String(id)) = siwc.get("device_id")
117 && crate::codex_siwc::is_valid_uuid(id)
118 {
119 return Ok(id.trim().go_lower());
120 }
121 Ok(uuid::Uuid::new_v4().to_string())
122}
123
124pub fn save(path: &Path, tokens: &Tokens) -> Result<(), String> {
129 with_file_lock(path, || {
130 let data = std::fs::read(path).map_err(|e| format!("failed to read existing credential file: {e}"))?;
131 let meta = decode(&data).map_err(|e| format!("failed to parse existing credential file: {e}"))?;
132 validate(meta.as_ref())?;
133 let mut meta = meta.unwrap_or_default();
134 meta.insert("use_siwc".into(), GoValue::Bool(true));
136 meta.insert(
137 "siwc".into(),
138 GoValue::from_json(&serde_json::Value::Object(tokens.to_map())),
139 );
140 let bytes = GoValue::Object(meta).marshal();
141 let dir = path.parent().unwrap_or(Path::new("."));
142 crate::codex_oauth::publish(dir, path, &bytes).map_err(|e| format!("failed to replace credential file: {e}"))
143 })
144}
145
146pub fn with_file_lock<T>(path: &Path, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
152 let file = lock_file(path)?;
153 let result = f();
154 drop(file);
155 result
156}
157
158pub fn lock_file(path: &Path) -> Result<std::fs::File, String> {
161 let (file, lock_path) = open_lock(path)?;
162 lock(&file, true).map_err(|e| format!("failed to acquire flock on {}: {e}", lock_path.display()))?;
163 Ok(file)
164}
165
166pub fn open_lock_file(path: &Path) -> Result<std::fs::File, String> {
168 open_lock(path).map(|(file, _)| file)
169}
170
171pub fn try_lock(file: &std::fs::File) -> Result<bool, String> {
174 match lock(file, false) {
175 Ok(()) => Ok(true),
176 Err(e) if would_block(&e) => Ok(false),
177 Err(e) => Err(format!("failed to acquire credential lock: {e}")),
178 }
179}
180
181fn open_lock(path: &Path) -> Result<(std::fs::File, PathBuf), String> {
182 let mut lock_path = lock_base(path).into_os_string();
183 lock_path.push(".lock");
184 let lock_path = PathBuf::from(lock_path);
185 let mut options = std::fs::OpenOptions::new();
186 options.read(true).write(true).create(true).truncate(false);
187 #[cfg(unix)]
188 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
189 let file = options
190 .open(&lock_path)
191 .map_err(|e| format!("failed to open credential lock file {}: {e}", lock_path.display()))?;
192 Ok((file, lock_path))
193}
194
195#[cfg(unix)]
196fn lock(file: &std::fs::File, wait: bool) -> std::io::Result<()> {
197 use std::os::fd::AsRawFd;
198 let operation = if wait {
199 libc::LOCK_EX
200 } else {
201 libc::LOCK_EX | libc::LOCK_NB
202 };
203 loop {
204 if unsafe { libc::flock(file.as_raw_fd(), operation) } == 0 {
206 return Ok(());
207 }
208 let error = std::io::Error::last_os_error();
209 if error.kind() != std::io::ErrorKind::Interrupted {
210 return Err(error);
211 }
212 }
213}
214
215#[cfg(unix)]
216fn would_block(error: &std::io::Error) -> bool {
217 error.kind() == std::io::ErrorKind::WouldBlock
218}
219
220#[cfg(windows)]
221fn lock(file: &std::fs::File, wait: bool) -> std::io::Result<()> {
222 use std::os::windows::io::AsRawHandle;
223 use windows_sys::Win32::Storage::FileSystem::{LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx};
224 let flags = if wait {
225 LOCKFILE_EXCLUSIVE_LOCK
226 } else {
227 LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY
228 };
229 let ok = unsafe {
232 let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED = std::mem::zeroed();
233 LockFileEx(file.as_raw_handle() as _, flags, 0, 1, 0, &mut overlapped)
234 };
235 if ok == 0 {
236 Err(std::io::Error::last_os_error())
237 } else {
238 Ok(())
239 }
240}
241
242#[cfg(windows)]
243fn would_block(error: &std::io::Error) -> bool {
244 error.raw_os_error() == Some(33)
246}
247
248#[cfg(not(any(unix, windows)))]
249fn lock(_: &std::fs::File, _: bool) -> std::io::Result<()> {
250 Ok(())
251}
252
253#[cfg(not(any(unix, windows)))]
254fn would_block(_: &std::io::Error) -> bool {
255 false
256}
257
258fn go_clean(path: &Path) -> PathBuf {
260 use std::path::Component;
261 let mut out: Vec<Component<'_>> = Vec::new();
262 for component in path.components() {
263 match component {
264 Component::CurDir => {}
265 Component::ParentDir => match out.last() {
266 Some(Component::Normal(_)) => {
267 out.pop();
268 }
269 Some(Component::RootDir | Component::Prefix(_)) => {}
270 _ => out.push(component),
271 },
272 other => out.push(other),
273 }
274 }
275 if out.is_empty() {
276 return PathBuf::from(".");
277 }
278 out.iter().collect()
279}
280
281#[cfg(windows)]
286pub fn plain_path(path: PathBuf) -> PathBuf {
287 use std::os::windows::ffi::{OsStrExt, OsStringExt};
288 use std::path::{Component, Prefix};
289 let wide: Vec<u16> = path.as_os_str().encode_wide().collect();
290 let plain = match path.components().next() {
291 Some(Component::Prefix(p)) => match p.kind() {
292 Prefix::VerbatimDisk(_) => wide[4..].to_vec(),
294 Prefix::VerbatimUNC(..) => [&[u16::from(b'\\'); 2][..], &wide[8..]].concat(),
295 _ => return path,
296 },
297 _ => return path,
298 };
299 PathBuf::from(std::ffi::OsString::from_wide(&plain))
300}
301
302#[cfg(not(windows))]
304pub fn plain_path(path: PathBuf) -> PathBuf {
305 path
306}
307
308fn go_abs(path: &Path) -> std::io::Result<PathBuf> {
310 std::path::absolute(go_clean(path)).map(|p| go_clean(&p))
311}
312
313fn lock_base(path: &Path) -> PathBuf {
317 let trimmed = path.to_str().map_or(path, |s| Path::new(s.trim()));
318 go_abs(trimmed).unwrap_or_else(|_| go_clean(trimmed))
319}
320
321pub async fn bind(cfg: &Config, target: &str, options: &LoginOptions) -> Result<PathBuf, BindError> {
324 let port = match options.callback_port {
325 0 => CALLBACK_PORT,
326 port => port,
327 };
328 let no_browser = options.no_browser;
329 let interaction = Interaction {
330 manual_delay: Duration::from_secs(15),
331 prompt: Some(Box::new(|| {
332 Box::pin(async {
333 use std::io::Write;
334 print!("Paste the callback URL (or press Enter to keep waiting): ");
335 let _ = std::io::stdout().flush();
336 let (tx, rx) = tokio::sync::oneshot::channel();
338 std::thread::spawn(move || {
339 let mut line = String::new();
340 let _ = tx.send(std::io::stdin().read_line(&mut line).map(|_| line));
341 });
342 rx.await.map_err(std::io::Error::other)?
343 })
344 })),
345 show_url: Box::new(move |url| show_url(url, port, no_browser)),
346 };
347 let proxy = cfg
349 .document
350 .get("requests")
351 .and_then(|r| r.get("proxy-url"))
352 .and_then(|v| v.as_str())
353 .unwrap_or_default();
354 let client = crate::proxy::GoClients::new(Default::default()).get(&crate::proxy::Proxy::parse(proxy));
355 bind_with(cfg, target, port, CodexOAuth::new(client), interaction).await
356}
357
358fn show_url(url: &str, port: u16, no_browser: bool) {
359 if !no_browser {
360 println!("Opening browser for OpenAI Sign in with ChatGPT authentication");
361 if crate::claude_login::open_browser(url) {
362 println!("Waiting for Sign in with ChatGPT authentication callback...");
363 return;
364 }
365 tracing::warn!("No browser available; please open the URL manually");
366 }
367 crate::claude_login::print_ssh_tunnel_instructions(port);
368 println!("Visit the following URL to continue authentication:\n{url}");
369 println!("Waiting for Sign in with ChatGPT authentication callback...");
370}
371
372pub(crate) async fn bind_with(
374 cfg: &Config,
375 target: &str,
376 port: u16,
377 oauth: CodexOAuth,
378 interaction: Interaction,
379) -> Result<PathBuf, BindError> {
380 let path = resolve(&cfg.auth_dir, target).map_err(BindError::Log)?;
381 let device = {
382 let path = path.clone();
383 tokio::task::spawn_blocking(move || device_id(&path))
384 .await
385 .map_err(|e| BindError::Log(format!("siwc-bind: {e}")))?
386 .map_err(|e| BindError::Log(format!("siwc-bind: {e}")))?
387 };
388 let redirect = format!("http://127.0.0.1:{port}/auth/callback");
389 let (verifier, challenge) =
390 crate::oauth::pkce().map_err(|_| BindError::Log("siwc-bind: PKCE generation failed".into()))?;
391 let random = |what: &str| {
392 crate::codex_siwc::random_base64url()
393 .map_err(|_| BindError::Log(format!("siwc-bind: {what} generation failed")))
394 };
395 let (state, nonce) = (random("state")?, random("nonce")?);
396 let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
399 .await
400 .map_err(|_| BindError::PortInUse)?;
401 let identifier = crate::codex_siwc::identifier(cfg);
402 let url =
403 crate::codex_siwc::authorize_url(&state, &nonce, &device, &redirect, &challenge, &identifier).map_err(|e| {
404 BindError::Log(format!(
405 "siwc-bind: failed to generate authorization URL: {}",
406 String::from_utf8_lossy(&e.body)
407 ))
408 })?;
409 let (results, mut callbacks) = tokio::sync::mpsc::channel(1);
412 let server = tokio::spawn(async move {
413 while let Ok(callback) = crate::codex_oauth::callback(&listener).await {
414 let _ = results.try_send(callback);
415 }
416 });
417 (interaction.show_url)(&url);
418 let result = async {
419 let failed = |e: String| BindError::Print(format!("Sign in with ChatGPT authentication failed: {e}"));
420 let (code, got_state, client_id, error, description) =
421 wait(&mut callbacks, interaction.manual_delay, interaction.prompt)
422 .await
423 .map_err(failed)?;
424 if !error.is_empty() {
425 return Err(failed(if description.is_empty() {
427 format!("OAuth error: {error}")
428 } else {
429 format!("OAuth error {error}: {description}")
430 }));
431 }
432 if got_state != state {
433 return Err(failed("state mismatch".into()));
434 }
435 if client_id.trim().is_empty() {
436 return Err(failed("callback did not contain an issued client ID".into()));
437 }
438 let tokens = oauth
439 .exchange_siwc(&code, &client_id, &redirect, &device, &verifier)
440 .await
441 .map_err(|e| {
442 BindError::Print(format!(
443 "Sign in with ChatGPT token exchange failed: {}",
444 String::from_utf8_lossy(&e.body)
445 ))
446 })?;
447 println!("Saving credentials to {}", path.display());
449 let target = path.clone();
450 tokio::task::spawn_blocking(move || save(&target, &tokens))
451 .await
452 .map_err(|e| e.to_string())
453 .and_then(|r| r)
454 .map_err(|e| BindError::Print(format!("Failed to save SIWC credentials: {e}")))?;
455 Ok(path)
456 }
457 .await;
458 tokio::time::sleep(Duration::from_millis(200)).await;
460 server.abort();
461 result
462}
463
464async fn wait(
468 callbacks: &mut tokio::sync::mpsc::Receiver<crate::codex_oauth::Callback>,
469 delay: Duration,
470 prompt: Option<crate::claude_login::Prompt>,
471) -> Result<(String, String, String, String, String), String> {
472 let deadline = tokio::time::sleep(Duration::from_secs(300));
473 tokio::pin!(deadline);
474 let manual = async {
475 let prompt = prompt?;
476 tokio::time::sleep(delay).await;
477 Some(prompt().await)
478 };
479 tokio::pin!(manual);
480 let mut manual_done = false;
481 loop {
482 tokio::select! {
483 biased;
484 Some(c) = callbacks.recv() => {
485 return Ok((c.code, c.state, c.client_id, c.error.unwrap_or_default(), String::new()));
486 }
487 () = &mut deadline => return Err("timeout waiting for OAuth callback".into()),
488 input = &mut manual, if !manual_done => {
489 manual_done = true;
490 let Some(input) = input else { continue };
491 let input = input.map_err(|e| e.to_string())?;
492 if let Some(c) = parse_callback_input(&input)? {
493 return Ok((c.code, c.state, c.client_id, c.error, c.description));
494 }
495 }
496 }
497 }
498}
499
500#[cfg(test)]
501#[path = "codex_siwc_bind_tests.rs"]
502mod tests;