Skip to main content

cpa_exec/
codex_siwc.rs

1//! Codex Sign in with ChatGPT (SIWC): the authorization URL, the code exchange and the
2//! bound credential file (Go internal/auth/codex/siwc_auth.go, openai.go
3//! `CodexSIWCTokenData` and sdk/cliproxy/auth/codex_siwc_bind.go). SIWC is a second
4//! token partition (`siwc`) of an existing Codex OAuth credential. Refresh and request
5//! use (`use_siwc`) belong to the Codex executor.
6
7use chrono::{Local, TimeDelta};
8use cpa_core::config::Config;
9use cpa_core::exec::{ExecError, FailureScope};
10use cpa_core::gostr::GoStr;
11use serde::Deserialize;
12use serde_json::{Map, Value};
13use url::Url;
14
15use crate::codex_oauth::CodexOAuth;
16
17pub const DYNAMIC_CLIENT_ID: &str = "dynamic_agent_client";
18pub const DEFAULT_IDENTIFIER: &str = "CLIProxyAPI";
19pub const AUTHORIZE_URL: &str = "https://auth.openai.com/api/accounts/authorize";
20pub const TOKEN_URL: &str = "https://auth.openai.com/api/accounts/oauth/token";
21pub const RESOURCE: &str = "https://api.openai.com/v1";
22/// The fixed loopback redirect. Nothing listens there for a management binding: the
23/// browser's final URL is pasted into the v8 callback.
24pub const REDIRECT_URI: &str = "http://127.0.0.1:1455/auth/callback";
25pub const DIRECT_TOKEN_SCOPE: &str = "chatgpt.tokens.use.direct";
26pub const SCOPE: &str = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
27const EXPIRY_MARGIN: TimeDelta = TimeDelta::minutes(3);
28
29/// `oauth.providers.codex.signin-with-chatgpt-identifier`, trimmed, else `CLIProxyAPI`
30/// (Go `EffectiveSignInWithChatGPTIdentifier`).
31pub fn identifier(cfg: &Config) -> String {
32    ["oauth", "providers", "codex", "signin-with-chatgpt-identifier"]
33        .iter()
34        .try_fold(&cfg.document, |node, key| node.get(*key))
35        // A Go string field: yaml.v3 takes a number or bool as its text.
36        .map(cpa_core::config::go_string)
37        .map(|v| v.trim().to_owned())
38        .filter(|v| !v.is_empty())
39        .unwrap_or_else(|| DEFAULT_IDENTIFIER.to_owned())
40}
41
42/// Go `codexUseSIWC`: the `use_siwc` attribute (`strconv.ParseBool`), else the metadata
43/// bool or string.
44pub fn enabled(credential: &cpa_core::credential::Credential) -> bool {
45    let attribute = credential
46        .attributes
47        .get("use_siwc")
48        .and_then(|raw| parse_bool(raw.trim()))
49        .unwrap_or(false);
50    attribute
51        || match credential.metadata.get("use_siwc") {
52            Some(Value::Bool(b)) => *b,
53            Some(Value::String(s)) => parse_bool(s.trim()).unwrap_or(false),
54            _ => false,
55        }
56}
57
58/// Go `codexSIWCAccessToken`: `siwc.access_token`, else `siwc.access`, trimmed.
59pub fn access_token(credential: &cpa_core::credential::Credential) -> &str {
60    let Some(Value::Object(siwc)) = credential.metadata.get("siwc") else {
61        return "";
62    };
63    ["access_token", "access"]
64        .iter()
65        .filter_map(|k| siwc.get(*k).and_then(Value::as_str).map(str::trim))
66        .find(|t| !t.is_empty())
67        .unwrap_or_default()
68}
69
70/// Go `ensureCodexSIWCCredentials`: an SIWC credential without its token fails before
71/// any request is built.
72pub fn require_token(credential: &cpa_core::credential::Credential) -> Result<(), ExecError> {
73    if enabled(credential) && access_token(credential).is_empty() {
74        return Err(siwc_error(
75            401,
76            "codex executor: use_siwc is enabled but siwc access_token is missing",
77        ));
78    }
79    Ok(())
80}
81
82fn partition(credential: &cpa_core::credential::Credential) -> Option<&Map<String, Value>> {
83    match credential.metadata.get("siwc") {
84        Some(Value::Object(siwc)) if !siwc.is_empty() => Some(siwc),
85        _ => None,
86    }
87}
88
89fn text<'a>(siwc: &'a Map<String, Value>, key: &str) -> &'a str {
90    siwc.get(key).and_then(Value::as_str).map(str::trim).unwrap_or_default()
91}
92
93type Time = chrono::DateTime<chrono::Utc>;
94
95/// A Go `time.Time` instant as Unix nanoseconds. chrono cannot hold every instant Go
96/// reads here (a millisecond Unix value up to `i64::MAX` is some 292 million years out),
97/// and a range failure must not read as Go's zero time.
98type GoTime = i128;
99const NANOS: i128 = 1_000_000_000;
100/// Go's zero time, 0001-01-01T00:00:00Z: `IsZero` treats it as unset.
101const ZERO: GoTime = -62_135_596_800 * NANOS;
102
103fn go_now(now: Time) -> GoTime {
104    i128::from(now.timestamp()) * NANOS + i128::from(now.timestamp_subsec_nanos())
105}
106
107/// Go's `int64(f)` for a JSON number (decoded as float64). Go leaves an out-of-range
108/// result to the platform: amd64 gives `math.MinInt64`, arm64 saturates as Rust does.
109fn go_float_to_int(f: f64) -> i64 {
110    if cfg!(target_arch = "x86_64") && !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&f) {
111        return i64::MIN;
112    }
113    f as i64
114}
115
116/// Go `normaliseUnix`: a non-positive value is the zero time; above 1e12, milliseconds.
117fn go_unix(raw: i64) -> GoTime {
118    match raw {
119        ..=0 => ZERO,
120        1_000_000_000_001.. => i128::from(raw) * 1_000_000,
121        _ => i128::from(raw) * NANOS,
122    }
123}
124
125/// Go `time.Parse` for the layouts `parseTimeValue` tries: `2006-01-02T15:04:05Z07:00`
126/// (RFC3339; RFC3339Nano accepts the same strings) with `sep` `T` and `zone`, and
127/// `2006-01-02 15:04:05` / `2006-01-02 15:04` with `sep` space. Go's grammar, not
128/// RFC 3339's: a one- or two-digit hour, a `.` or `,` fraction after the seconds even
129/// where the layout has none, no leap second, only an upper-case `Z`, and a space in the
130/// layout matching any run of spaces.
131fn go_parse(s: &str, sep: u8, seconds: bool, zone: bool) -> Option<GoTime> {
132    // Go `getnum`: one or two digits, two when `fixed`.
133    fn num(v: &[u8], fixed: bool) -> Option<(i64, &[u8])> {
134        let digit = |i: usize| v.get(i).filter(|b| b.is_ascii_digit()).map(|b| i64::from(b - b'0'));
135        let first = digit(0)?;
136        match digit(1) {
137            Some(second) => Some((first * 10 + second, &v[2..])),
138            None if fixed => None,
139            None => Some((first, &v[1..])),
140        }
141    }
142    // Go `skip` for a one-byte layout literal.
143    fn lit(v: &[u8], b: u8) -> Option<&[u8]> {
144        if b == b' ' {
145            if v.first().is_some_and(|c| *c != b' ') {
146                return None;
147            }
148            return Some(&v[v.iter().take_while(|c| **c == b' ').count()..]);
149        }
150        (v.first() == Some(&b)).then(|| &v[1..])
151    }
152    let v = s.as_bytes();
153    // stdLongYear: four bytes through `atoi`, so four digits.
154    if v.len() < 4 || !v[..4].iter().all(u8::is_ascii_digit) {
155        return None;
156    }
157    let year: i32 = s[..4].parse().ok()?;
158    let (month, v) = num(lit(&v[4..], b'-')?, true)?;
159    let (day, v) = num(lit(v, b'-')?, true)?;
160    let (hour, v) = num(lit(v, sep)?, false)?;
161    let (min, mut v) = num(lit(v, b':')?, true)?;
162    if !(1..=12).contains(&month) || hour >= 24 || min >= 60 {
163        return None;
164    }
165    let (mut sec, mut nsec) = (0, 0);
166    if seconds {
167        (sec, v) = num(lit(v, b':')?, true)?;
168        if sec >= 60 {
169            return None;
170        }
171        // Go `parseNanoseconds`: at most nine digits count; the rest are read and dropped.
172        if v.len() >= 2 && matches!(v[0], b'.' | b',') && v[1].is_ascii_digit() {
173            let n = 1 + v[1..].iter().take_while(|b| b.is_ascii_digit()).count();
174            let digits = &v[1..n.min(10)];
175            nsec =
176                digits.iter().fold(0i128, |n, d| n * 10 + i128::from(d - b'0')) * 10i128.pow(9 - digits.len() as u32);
177            v = &v[n..];
178        }
179    }
180    let mut offset = 0;
181    if zone {
182        if v.first() == Some(&b'Z') {
183            v = &v[1..];
184        } else {
185            // stdISO8601ColonTZ: `±hh:mm`; Go allows up to 24 hours and 60 minutes.
186            if v.len() < 6 || v[3] != b':' {
187                return None;
188            }
189            let (hr, _) = num(&v[1..3], true)?;
190            let (mm, _) = num(&v[4..6], true)?;
191            if hr > 24 || mm > 60 {
192                return None;
193            }
194            offset = match v[0] {
195                b'+' => (hr * 60 + mm) * 60,
196                b'-' => -(hr * 60 + mm) * 60,
197                _ => return None,
198            };
199            v = &v[6..];
200        }
201    }
202    if !v.is_empty() {
203        return None;
204    }
205    let midnight = chrono::NaiveDate::from_ymd_opt(year, month as u32, day as u32)?
206        .and_hms_opt(0, 0, 0)?
207        .and_utc()
208        .timestamp();
209    Some(i128::from(midnight + hour * 3600 + min * 60 + sec - offset) * NANOS + nsec)
210}
211
212/// Go `parseTimeValue` on a decoded JSON value; `None` when it does not parse. The zero
213/// time is a value: it still ends a key search.
214fn go_time(value: &Value) -> Option<GoTime> {
215    match value {
216        Value::String(s) => {
217            let s = s.trim();
218            if s.is_empty() {
219                return None;
220            }
221            go_parse(s, b'T', true, true)
222                .or_else(|| go_parse(s, b' ', true, false))
223                .or_else(|| go_parse(s, b' ', false, false))
224                .or_else(|| s.parse().ok().map(go_unix))
225        }
226        Value::Number(n) => Some(go_unix(go_float_to_int(n.as_f64()?))),
227        _ => None,
228    }
229}
230
231/// Go `lookupMetadataTime`: the first key whose value parses, zero time included.
232fn lookup_time(map: &Map<String, Value>, keys: &[&str]) -> Option<GoTime> {
233    keys.iter().find_map(|k| map.get(*k).and_then(go_time))
234}
235
236/// Go `parseIntAny` for `expires_in`: whole seconds from a number or a decimal string.
237fn go_int(value: &Value) -> Option<i64> {
238    match value {
239        Value::Number(n) => Some(go_float_to_int(n.as_f64()?)),
240        Value::String(s) => s.trim().parse().ok(),
241        _ => None,
242    }
243}
244
245/// Go `expirationFromMap`: the expiry keys, then `expires_in` after its issue time, then
246/// a nested `token` or `Token` map.
247fn expiration_from_map(map: &Map<String, Value>) -> Option<GoTime> {
248    if let Some(t) = lookup_time(
249        map,
250        &["expired", "expire", "expires_at", "expiresAt", "expiry", "expires"],
251    ) {
252        return Some(t);
253    }
254    let seconds = ["expires_in", "expiresIn"]
255        .iter()
256        .find_map(|k| map.get(*k).and_then(go_int).filter(|s| *s > 0));
257    if let Some(seconds) = seconds {
258        let issued = ["timestamp", "issued_at", "issuedAt"]
259            .iter()
260            .find_map(|k| map.get(*k).and_then(go_time).filter(|t| *t != ZERO));
261        if let Some(issued) = issued {
262            // `time.Duration(expiresIn) * time.Second` wraps like Go's int64 product.
263            return Some(issued + i128::from(seconds.wrapping_mul(1_000_000_000)));
264        }
265    }
266    ["token", "Token"].iter().find_map(|k| match map.get(*k) {
267        Some(Value::Object(nested)) => expiration_from_map(nested),
268        _ => None,
269    })
270}
271
272/// Go `parseJWTExp`'s payload decoding: the middle of exactly three `.`-separated
273/// segments, through `base64.URLEncoding` with the padding its length implies and then
274/// `RawURLEncoding`. Both skip CR and LF and accept non-zero trailing bits.
275fn jwt_payload(token: &str) -> Option<Vec<u8>> {
276    use base64::Engine;
277    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
278    let parts: Vec<&str> = token.trim().split('.').collect();
279    let [_, segment, _] = parts[..] else {
280        return None;
281    };
282    let engine = |mode| {
283        let config = GeneralPurposeConfig::new()
284            .with_decode_padding_mode(mode)
285            .with_decode_allow_trailing_bits(true);
286        GeneralPurpose::new(&base64::alphabet::URL_SAFE, config)
287    };
288    let strip = |s: &str| s.bytes().filter(|b| !matches!(b, b'\r' | b'\n')).collect::<Vec<u8>>();
289    // The padding comes from the length before CR and LF are skipped, as in Go.
290    let pad = ["", "", "==", "="][segment.len() % 4];
291    engine(DecodePaddingMode::RequireCanonical)
292        .decode(strip(&format!("{segment}{pad}")))
293        .or_else(|_| engine(DecodePaddingMode::RequireNone).decode(strip(segment)))
294        .ok()
295}
296
297/// Go `json.Unmarshal` of a JWT payload into `struct{ Exp any }`: every member whose
298/// name folds to `exp` (ASCII case; nothing else folds into those letters) replaces the
299/// field in input order, null clearing it; other members are skipped unconverted. `None`
300/// when the payload is not one JSON object or null, or a value fails to decode.
301// ponytail: an `exp` value holding invalid UTF-8 or a lone surrogate fails here, where Go
302// substitutes U+FFFD; such a value is never a number, so only a later `exp` in the same
303// payload could read differently.
304fn jwt_exp_claim(payload: &[u8]) -> Option<Value> {
305    use serde::de::{DeserializeSeed, Deserializer, IgnoredAny, MapAccess, Visitor};
306    struct IsExp(bool);
307    impl<'de> serde::Deserialize<'de> for IsExp {
308        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
309            struct Key;
310            impl Visitor<'_> for Key {
311                type Value = IsExp;
312                fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
313                    f.write_str("a member name")
314                }
315                fn visit_bytes<E>(self, v: &[u8]) -> Result<IsExp, E> {
316                    Ok(IsExp(v.eq_ignore_ascii_case(b"exp")))
317                }
318                fn visit_str<E>(self, v: &str) -> Result<IsExp, E> {
319                    Ok(IsExp(v.eq_ignore_ascii_case("exp")))
320                }
321            }
322            // Raw bytes: a name that is not UTF-8 is skipped, not an error.
323            d.deserialize_bytes(Key)
324        }
325    }
326    struct Claims;
327    impl<'de> DeserializeSeed<'de> for Claims {
328        type Value = Value;
329        fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
330            d.deserialize_any(self)
331        }
332    }
333    impl<'de> Visitor<'de> for Claims {
334        type Value = Value;
335        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
336            f.write_str("an object or null")
337        }
338        fn visit_unit<E>(self) -> Result<Value, E> {
339            Ok(Value::Null)
340        }
341        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
342            let mut exp = Value::Null;
343            while let Some(IsExp(is_exp)) = map.next_key()? {
344                if is_exp {
345                    exp = map.next_value()?;
346                } else {
347                    map.next_value::<IgnoredAny>()?;
348                }
349            }
350            Ok(exp)
351        }
352    }
353    let mut de = serde_json::Deserializer::from_slice(payload);
354    let exp = Claims.deserialize(&mut de).ok()?;
355    de.end().ok()?;
356    Some(exp)
357}
358
359/// Go `parseJWTExp`: a positive number or decimal string, through `normaliseUnix`.
360fn jwt_exp(token: &str) -> Option<GoTime> {
361    match jwt_exp_claim(&jwt_payload(token)?)? {
362        Value::Number(n) => n.as_f64().filter(|f| *f > 0.0).map(|f| go_unix(go_float_to_int(f))),
363        Value::String(s) => s.trim().parse::<i64>().ok().filter(|s| *s > 0).map(go_unix),
364        _ => None,
365    }
366}
367
368/// Go `SIWCExpirationTime`: the partition's expiration, else its access token's JWT
369/// `exp`; a zero time is no expiration.
370fn expiry(siwc: &Map<String, Value>) -> Option<GoTime> {
371    expiration_from_map(siwc)
372        .filter(|t| *t != ZERO)
373        .or_else(|| jwt_exp(text(siwc, "access_token")).filter(|t| *t != ZERO))
374}
375
376/// Go `CodexSIWCNeedsRefresh`: `None` when the partition cannot refresh (no refresh
377/// token or client ID), else whether it is due at `now`: no access token, five minutes
378/// before its expiry, five minutes after its last refresh, or now when neither is known.
379pub fn refresh_due(credential: &cpa_core::credential::Credential, now: Time) -> Option<bool> {
380    let siwc = partition(credential)?;
381    if text(siwc, "refresh_token").is_empty() || text(siwc, "client_id").is_empty() {
382        return None;
383    }
384    if text(siwc, "access_token").is_empty() {
385        return Some(true);
386    }
387    let (now, lead) = (go_now(now), 5 * 60 * NANOS);
388    if let Some(expiry) = expiry(siwc) {
389        return Some(expiry - lead <= now);
390    }
391    let last = lookup_time(siwc, &["last_refresh", "lastRefresh"]).filter(|t| *t != ZERO);
392    Some(last.is_none_or(|last| last + lead <= now))
393}
394
395/// The partition's request token is present and not expired at `now`.
396pub(crate) fn access_usable(credential: &cpa_core::credential::Credential, now: Time) -> bool {
397    !access_token(credential).is_empty()
398        && partition(credential)
399            .and_then(expiry)
400            .is_none_or(|exp| exp > go_now(now))
401}
402
403/// The `siwc` patch of a refresh: the stored partition with the refreshed fields over it.
404pub(crate) fn refresh_patch(
405    credential: &cpa_core::credential::Credential,
406    tokens: &Tokens,
407) -> cpa_core::credential::MetadataPatch {
408    let mut merged = partition(credential).cloned().unwrap_or_default();
409    merged.extend(tokens.to_map());
410    let mut patch = cpa_core::credential::MetadataPatch::default();
411    patch.set.insert("siwc".into(), Value::Object(merged));
412    patch
413}
414
415/// The partition's refresh grant inputs: refresh token, client ID and device ID.
416pub(crate) fn refresh_inputs(credential: &cpa_core::credential::Credential) -> (&str, &str, &str) {
417    partition(credential).map_or(("", "", ""), |siwc| {
418        (
419            text(siwc, "refresh_token"),
420            text(siwc, "client_id"),
421            text(siwc, "device_id"),
422        )
423    })
424}
425
426/// Go `codexSIWCUserAgent`: `<identifier> (<GOOS>; <GOARCH>)`.
427pub fn user_agent(cfg: &Config) -> String {
428    format!(
429        "{} ({}; {})",
430        identifier(cfg),
431        crate::kimi_http::go_os(),
432        crate::kimi_http::go_arch()
433    )
434}
435
436/// Go `strconv.ParseBool`.
437fn parse_bool(s: &str) -> Option<bool> {
438    match s {
439        "1" | "t" | "T" | "true" | "TRUE" | "True" => Some(true),
440        "0" | "f" | "F" | "false" | "FALSE" | "False" => Some(false),
441        _ => None,
442    }
443}
444
445/// Go `IsValidUUID`: a canonical 36-character UUID, any case, surrounding space ignored.
446pub fn is_valid_uuid(raw: &str) -> bool {
447    let raw = raw.trim().as_bytes();
448    raw.len() == 36
449        && raw.iter().enumerate().all(|(i, b)| match i {
450            8 | 13 | 18 | 23 => *b == b'-',
451            _ => b.is_ascii_hexdigit(),
452        })
453}
454
455/// Go `GenerateRandomBase64URL`: 32 random bytes, unpadded base64url.
456pub fn random_base64url() -> Result<String, ExecError> {
457    use base64::Engine;
458    let mut bytes = [0u8; 32];
459    getrandom::fill(&mut bytes).map_err(|_| siwc_error(500, "failed to generate random bytes"))?;
460    Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
461}
462
463/// Go `GenerateSIWCAuthURL`; `url.Values.Encode` sorts the parameters.
464pub fn authorize_url(
465    state: &str,
466    nonce: &str,
467    device_id: &str,
468    redirect: &str,
469    challenge: &str,
470    identifier: &str,
471) -> Result<String, ExecError> {
472    let device_id = device_id.trim();
473    if !is_valid_uuid(device_id) {
474        return Err(siwc_error(400, "Sign in with ChatGPT requires a valid device UUID"));
475    }
476    if state.trim().is_empty() {
477        return Err(siwc_error(400, "state is required"));
478    }
479    if nonce.trim().is_empty() {
480        return Err(siwc_error(400, "nonce is required"));
481    }
482    let redirect = match redirect.trim() {
483        "" => REDIRECT_URI,
484        r => r,
485    };
486    let host = format!("urn:uuid:{}", device_id.go_lower());
487    let mut url = Url::parse(AUTHORIZE_URL).expect("constant URL");
488    url.query_pairs_mut().extend_pairs([
489        ("agent_name_hint", identifier),
490        ("client_id", DYNAMIC_CLIENT_ID),
491        ("code_challenge", challenge),
492        ("code_challenge_method", "S256"),
493        ("ext_agent_host_id", &host),
494        ("nonce", nonce.trim()),
495        ("redirect_uri", redirect),
496        ("resource", RESOURCE),
497        ("response_type", "code"),
498        ("scope", SCOPE),
499        ("state", state.trim()),
500    ]);
501    Ok(url.into())
502}
503
504/// Go `CodexSIWCTokenData`.
505#[derive(Debug, Clone, Default, PartialEq, Eq)]
506pub struct Tokens {
507    pub access_token: String,
508    pub refresh_token: String,
509    pub id_token: String,
510    pub client_id: String,
511    pub scope: String,
512    pub scopes: Vec<String>,
513    pub expired: String,
514    pub last_refresh: String,
515    pub device_id: String,
516}
517
518impl Tokens {
519    /// Go `ToMap`: the `siwc` partition as persisted; optional fields only when set.
520    pub fn to_map(&self) -> Map<String, Value> {
521        let mut out = Map::new();
522        let mut set = |k: &str, v: &str| {
523            out.insert(k.into(), Value::String(v.to_owned()));
524        };
525        set("access_token", &self.access_token);
526        set("refresh_token", &self.refresh_token);
527        set("client_id", &self.client_id);
528        set("expired", &self.expired);
529        set("last_refresh", &self.last_refresh);
530        if !self.id_token.is_empty() {
531            set("id_token", &self.id_token);
532        }
533        if !self.scope.is_empty() {
534            set("scope", &self.scope);
535        }
536        if !self.device_id.is_empty() {
537            set("device_id", &self.device_id);
538        }
539        if !self.scopes.is_empty() {
540            out.insert("scopes".into(), self.scopes.clone().into());
541        }
542        out
543    }
544}
545
546#[derive(Deserialize)]
547struct TokenResponse {
548    #[serde(default)]
549    access_token: String,
550    #[serde(default)]
551    refresh_token: String,
552    #[serde(default)]
553    id_token: String,
554    #[serde(default)]
555    scope: String,
556    #[serde(default)]
557    expires_in: i64,
558}
559
560fn siwc_error(status: u16, message: &str) -> ExecError {
561    ExecError::local(status, FailureScope::Credential, message)
562}
563
564impl CodexOAuth {
565    /// Go `requestSIWCToken`. Upstream bodies are never echoed: the management session
566    /// reports a fixed message.
567    pub(crate) async fn siwc_token_request(
568        &self,
569        form: &[(&str, &str)],
570        client_id: &str,
571        device_id: &str,
572        require_id_token: bool,
573    ) -> Result<Tokens, ExecError> {
574        // url.Values.Encode sorts keys; callers pass them sorted.
575        let body = url::form_urlencoded::Serializer::new(String::new())
576            .extend_pairs(form)
577            .finish();
578        let (status, body) = self
579            .post(
580                self.siwc_token_url(),
581                "application/x-www-form-urlencoded",
582                body.into_bytes(),
583            )
584            .await?;
585        if status != 200 && !require_id_token {
586            // A refresh keeps the OAuth error code (Go echoes the body), so
587            // `refresh_token_reused` stops the retries; bodies may echo request material.
588            return Err(crate::codex_oauth::refresh_error(
589                status,
590                &format!(
591                    "OpenAI OAuth token request failed ({status}): {}",
592                    crate::codex_oauth::oauth_code(&body)
593                ),
594            ));
595        }
596        if status != 200 {
597            return Err(siwc_error(
598                status,
599                &format!("OpenAI OAuth token request failed ({status})"),
600            ));
601        }
602        let parsed: TokenResponse =
603            serde_json::from_slice(&body).map_err(|_| siwc_error(502, "failed to parse SIWC token response"))?;
604        let invalid = |field: &str| siwc_error(502, &format!("OpenAI OAuth token response has invalid {field}"));
605        if parsed.access_token.trim().is_empty() {
606            return Err(invalid("access_token"));
607        }
608        if parsed.refresh_token.trim().is_empty() {
609            return Err(invalid("refresh_token"));
610        }
611        if require_id_token && parsed.id_token.trim().is_empty() {
612            return Err(siwc_error(
613                502,
614                "OpenAI OAuth token response did not contain an ID token",
615            ));
616        }
617        if parsed.scope.trim().is_empty() {
618            return Err(invalid("scope"));
619        }
620        if parsed.expires_in <= 0 {
621            return Err(invalid("expires_in"));
622        }
623        let scopes: Vec<String> = parsed.scope.split_whitespace().map(str::to_owned).collect();
624        if !scopes.iter().any(|s| s == DIRECT_TOKEN_SCOPE) {
625            return Err(siwc_error(
626                502,
627                &format!("OpenAI OAuth grant did not include {DIRECT_TOKEN_SCOPE}"),
628            ));
629        }
630        let now = Local::now();
631        let lifetime = TimeDelta::try_seconds(parsed.expires_in).unwrap_or(TimeDelta::MAX);
632        let ttl = match lifetime - EXPIRY_MARGIN {
633            ttl if ttl > TimeDelta::zero() => ttl,
634            _ => lifetime,
635        };
636        let rfc3339 = |t: chrono::DateTime<Local>| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
637        Ok(Tokens {
638            access_token: parsed.access_token,
639            refresh_token: parsed.refresh_token,
640            id_token: parsed.id_token,
641            client_id: client_id.trim().to_owned(),
642            scope: parsed.scope.trim().to_owned(),
643            scopes,
644            expired: rfc3339(now.checked_add_signed(ttl).unwrap_or(now)),
645            last_refresh: rfc3339(now),
646            device_id: device_id.trim().to_owned(),
647        })
648    }
649
650    /// Go `ExchangeSIWCCodeForTokens`: the issued client ID from the callback, never the
651    /// dynamic one in the authorization URL.
652    pub async fn exchange_siwc(
653        &self,
654        code: &str,
655        client_id: &str,
656        redirect: &str,
657        device_id: &str,
658        verifier: &str,
659    ) -> Result<Tokens, ExecError> {
660        let client_id = client_id.trim();
661        if client_id.is_empty() {
662            return Err(siwc_error(
663                400,
664                "OpenAI OAuth registration callback did not contain an issued client ID",
665            ));
666        }
667        let code = code.trim();
668        if code.is_empty() {
669            return Err(siwc_error(400, "authorization code is required"));
670        }
671        let redirect = match redirect.trim() {
672            "" => REDIRECT_URI,
673            r => r,
674        };
675        self.siwc_token_request(
676            &[
677                ("client_id", client_id),
678                ("code", code),
679                ("code_verifier", verifier),
680                ("grant_type", "authorization_code"),
681                ("redirect_uri", redirect),
682                ("resource", RESOURCE),
683            ],
684            client_id,
685            device_id,
686            true,
687        )
688        .await
689    }
690}
691
692/// Go `BindCodexSIWC`'s file: every top-level member of `disk` kept as written (large
693/// numbers included), `siwc` replaced by `tokens` and `use_siwc` set, encoded like Go's
694/// `json.Marshal` of the merged map (sorted keys, compact, HTML-escaped, no newline).
695/// `None` when `disk` is not a JSON object.
696pub fn bind_file(disk: &[u8], tokens: &Tokens) -> Option<Vec<u8>> {
697    let mut members: std::collections::BTreeMap<String, Box<serde_json::value::RawValue>> =
698        serde_json::from_slice(disk).ok()?;
699    let siwc = crate::codex_oauth::encode_go_json(&Value::Object(tokens.to_map()));
700    members.insert(
701        "siwc".into(),
702        serde_json::value::RawValue::from_string(siwc.trim_end().to_owned()).ok()?,
703    );
704    members.insert(
705        "use_siwc".into(),
706        serde_json::value::RawValue::from_string("true".into()).ok()?,
707    );
708    let mut out = String::with_capacity(disk.len() + 512);
709    out.push('{');
710    for (i, (key, value)) in members.iter().enumerate() {
711        if i > 0 {
712            out.push(',');
713        }
714        out.push_str(&crate::codex_json::go_quote(key, true));
715        out.push(':');
716        compact_html(value.get(), &mut out);
717    }
718    out.push('}');
719    Some(out.into_bytes())
720}
721
722/// Go `compact(dst, src, escapeHTML=true)` over valid JSON: whitespace outside strings
723/// dropped, `<`, `>`, `&`, U+2028 and U+2029 escaped, everything else verbatim.
724fn compact_html(raw: &str, out: &mut String) {
725    let (mut in_string, mut escaped) = (false, false);
726    for c in raw.chars() {
727        if in_string {
728            match c {
729                '<' => out.push_str("\\u003c"),
730                '>' => out.push_str("\\u003e"),
731                '&' => out.push_str("\\u0026"),
732                '\u{2028}' => out.push_str("\\u2028"),
733                '\u{2029}' => out.push_str("\\u2029"),
734                _ => out.push(c),
735            }
736            match (escaped, c) {
737                (true, _) => escaped = false,
738                (false, '\\') => escaped = true,
739                (false, '"') => in_string = false,
740                _ => {}
741            }
742        } else if !matches!(c, ' ' | '\t' | '\n' | '\r') {
743            in_string = c == '"';
744            out.push(c);
745        }
746    }
747}
748
749#[cfg(test)]
750#[path = "codex_siwc_tests.rs"]
751mod tests;