| 1 | //! ChatGPT (Codex) and Grok subscription auth, fx.sh-compatible. |
| 2 | //! |
| 3 | //! Mirrors fx's credential model (`src/core/auth/` in vercel-labs/fx): |
| 4 | //! - Codex session: `~/.fx/chatgpt-auth.json` (`{version:1, access_token, |
| 5 | //! refresh_token, expires_at_ms, account_id}`), refreshed against |
| 6 | //! `https://auth.openai.com/oauth/token` with the public Codex client id. |
| 7 | //! - Grok session: `~/.fx/grok-auth.json` (same shape), refreshed against |
| 8 | //! `https://auth.x.ai/oauth2/token`. |
| 9 | //! - Codex fallback: `~/.codex/auth.json` (the Codex CLI's own login). When no |
| 10 | //! fx codex session exists we reuse the CLI's tokens directly so a user who |
| 11 | //! ran `codex login` (or the ChatGPT app) works out of the box. |
| 12 | //! |
| 13 | //! The subscription tokens never go to the Vercel AI Gateway — codex calls go |
| 14 | //! to `https://chatgpt.com/backend-api/codex/responses`, grok calls to |
| 15 | //! `https://cli-chat-proxy.grok.com/v1/responses` (same as fx). |
| 16 | |
| 17 | use std::time:: |
| 18 | |
| 19 | use anyhow::{Context |
| 20 | use serde_json::{Value |
| 21 | |
| 22 | /// Public Codex OAuth client id (fx `chatgpt_oauth::client_id`). Shared |
| 23 | /// between fx, Codex CLI and wynba so tokens are interchangeable. |
| 24 | pub const CODEX_CLIENT_ID: |
| 25 | pub const CODEX_TOKEN_URL: |
| 26 | pub const CODEX_AUTH_URL: |
| 27 | pub const CODEX_RESPONSES_URL: |
| 28 | pub const CODEX_MODELS_URL: |
| 29 | |
| 30 | /// Public Grok OAuth client id (fx `grok_oauth::client_id`). |
| 31 | pub const GROK_CLIENT_ID: |
| 32 | pub const GROK_TOKEN_URL: |
| 33 | pub const GROK_AUTH_URL: |
| 34 | pub const GROK_USERINFO_URL: |
| 35 | pub const GROK_REVOKE_URL: |
| 36 | pub const GROK_RESPONSES_URL: |
| 37 | pub const GROK_MODELS_URL: |
| 38 | |
| 39 | /// Refresh a minute before expiry (fx `expiry_skew_ms`). |
| 40 | const EXPIRY_SKEW_MS: i64 |
| 41 | |
| 42 | #[derive(Clone |
| 43 | pub struct SubSession |
| 44 | pub access_token: String |
| 45 | pub refresh_token: String |
| 46 | pub expires_at_ms: i64 |
| 47 | pub account_id: String |
| 48 | } |
| 49 | |
| 50 | fn now_ms() -> i64 |
| 51 | chrono::Utc:: |
| 52 | } |
| 53 | |
| 54 | impl SubSession { |
| 55 | fn expired(&self |
| 56 | self.expires_at_ms - EXPIRY_SKEW_MS |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | fn home() -> Result |
| 61 | std::env::var |
| 62 | } |
| 63 | |
| 64 | pub fn codex_auth_path() -> |
| 65 | Ok(format! |
| 66 | } |
| 67 | |
| 68 | pub fn grok_auth_path() -> |
| 69 | Ok(format! |
| 70 | } |
| 71 | |
| 72 | fn fx_settings_path() -> Result |
| 73 | Ok(format! |
| 74 | } |
| 75 | |
| 76 | fn parse_fx_session(bytes: |
| 77 | let v: Value |
| 78 | let obj = |
| 79 | if obj.get( |
| 80 | bail!("unsupported subscription session version"); |
| 81 | } |
| 82 | let get = |
| 83 | obj.get(k |
| 84 | .and_then(|x| |
| 85 | .filter(|s| |
| 86 | .map(|s| |
| 87 | .with_context(|| format! |
| 88 | }; |
| 89 | let s = |
| 90 | access_token: get(" |
| 91 | refresh_token: get(" |
| 92 | expires_at_ms: obj |
| 93 | .get("expires_at_ms") |
| 94 | .and_then(|x| |
| 95 | .context("subscription session missing 'expires_at_ms'") |
| 96 | account_id: get(" |
| 97 | }; |
| 98 | if !valid_account_id(&s |
| 99 | bail!("invalid account id in subscription session"); |
| 100 | } |
| 101 | Ok(s) |
| 102 | } |
| 103 | |
| 104 | fn stringify_session(s: |
| 105 | Ok(serde_json:: |
| 106 | "version": 1, |
| 107 | "access_token": s. |
| 108 | "refresh_token": s. |
| 109 | "expires_at_ms": s. |
| 110 | "account_id": s. |
| 111 | }))?) |
| 112 | } |
| 113 | |
| 114 | fn valid_account_id(id: |
| 115 | // fx `types::validCredentialAccountId`: printable ASCII, bounded. |
| 116 | !id.is_empty() |
| 117 | && id.len() |
| 118 | && id.bytes() |
| 119 | } |
| 120 | |
| 121 | fn load_fx_session(path: |
| 122 | let bytes = |
| 123 | parse_fx_session(&bytes). |
| 124 | } |
| 125 | |
| 126 | fn save_fx_session(path: |
| 127 | if let Some |
| 128 | std::fs::create_dir_all |
| 129 | } |
| 130 | let text = |
| 131 | atomic_write_secure(path, & |
| 132 | Ok(()) |
| 133 | } |
| 134 | |
| 135 | /// Atomic write via tmp + rename so a crash mid-write can't corrupt login |
| 136 | /// files. Sets 0o600 on unix. |
| 137 | fn atomic_write_secure(path: |
| 138 | let tmp = |
| 139 | std::fs::write |
| 140 | #[cfg(unix |
| 141 | { |
| 142 | use std::os |
| 143 | let _ = |
| 144 | } |
| 145 | std::fs::rename |
| 146 | #[cfg(unix |
| 147 | { |
| 148 | use std::os |
| 149 | let _ = |
| 150 | } |
| 151 | Ok(()) |
| 152 | } |
| 153 | |
| 154 | /// Atomic write for non-secret files (no chmod). |
| 155 | fn atomic_write(path: |
| 156 | let tmp = |
| 157 | std::fs::write |
| 158 | std::fs::rename |
| 159 | Ok(()) |
| 160 | } |
| 161 | |
| 162 | /// Decode the `chatgpt_account_id` claim from a ChatGPT JWT access token |
| 163 | /// (fx `chatgpt_oauth::extractAccountId`: payload claim |
| 164 | /// `https://api.openai.com/auth` -> `chatgpt_account_id`). |
| 165 | pub fn codex_account_id_from_token(token |
| 166 | let mut parts |
| 167 | let (_h, |
| 168 | parts.next().context |
| 169 | parts.next().context |
| 170 | parts.next().context |
| 171 | ); |
| 172 | if parts.next() |
| 173 | bail!("invalid JWT"); |
| 174 | } |
| 175 | let decoded = |
| 176 | let v: Value |
| 177 | let id = |
| 178 | .get("https://api.openai.com/auth") |
| 179 | .and_then(|c| |
| 180 | .and_then(|x| |
| 181 | .context("JWT has no chatgpt_account_id claim") |
| 182 | if !valid_account_id(id |
| 183 | bail!("invalid chatgpt_account_id in token"); |
| 184 | } |
| 185 | Ok(id. |
| 186 | } |
| 187 | |
| 188 | fn base64_url_decode(s: |
| 189 | use base64::{Engine |
| 190 | // JWTs are unpadded, but tolerate padded input by stripping `=`. |
| 191 | let trimmed = |
| 192 | URL_SAFE_NO_PAD |
| 193 | .decode(trimmed) |
| 194 | .with_context(|| "invalid base64url |
| 195 | } |
| 196 | |
| 197 | fn base64_url_encode(bytes: |
| 198 | use base64::{Engine |
| 199 | URL_SAFE_NO_PAD.encode(bytes |
| 200 | } |
| 201 | |
| 202 | fn random_secret() -> String |
| 203 | // 32 bytes of entropy, base64url-encoded (fx `randomUrlSafeSecret`). |
| 204 | let mut bytes |
| 205 | #[cfg(unix |
| 206 | { |
| 207 | use std::io |
| 208 | if let Ok |
| 209 | let _ = |
| 210 | } |
| 211 | } |
| 212 | if bytes.iter() |
| 213 | // Fallback when /dev/urandom is unavailable (non-Unix or sandbox): |
| 214 | // hash time + pid + a fresh v4 UUID. Weaker than OS entropy — only |
| 215 | // used for PKCE verifier/state, never for long-lived secrets — and |
| 216 | // the UUID adds per-call uniqueness the old time+pid hash lacked. |
| 217 | use sha2::{Digest |
| 218 | let mut h |
| 219 | h.update(now_ms |
| 220 | h.update(std |
| 221 | h.update(uuid |
| 222 | let d = |
| 223 | bytes.copy_from_slice(&d |
| 224 | } |
| 225 | base64_url_encode(&bytes) |
| 226 | } |
| 227 | |
| 228 | fn pkce_challenge(verifier: |
| 229 | use sha2::{Digest |
| 230 | let mut h |
| 231 | h.update(verifier |
| 232 | base64_url_encode(&h.finalize |
| 233 | } |
| 234 | |
| 235 | fn percent_encode(s: |
| 236 | let mut out |
| 237 | for b in s |
| 238 | if b.is_ascii_alphanumeric() |
| 239 | out.push(b |
| 240 | } else { |
| 241 | out.push_str(&format! |
| 242 | } |
| 243 | } |
| 244 | out |
| 245 | } |
| 246 | |
| 247 | // --------------------------------------------------------------------------- |
| 248 | // Codex |
| 249 | // --------------------------------------------------------------------------- |
| 250 | |
| 251 | /// Codex CLI's own session (`~/.codex/auth.json`, auth_mode=chatgpt). |
| 252 | /// Returns (access_token, refresh_token, account_id) when usable. |
| 253 | fn load_codex_cli_session() -> Option |
| 254 | let path = |
| 255 | let text = |
| 256 | let v: Value |
| 257 | if v.get( |
| 258 | && v.get( |
| 259 | { |
| 260 | return None; |
| 261 | } |
| 262 | let tokens = |
| 263 | let access = |
| 264 | if access.is_empty() |
| 265 | return None; |
| 266 | } |
| 267 | let refresh = |
| 268 | .get("refresh_token") |
| 269 | .and_then(|x| |
| 270 | .filter(|s| |
| 271 | .map(|s| |
| 272 | let account = |
| 273 | .get("account_id") |
| 274 | .and_then(|x| |
| 275 | .filter(|s| |
| 276 | .map(|s| |
| 277 | .or_else(|| codex_account_id_from_token |
| 278 | Some((access, |
| 279 | } |
| 280 | |
| 281 | /// Valid credential for the Codex subscription route: (access_token, |
| 282 | /// account_id). Prefers `~/.fx/chatgpt-auth.json` (fx/wynba login), falls |
| 283 | /// back to the Codex CLI's `~/.codex/auth.json`, and refreshes expired fx |
| 284 | /// sessions in place. |
| 285 | pub fn codex_access() -> |
| 286 | let path = |
| 287 | if let Some |
| 288 | if !s.expired |
| 289 | return Ok((s |
| 290 | } |
| 291 | // Refresh in place (fx `refreshSession`: JSON POST, rotate tokens, |
| 292 | // verify the account didn't change, persist). |
| 293 | refresh_codex_session(&mut s |
| 294 | save_fx_session(&path, |
| 295 | return Ok((s |
| 296 | } |
| 297 | // Fallback: the Codex CLI's own login. |
| 298 | if let Some |
| 299 | let account = |
| 300 | codex_account_id_from_token(&access). |
| 301 | }); |
| 302 | if account.is_empty() |
| 303 | bail!("Codex CLI session has no account id — run `wynba login codex`"); |
| 304 | } |
| 305 | // The CLI's access token may be expired (the CLI refreshes lazily) — |
| 306 | // refresh eagerly when a refresh token is available so the first call |
| 307 | // works instead of dying on a 401. |
| 308 | let expired = |
| 309 | if expired { |
| 310 | if let Some |
| 311 | let mut tmp |
| 312 | access_token: access.clone |
| 313 | refresh_token: rt, |
| 314 | expires_at_ms: 0, |
| 315 | account_id: account.clone |
| 316 | }; |
| 317 | refresh_codex_session(&mut tmp |
| 318 | save_fx_session(&path, |
| 319 | return Ok((tmp |
| 320 | } |
| 321 | bail!("Codex CLI session is expired — run `wynba login codex`"); |
| 322 | } |
| 323 | // Seed the fx session file so refresh works next time (when we have a |
| 324 | // refresh token); never fail the call over the seed. |
| 325 | if let Some |
| 326 | let exp_ms = |
| 327 | let _ = |
| 328 | &path, |
| 329 | &SubSession { |
| 330 | access_token: access.clone |
| 331 | refresh_token: rt, |
| 332 | expires_at_ms: exp_ms, |
| 333 | account_id: account.clone |
| 334 | }, |
| 335 | ); |
| 336 | } |
| 337 | return Ok((access |
| 338 | } |
| 339 | bail!("not signed in to Codex — run `wynba login codex` (or `fx login codex`)") |
| 340 | } |
| 341 | |
| 342 | fn jwt_exp_ms(token: |
| 343 | let payload = |
| 344 | let decoded = |
| 345 | let v: Value |
| 346 | v.get("exp |
| 347 | } |
| 348 | |
| 349 | fn refresh_codex_session(s: |
| 350 | let body = |
| 351 | "client_id": CODEX_CLIENT_ID, |
| 352 | "grant_type": "refresh_token", |
| 353 | "refresh_token": s. |
| 354 | }); |
| 355 | let resp = |
| 356 | .timeout(Duration::from_secs |
| 357 | .set("Content-Type", |
| 358 | .send_json(&body); |
| 359 | let resp = |
| 360 | Ok(r) |
| 361 | Err(ureq:: |
| 362 | let text = |
| 363 | if text.contains( |
| 364 | || text.contains( |
| 365 | || text.contains( |
| 366 | || text.contains( |
| 367 | { |
| 368 | let _ = |
| 369 | bail!("Codex session expired — run `wynba login codex`"); |
| 370 | } |
| 371 | bail!("Codex refresh failed: {text |
| 372 | } |
| 373 | Err(e) |
| 374 | }; |
| 375 | let v: Value |
| 376 | let access = |
| 377 | .get("access_token") |
| 378 | .and_then(|x| |
| 379 | .context("Codex refresh missing access_token") |
| 380 | .to_string(); |
| 381 | let account = |
| 382 | if account != s |
| 383 | let _ = |
| 384 | bail!("Codex account changed during refresh — run `wynba login codex`"); |
| 385 | } |
| 386 | s.access_token = access |
| 387 | if let Some |
| 388 | s.refresh_token = rt |
| 389 | } |
| 390 | s.expires_at_ms = v |
| 391 | .get("expires_in") |
| 392 | .and_then(|x| |
| 393 | .map(|e| |
| 394 | .or_else(|| jwt_exp_ms |
| 395 | .unwrap_or_else(|| now_ms |
| 396 | Ok(()) |
| 397 | } |
| 398 | |
| 399 | /// Browser PKCE login for the Codex subscription (fx `fx login codex`): |
| 400 | /// localhost callback, code exchange, account extraction, save to |
| 401 | /// `~/.fx/chatgpt-auth.json`. |
| 402 | pub fn login_codex() -> |
| 403 | let verifier = |
| 404 | let challenge = |
| 405 | let state = |
| 406 | let listener = |
| 407 | std::net::TcpListener |
| 408 | let port = |
| 409 | let redirect_uri = |
| 410 | let auth_url = |
| 411 | "{CODEX_AUTH_URL}?response_type=code&client_id={}&redirect_uri={} |
| 412 | percent_encode(CODEX_CLIENT_ID), |
| 413 | percent_encode(&redirect_uri), |
| 414 | percent_encode("openid profile email offline_access api.connectors.read api.connectors.invoke"), |
| 415 | percent_encode(&challenge), |
| 416 | percent_encode(&state), |
| 417 | ); |
| 418 | println!("Opening browser for ChatGPT sign-in…"); |
| 419 | println!("If the browser doesn't open, visit:\n |
| 420 | let _ = |
| 421 | // Same ask-first shape as Grok: an empty line waits for the browser |
| 422 | // callback; a pasted code skips it (localhost may be unreachable). |
| 423 | let code = |
| 424 | Some(c) |
| 425 | None => { |
| 426 | println!("Waiting for the browser to return… (press Ctrl+C to cancel)"); |
| 427 | match wait_for_oauth_code(listener, |
| 428 | Ok(c) |
| 429 | Err(e) |
| 430 | println!("Browser callback didn't complete ({e:# |
| 431 | read_pasted_code_loop("authorization code")? |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | }; |
| 436 | // Exchange the code (form POST, fx `exchangeAuthorizationCodeForRedirect`). |
| 437 | let form = |
| 438 | ("grant_type", "authorization_code" |
| 439 | ("client_id", CODEX_CLIENT_ID |
| 440 | ("code", &code |
| 441 | ("code_verifier", &verifier |
| 442 | ("redirect_uri", &redirect_uri |
| 443 | ]; |
| 444 | let resp = |
| 445 | .timeout(Duration::from_secs |
| 446 | .send_form(&form) |
| 447 | .map_err(|e| |
| 448 | ureq::Error::Status |
| 449 | anyhow::anyhow!( |
| 450 | } |
| 451 | e => anyhow:: |
| 452 | })?; |
| 453 | let v: Value |
| 454 | let access = |
| 455 | .get("access_token") |
| 456 | .and_then(|x| |
| 457 | .context("Codex sign-in missing access_token") |
| 458 | .to_string(); |
| 459 | let refresh = |
| 460 | .get("refresh_token") |
| 461 | .and_then(|x| |
| 462 | .context("Codex sign-in missing refresh_token") |
| 463 | .to_string(); |
| 464 | let expires_in = |
| 465 | .get("expires_in") |
| 466 | .and_then(|x| |
| 467 | .unwrap_or(3600); |
| 468 | let account = |
| 469 | let session = |
| 470 | access_token: access, |
| 471 | refresh_token: refresh, |
| 472 | expires_at_ms: now_ms() |
| 473 | account_id: account, |
| 474 | }; |
| 475 | let path = |
| 476 | save_fx_session(&path, |
| 477 | Ok(path) |
| 478 | } |
| 479 | |
| 480 | pub fn logout_codex() -> |
| 481 | // fx `fx logout codex` removes the local session only (withdrawing access |
| 482 | // happens in the ChatGPT account's connected apps). |
| 483 | let path = |
| 484 | match std::fs |
| 485 | Ok(()) => Ok |
| 486 | Err(e) |
| 487 | Err(e) |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | pub fn codex_signed_in() -> |
| 492 | codex_auth_path() |
| 493 | .ok() |
| 494 | .and_then(|p| |
| 495 | .is_some() |
| 496 | || load_codex_cli_session().is_some |
| 497 | } |
| 498 | |
| 499 | // --------------------------------------------------------------------------- |
| 500 | // Grok |
| 501 | // --------------------------------------------------------------------------- |
| 502 | |
| 503 | pub fn grok_access() -> |
| 504 | let path = |
| 505 | let mut s |
| 506 | .with_context(|| "not signed in to Grok — run `wynba login grok` (or `fx login grok`) |
| 507 | if s.expired() |
| 508 | refresh_grok_session(&mut s |
| 509 | save_fx_session(&path, |
| 510 | } |
| 511 | Ok((s. |
| 512 | } |
| 513 | |
| 514 | fn refresh_grok_session(s: |
| 515 | let form = |
| 516 | ("grant_type", "refresh_token" |
| 517 | ("client_id", GROK_CLIENT_ID |
| 518 | ("refresh_token", s |
| 519 | ]; |
| 520 | let resp = |
| 521 | .timeout(Duration::from_secs |
| 522 | .send_form(&form); |
| 523 | let resp = |
| 524 | Ok(r) |
| 525 | Err(ureq:: |
| 526 | let text = |
| 527 | if text.contains( |
| 528 | let _ = |
| 529 | bail!("Grok session expired — run `wynba login grok`"); |
| 530 | } |
| 531 | bail!("Grok refresh failed: {text |
| 532 | } |
| 533 | Err(e) |
| 534 | }; |
| 535 | let v: Value |
| 536 | let access = |
| 537 | .get("access_token") |
| 538 | .and_then(|x| |
| 539 | .context("Grok refresh missing access_token") |
| 540 | .to_string(); |
| 541 | let account = |
| 542 | if account != s |
| 543 | let _ = |
| 544 | bail!("Grok account changed during refresh — run `wynba login grok`"); |
| 545 | } |
| 546 | s.access_token = access |
| 547 | if let Some |
| 548 | s.refresh_token = rt |
| 549 | } |
| 550 | s.expires_at_ms = v |
| 551 | .get("expires_in") |
| 552 | .and_then(|x| |
| 553 | .map(|e| |
| 554 | .unwrap_or_else(|| now_ms |
| 555 | Ok(()) |
| 556 | } |
| 557 | |
| 558 | fn grok_userinfo_sub(access_token: |
| 559 | let resp = |
| 560 | .timeout(Duration::from_secs |
| 561 | .set("Authorization", |
| 562 | .call() |
| 563 | .map_err(|e| |
| 564 | let v: Value |
| 565 | let sub = |
| 566 | .get("sub") |
| 567 | .and_then(|x| |
| 568 | .context("Grok userinfo missing sub") |
| 569 | if !valid_account_id(sub |
| 570 | bail!("invalid Grok account id"); |
| 571 | } |
| 572 | Ok(sub. |
| 573 | } |
| 574 | |
| 575 | /// Browser PKCE login for the Grok subscription (fx `fx login grok`). |
| 576 | pub fn login_grok() -> |
| 577 | let verifier = |
| 578 | let challenge = |
| 579 | let state = |
| 580 | let listener = |
| 581 | std::net::TcpListener |
| 582 | let port = |
| 583 | let redirect_uri = |
| 584 | let auth_url = |
| 585 | "{GROK_AUTH_URL}?response_type=code&client_id={}&redirect_uri={} |
| 586 | percent_encode(GROK_CLIENT_ID), |
| 587 | percent_encode(&redirect_uri), |
| 588 | percent_encode("openid profile email offline_access grok-cli:access api:access"), |
| 589 | percent_encode(&challenge), |
| 590 | percent_encode(&state), |
| 591 | ); |
| 592 | println!("Opening browser for Grok sign-in…"); |
| 593 | println!("If the browser doesn't open, visit:\n |
| 594 | let _ = |
| 595 | // Ask first: when the browser can't return to wynba (remote/headless), |
| 596 | // xAI shows a code to paste — and the local callback may also get stray |
| 597 | // non-OAuth connections, so pasting must always be on the table. Empty |
| 598 | // input falls through to the localhost callback below. |
| 599 | let code = |
| 600 | Some(c) |
| 601 | None => { |
| 602 | println!("Waiting for the browser to return… (press Ctrl+C to cancel)"); |
| 603 | match wait_for_oauth_code(listener, |
| 604 | Ok(c) |
| 605 | Err(e) |
| 606 | // Callback failed (timeout/denial) — fall back to paste, |
| 607 | // looping until a code arrives (fx parity). |
| 608 | println!("Browser callback didn't complete ({e:# |
| 609 | read_pasted_code_loop("authorization code")? |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | }; |
| 614 | let form = |
| 615 | ("grant_type", "authorization_code" |
| 616 | ("client_id", GROK_CLIENT_ID |
| 617 | ("code", code |
| 618 | ("code_verifier", verifier |
| 619 | ("redirect_uri", redirect_uri |
| 620 | ]; |
| 621 | let resp = |
| 622 | .timeout(Duration::from_secs |
| 623 | .send_form(&form) |
| 624 | .map_err(|e| |
| 625 | ureq::Error::Status |
| 626 | anyhow::anyhow!( |
| 627 | } |
| 628 | e => anyhow:: |
| 629 | })?; |
| 630 | let v: Value |
| 631 | let access = |
| 632 | .get("access_token") |
| 633 | .and_then(|x| |
| 634 | .context("Grok sign-in missing access_token") |
| 635 | .to_string(); |
| 636 | let refresh = |
| 637 | .get("refresh_token") |
| 638 | .and_then(|x| |
| 639 | .context("Grok sign-in missing refresh_token") |
| 640 | .to_string(); |
| 641 | let expires_in = |
| 642 | .get("expires_in") |
| 643 | .and_then(|x| |
| 644 | .context("Grok sign-in missing expires_in") |
| 645 | let account = |
| 646 | let session = |
| 647 | access_token: access, |
| 648 | refresh_token: refresh, |
| 649 | expires_at_ms: now_ms() |
| 650 | account_id: account, |
| 651 | }; |
| 652 | let path = |
| 653 | save_fx_session(&path, |
| 654 | Ok(path) |
| 655 | } |
| 656 | |
| 657 | pub fn logout_grok() -> |
| 658 | // fx `fx logout grok` revokes the token with xAI as well. |
| 659 | let path = |
| 660 | if let Some |
| 661 | let form = |
| 662 | ("token", s |
| 663 | ("client_id", GROK_CLIENT_ID |
| 664 | ]; |
| 665 | let _ = |
| 666 | .timeout(Duration::from_secs |
| 667 | .send_form(&form); |
| 668 | } |
| 669 | match std::fs |
| 670 | Ok(()) => Ok |
| 671 | Err(e) |
| 672 | Err(e) |
| 673 | } |
| 674 | } |
| 675 | |
| 676 | pub fn grok_signed_in() -> |
| 677 | grok_auth_path() |
| 678 | .ok() |
| 679 | .and_then(|p| |
| 680 | .is_some() |
| 681 | } |
| 682 | |
| 683 | // --------------------------------------------------------------------------- |
| 684 | // Claude (Claude Code subscription) |
| 685 | // --------------------------------------------------------------------------- |
| 686 | |
| 687 | /// Public Claude Code OAuth client id (the same one the Claude Code CLI |
| 688 | /// uses — tokens are interchangeable). |
| 689 | pub const CLAUDE_CLIENT_ID: |
| 690 | pub const CLAUDE_AUTH_URL: |
| 691 | pub const CLAUDE_TOKEN_URL: |
| 692 | pub const CLAUDE_REDIRECT_URI: |
| 693 | pub const CLAUDE_API_BASE: |
| 694 | /// Beta header Anthropic requires for subscription OAuth tokens. |
| 695 | pub const CLAUDE_OAUTH_BETA: |
| 696 | |
| 697 | fn claude_credentials_path() -> Result |
| 698 | Ok(format! |
| 699 | } |
| 700 | |
| 701 | /// Valid Claude OAuth credential: (access_token). Refreshes eagerly when |
| 702 | /// expired (the CLI refreshes lazily, so a stored token may be stale). |
| 703 | pub fn claude_access() -> |
| 704 | let path = |
| 705 | let text = |
| 706 | .with_context(|| "not signed in to Claude — run `wynba login claude` |
| 707 | let mut v |
| 708 | serde_json::from_str(&text |
| 709 | let oauth = |
| 710 | .get("claudeAiOauth") |
| 711 | .context("no Claude subscription login in ~/.claude/.credentials.json — run `wynba login claude`") |
| 712 | let access = |
| 713 | .get("accessToken") |
| 714 | .and_then(|x| |
| 715 | .unwrap_or("") |
| 716 | .to_string(); |
| 717 | let expires_at = |
| 718 | if !access.is_empty |
| 719 | return Ok(access |
| 720 | } |
| 721 | // Refresh in place, preserving the rest of the credentials file. |
| 722 | let refresh = |
| 723 | .get("refreshToken") |
| 724 | .and_then(|x| |
| 725 | .context("Claude session expired and has no refresh token — run `wynba login claude`") |
| 726 | .to_string(); |
| 727 | let (new_access, |
| 728 | if let Some |
| 729 | obj.insert("accessToken |
| 730 | obj.insert("refreshToken |
| 731 | obj.insert("expiresAt |
| 732 | } |
| 733 | atomic_write_secure(&path, |
| 734 | .context("failed to save refreshed Claude session") |
| 735 | Ok(new_access) |
| 736 | } |
| 737 | |
| 738 | fn refresh_claude_token(refresh_token: |
| 739 | let body = |
| 740 | "grant_type": "refresh_token", |
| 741 | "refresh_token": refresh_token, |
| 742 | "client_id": CLAUDE_CLIENT_ID, |
| 743 | }); |
| 744 | let resp = |
| 745 | .timeout(Duration::from_secs |
| 746 | .set("Content-Type", |
| 747 | .send_json(&body); |
| 748 | let resp = |
| 749 | Ok(r) |
| 750 | Err(ureq:: |
| 751 | let text = |
| 752 | bail!("Claude refresh failed ({text |
| 753 | } |
| 754 | Err(e) |
| 755 | }; |
| 756 | let v: Value |
| 757 | Ok(( |
| 758 | v.get("access_token |
| 759 | .and_then(|x| |
| 760 | .context("Claude refresh missing access_token") |
| 761 | .to_string(), |
| 762 | v.get("refresh_token |
| 763 | .and_then(|x| |
| 764 | .context("Claude refresh missing refresh_token") |
| 765 | .to_string(), |
| 766 | v.get("expires_in |
| 767 | )) |
| 768 | } |
| 769 | |
| 770 | /// Claude Code login: browser PKCE flow with a pasted authorization code |
| 771 | /// (Claude shows the code in the browser — no localhost callback needed). |
| 772 | pub fn login_claude() -> |
| 773 | let verifier = |
| 774 | let challenge = |
| 775 | let state = |
| 776 | let auth_url = |
| 777 | "{CLAUDE_AUTH_URL}?code=true&client_id={}&response_type=code&redirect_uri={} |
| 778 | percent_encode(CLAUDE_CLIENT_ID), |
| 779 | percent_encode(CLAUDE_REDIRECT_URI), |
| 780 | percent_encode("org:create_api_key user:profile workspace:create_api_key"), |
| 781 | percent_encode(&challenge), |
| 782 | percent_encode(&state), |
| 783 | ); |
| 784 | println!("Opening browser for Claude sign-in…"); |
| 785 | println!("If the browser doesn't open, visit:\n |
| 786 | let _ = |
| 787 | print!("Paste the authorization code shown in the browser: "); |
| 788 | use std::io |
| 789 | let _ = |
| 790 | let mut line |
| 791 | std::io::stdin |
| 792 | .read_line(&mut |
| 793 | .context("failed to read code") |
| 794 | // The browser shows `code#state`. |
| 795 | let pasted = |
| 796 | if pasted.is_empty() |
| 797 | bail!("no code entered"); |
| 798 | } |
| 799 | let (code, |
| 800 | let body = |
| 801 | "grant_type": "authorization_code", |
| 802 | "client_id": CLAUDE_CLIENT_ID, |
| 803 | "code": code, |
| 804 | "code_verifier": verifier, |
| 805 | "redirect_uri": CLAUDE_REDIRECT_URI, |
| 806 | "state": state, |
| 807 | }); |
| 808 | let resp = |
| 809 | .timeout(Duration::from_secs |
| 810 | .set("Content-Type", |
| 811 | .send_json(&body) |
| 812 | .map_err(|e| |
| 813 | ureq::Error::Status |
| 814 | anyhow::anyhow!( |
| 815 | } |
| 816 | e => anyhow:: |
| 817 | })?; |
| 818 | let v: Value |
| 819 | let access = |
| 820 | .get("access_token") |
| 821 | .and_then(|x| |
| 822 | .context("Claude sign-in missing access_token") |
| 823 | .to_string(); |
| 824 | let refresh = |
| 825 | .get("refresh_token") |
| 826 | .and_then(|x| |
| 827 | .context("Claude sign-in missing refresh_token") |
| 828 | .to_string(); |
| 829 | let expires_in = |
| 830 | let path = |
| 831 | // Merge into the existing credentials file (keep MCP/API-key entries). |
| 832 | let mut file |
| 833 | .ok() |
| 834 | .and_then(|t| |
| 835 | .unwrap_or_else(|| json! |
| 836 | if !file.is_object |
| 837 | file = json! |
| 838 | } |
| 839 | if let Some |
| 840 | obj.insert( |
| 841 | "claudeAiOauth".into(), |
| 842 | json!({ |
| 843 | "accessToken": access, |
| 844 | "refreshToken": refresh, |
| 845 | "expiresAt": now_ms() |
| 846 | "scopes": ["org:create_api_key" |
| 847 | }), |
| 848 | ); |
| 849 | } |
| 850 | if let Some |
| 851 | std::fs::create_dir_all |
| 852 | } |
| 853 | atomic_write_secure(&path, |
| 854 | Ok(path) |
| 855 | } |
| 856 | |
| 857 | pub fn logout_claude() -> |
| 858 | // Remove just the OAuth object — keep the rest of the Claude CLI state. |
| 859 | let path = |
| 860 | let text = |
| 861 | Ok(t) |
| 862 | Err(e) |
| 863 | Err(e) |
| 864 | }; |
| 865 | let mut v |
| 866 | let removed = |
| 867 | .as_object_mut() |
| 868 | .map(|o| |
| 869 | .unwrap_or(false); |
| 870 | if removed { |
| 871 | atomic_write_secure(&path, |
| 872 | } |
| 873 | Ok(removed) |
| 874 | } |
| 875 | |
| 876 | pub fn claude_signed_in() -> |
| 877 | claude_credentials_path() |
| 878 | .ok() |
| 879 | .and_then(|p| |
| 880 | .and_then(|t| |
| 881 | .and_then(|v| |
| 882 | v.get("claudeAiOauth |
| 883 | .get("accessToken") |
| 884 | .as_str() |
| 885 | .map(|s| |
| 886 | }) |
| 887 | .unwrap_or(false) |
| 888 | } |
| 889 | |
| 890 | // --------------------------------------------------------------------------- |
| 891 | // Shared login-callback server |
| 892 | // --------------------------------------------------------------------------- |
| 893 | |
| 894 | /// Serve one OAuth browser callback on `listener`: parse the GET target, |
| 895 | /// validate `state`, reply with an fx-style completion page, and return the |
| 896 | /// authorization `code`. Connections that are not the OAuth callback (stray |
| 897 | /// browser pre-connects, probes) are answered and ignored — only the real |
| 898 | /// callback or the deadline ends the wait, so a stray connection can never |
| 899 | /// abort the login before the user pastes or authorizes. |
| 900 | fn wait_for_oauth_code( |
| 901 | listener: std::net |
| 902 | provider: &str |
| 903 | expected_state: &str |
| 904 | callback_path: &str |
| 905 | ) -> Result<String |
| 906 | use std::io |
| 907 | // 5-minute browser login timeout (fx `browser_login_timeout_seconds`). |
| 908 | listener |
| 909 | .set_nonblocking(true) |
| 910 | .context("login listener failed") |
| 911 | let deadline = |
| 912 | let prefix = |
| 913 | loop { |
| 914 | if std::time |
| 915 | bail!("{provider} |
| 916 | } |
| 917 | match listener.accept() |
| 918 | Ok((mut |
| 919 | let _ = |
| 920 | let target = |
| 921 | let mut reader |
| 922 | let mut request_line |
| 923 | reader.read_line(&mut |
| 924 | // Drain headers. |
| 925 | loop { |
| 926 | let mut h |
| 927 | reader.read_line(&mut |
| 928 | if h.trim() |
| 929 | break; |
| 930 | } |
| 931 | } |
| 932 | Ok(request_line |
| 933 | .split_whitespace() |
| 934 | .nth(1) |
| 935 | .unwrap_or("") |
| 936 | .to_string()) |
| 937 | })() |
| 938 | .unwrap_or_default(); |
| 939 | if !target.starts_with |
| 940 | // Not the OAuth callback — ignore and keep waiting. |
| 941 | let page = |
| 942 | let _ = |
| 943 | stream, |
| 944 | "HTTP/1.1 404 Not Found\r\nContent-Length: {}\ |
| 945 | page.len() |
| 946 | ); |
| 947 | continue; |
| 948 | } |
| 949 | let result = |
| 950 | let (status, |
| 951 | Ok(_) |
| 952 | "200 OK", |
| 953 | "Signed in", |
| 954 | "You can close this tab and return to the terminal.", |
| 955 | ), |
| 956 | Err(_) |
| 957 | "400 Bad Request", |
| 958 | "Sign-in failed", |
| 959 | "The authorization response was invalid. Return to the terminal and try again.", |
| 960 | ), |
| 961 | }; |
| 962 | let page = |
| 963 | "<!doctype html><html><body style=\"background:#0a0a0a;color:#fff;font-family:sans-serif;display:flex;height:100vh;align-items:center;justify-content:center\"><div><h1> |
| 964 | ); |
| 965 | let _ = |
| 966 | stream, |
| 967 | "HTTP/1.1 {status}\r\n |
| 968 | page.len() |
| 969 | ); |
| 970 | return result.with_context( |
| 971 | } |
| 972 | Err(e) |
| 973 | std::thread::sleep |
| 974 | continue; |
| 975 | } |
| 976 | Err(e) |
| 977 | } |
| 978 | } |
| 979 | } |
| 980 | |
| 981 | /// Prompt for a pasted authorization code. Returns `Ok(None)` on an empty |
| 982 | /// line (caller falls through to the browser callback) and `Ok(Some(code))` |
| 983 | /// otherwise. EOF counts as empty so a closed stdin waits for the browser |
| 984 | /// instead of dying. |
| 985 | fn read_pasted_code(label: |
| 986 | use std::io |
| 987 | print!("Paste the {label |
| 988 | let _ = |
| 989 | let mut line |
| 990 | match std::io |
| 991 | Ok(_) |
| 992 | let code = |
| 993 | Ok(if code |
| 994 | } |
| 995 | Err(e) |
| 996 | } |
| 997 | } |
| 998 | |
| 999 | /// Paste loop used when the browser callback didn't complete: keeps asking |
| 1000 | /// until a code arrives (Ctrl+C aborts). |
| 1001 | fn read_pasted_code_loop(label: |
| 1002 | loop { |
| 1003 | match read_pasted_code(label) |
| 1004 | Some(c) |
| 1005 | None => println! |
| 1006 | } |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | fn parse_callback_target(target: |
| 1011 | let prefix = |
| 1012 | if !target.starts_with |
| 1013 | bail!("unexpected callback path"); |
| 1014 | } |
| 1015 | let query = |
| 1016 | let mut map |
| 1017 | for pair in query |
| 1018 | if let Some |
| 1019 | map.insert(percent_decode |
| 1020 | } |
| 1021 | } |
| 1022 | if let Some |
| 1023 | if map.get( |
| 1024 | bail!("authorization denied ({err |
| 1025 | } |
| 1026 | bail!("invalid callback state"); |
| 1027 | } |
| 1028 | let code = |
| 1029 | let state = |
| 1030 | if state != expected_state |
| 1031 | bail!("callback state mismatch"); |
| 1032 | } |
| 1033 | if code.is_empty() |
| 1034 | bail!("empty authorization code"); |
| 1035 | } |
| 1036 | Ok(code) |
| 1037 | } |
| 1038 | |
| 1039 | fn percent_decode(s: |
| 1040 | let mut out |
| 1041 | let b = |
| 1042 | let mut i |
| 1043 | while i < b |
| 1044 | if b[i] |
| 1045 | && let (Some |
| 1046 | { |
| 1047 | out.push(h |
| 1048 | i += 3; |
| 1049 | continue; |
| 1050 | } |
| 1051 | out.push(if |
| 1052 | i += 1; |
| 1053 | } |
| 1054 | String::from_utf8_lossy( |
| 1055 | } |
| 1056 | |
| 1057 | fn hex(b: |
| 1058 | match b { |
| 1059 | b'0'..=b'9' |
| 1060 | b'a'..=b'f' |
| 1061 | b'A'..=b'F' |
| 1062 | _ => None |
| 1063 | } |
| 1064 | } |
| 1065 | |
| 1066 | fn open_browser(url: |
| 1067 | #[cfg(target_os |
| 1068 | { |
| 1069 | std::process::Command |
| 1070 | Ok(()) |
| 1071 | } |
| 1072 | #[cfg(target_os |
| 1073 | { |
| 1074 | std::process::Command |
| 1075 | return Ok(()); |
| 1076 | } |
| 1077 | #[cfg(target_os |
| 1078 | { |
| 1079 | std::process::Command |
| 1080 | .args(["/c", |
| 1081 | .status()?; |
| 1082 | return Ok(()); |
| 1083 | } |
| 1084 | #[cfg(not |
| 1085 | { |
| 1086 | let _ = |
| 1087 | bail!("unsupported OS for opening browser"); |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | /// Read the per-provider saved model from `~/.fx/settings.json` |
| 1092 | /// (`models: {gateway, codex, grok}` — fx keeps separate selections so |
| 1093 | /// switching providers doesn't clobber another provider's model). |
| 1094 | pub fn fx_saved_model(provider |
| 1095 | let path = |
| 1096 | let text = |
| 1097 | let v: Value |
| 1098 | // New shape: models: { gateway|codex|grok: "<id>" }. |
| 1099 | if let Some |
| 1100 | .get("models") |
| 1101 | .and_then(|m| |
| 1102 | .and_then(|x| |
| 1103 | { |
| 1104 | let m = |
| 1105 | if !m.is_empty |
| 1106 | return Some(m |
| 1107 | } |
| 1108 | } |
| 1109 | // Legacy shape: top-level `model` (gateway only). |
| 1110 | if (provider == |
| 1111 | && let Some |
| 1112 | { |
| 1113 | let m = |
| 1114 | if !m.is_empty |
| 1115 | return Some(m |
| 1116 | } |
| 1117 | } |
| 1118 | None |
| 1119 | } |
| 1120 | |
| 1121 | /// Persist the per-provider model selection to `~/.fx/settings.json` so fx |
| 1122 | /// and wynba share it (fx `model_preferences`). Writes atomically; failures |
| 1123 | /// are logged via events instead of silently swallowed. |
| 1124 | pub fn fx_save_model(provider |
| 1125 | let Ok( |
| 1126 | let mut v |
| 1127 | .ok() |
| 1128 | .and_then(|t| |
| 1129 | .unwrap_or_else(|| json! |
| 1130 | if !v.is_object |
| 1131 | v = json! |
| 1132 | } |
| 1133 | let key = |
| 1134 | "fx" | "vercel" |
| 1135 | "codex" => "codex" |
| 1136 | "grok" => "grok" |
| 1137 | "claude-code" | "claude" |
| 1138 | _ => return, |
| 1139 | }; |
| 1140 | if let Some |
| 1141 | let models = |
| 1142 | .entry("models") |
| 1143 | .or_insert_with(|| json! |
| 1144 | if let Some |
| 1145 | mobj.insert(key |
| 1146 | } |
| 1147 | } |
| 1148 | if let Ok |
| 1149 | if let Err |
| 1150 | crate::events::warn( |
| 1151 | } |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | /// Which fx provider is active (`provider: gateway|codex|grok` in settings). |
| 1156 | pub fn fx_active_provider() -> |
| 1157 | let path = |
| 1158 | let text = |
| 1159 | let v: Value |
| 1160 | v.get("provider |
| 1161 | .and_then(|x| |
| 1162 | .map(|s| |
| 1163 | } |
| 1164 | |
| 1165 | pub fn fx_save_provider(provider |
| 1166 | let Ok( |
| 1167 | let mut v |
| 1168 | .ok() |
| 1169 | .and_then(|t| |
| 1170 | .unwrap_or_else(|| json! |
| 1171 | if !v.is_object |
| 1172 | v = json! |
| 1173 | } |
| 1174 | if let Some |
| 1175 | obj.insert("provider |
| 1176 | } |
| 1177 | if let Ok |
| 1178 | if let Err |
| 1179 | crate::events::warn( |
| 1180 | } |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | #[cfg(test)] |
| 1185 | mod tests { |
| 1186 | use super::*; |
| 1187 | |
| 1188 | #[test] |
| 1189 | fn fx_session_round_trips() { |
| 1190 | let s = |
| 1191 | access_token: "a". |
| 1192 | refresh_token: "r". |
| 1193 | expires_at_ms: 1234, |
| 1194 | account_id: "acct_123". |
| 1195 | }; |
| 1196 | let text = |
| 1197 | let back = |
| 1198 | assert_eq!(back. |
| 1199 | assert_eq!(back. |
| 1200 | assert_eq!(back. |
| 1201 | } |
| 1202 | |
| 1203 | #[test] |
| 1204 | fn callback_parses_code_and_validates_state() { |
| 1205 | let target = |
| 1206 | assert_eq!( |
| 1207 | parse_callback_target(target, " |
| 1208 | "abc123" |
| 1209 | ); |
| 1210 | assert!(parse_callback_target( |
| 1211 | } |
| 1212 | |
| 1213 | #[test] |
| 1214 | fn pkce_challenge_is_stable() { |
| 1215 | // RFC 7636 example vector. |
| 1216 | let c = |
| 1217 | assert_eq!(c, |
| 1218 | } |
| 1219 | |
| 1220 | #[test] |
| 1221 | fn base64url_round_trips() { |
| 1222 | for bytes in [ |
| 1223 | let enc = |
| 1224 | assert!(!enc |
| 1225 | assert_eq!(base64_url_decode( |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | #[test] |
| 1230 | fn base64url_tolerates_padding_and_rejects_garbage() { |
| 1231 | // Padded JWT-style input decodes like its unpadded form. |
| 1232 | assert_eq!(base64_url_decode( |
| 1233 | assert_eq!(base64_url_decode( |
| 1234 | // URL-safe alphabet: '-' and '_' must decode. |
| 1235 | let enc = |
| 1236 | assert_eq!(base64_url_decode( |
| 1237 | assert!(base64_url_decode( |
| 1238 | assert!(base64_url_decode( |
| 1239 | } |
| 1240 | } |