Skip to main content

cpa_exec/
meta_auth.rs

1//! Meta Muse RFC 8628 device login, API-key minting and credential files
2//! (internal/auth/meta/meta.go, sdk/auth/meta.go, internal/cmd/meta_login.go).
3//!
4//! Meta has no refresh-token grant. The device flow yields a DCA token (`dca:...`), which
5//! is exchanged for an LLM API key at the mint endpoint; refresh re-mints from the saved
6//! DCA token. The SDK refresh lead is nil: refresh happens on demand only.
7
8use std::collections::{BTreeMap, HashMap};
9use std::path::{Path, PathBuf};
10use std::sync::{LazyLock, Mutex};
11use std::time::Duration;
12
13use chrono::{DateTime, Utc};
14use cpa_common::json::{self as gj, GoValue};
15use cpa_core::exec::{ExecError, FailureScope};
16use futures_util::FutureExt;
17use futures_util::future::{BoxFuture, Shared};
18use serde_json::Value;
19use sha2::{Digest, Sha256};
20
21use crate::kimi_auth::{form, open_browser, write_private};
22use crate::kimi_http::rfc3339_utc;
23use crate::meta_wire::{Slot, check_valid, unmarshal};
24use crate::proxy::{GoHeaders, MAX_ERROR_BODY, read_all, send};
25
26pub const DEFAULT_API_BASE_URL: &str = "https://api.meta.ai/v1";
27pub const AUTH_HOST: &str = "https://auth.meta.com";
28pub const CLIENT_ID: &str = "1031625952748946";
29pub const DEFAULT_MINT_URL: &str = "https://api.meta.ai/muse-code/key";
30const DEVICE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
31const AUTH_USER_AGENT: &str = "muse-code/1.0.2";
32/// Poll interval in server units when the device response has none.
33const DEFAULT_POLL_INTERVAL: u64 = 5;
34/// Upper bound on waiting for the user (MaxPollDuration), in seconds.
35const MAX_POLL_SECONDS: u64 = 15 * 60;
36/// `httpClientTimeout` for every credential-acquisition call.
37const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
38
39/// Device authorization response.
40#[derive(Debug, Clone, Default, PartialEq, Eq)]
41pub struct DeviceCode {
42    pub device_code: String,
43    pub user_code: String,
44    pub verification_uri: String,
45    pub verification_uri_complete: String,
46    pub expires_in: i64,
47    pub interval: i64,
48}
49
50impl DeviceCode {
51    #[cfg(test)]
52    pub(crate) fn decode_for_test(raw: &[u8]) -> Result<Self, String> {
53        Self::decode(raw)
54    }
55
56    /// `json.Unmarshal` into DeviceCodeResponse (`TokenEndpoint` is `json:"-"`).
57    fn decode(raw: &[u8]) -> Result<Self, String> {
58        let mut c = Self::default();
59        unmarshal(
60            raw,
61            "meta",
62            "DeviceCodeResponse",
63            &mut [
64                ("device_code", Slot::Str(&mut c.device_code)),
65                ("user_code", Slot::Str(&mut c.user_code)),
66                ("verification_uri", Slot::Str(&mut c.verification_uri)),
67                ("verification_uri_complete", Slot::Str(&mut c.verification_uri_complete)),
68                ("expires_in", Slot::Int(&mut c.expires_in, "int")),
69                ("interval", Slot::Int(&mut c.interval, "int")),
70            ],
71        )?;
72        Ok(c)
73    }
74}
75
76/// The DCA token from the token endpoint. `expires_at` is Unix seconds, 0 when unknown.
77#[derive(Debug, Clone, Default, PartialEq, Eq)]
78pub struct TokenData {
79    pub access_token: String,
80    pub token_type: String,
81    pub expires_in: i64,
82    pub expires_at: i64,
83    pub error: String,
84    pub error_description: String,
85}
86
87impl TokenData {
88    #[cfg(test)]
89    pub(crate) fn decode_for_test(raw: &[u8]) -> (Self, Result<(), String>) {
90        Self::decode(raw)
91    }
92
93    /// `json.Unmarshal` into TokenData. Fields decoded before a type error are kept, as
94    /// Go does; the poll loop relies on that for error answers.
95    fn decode(raw: &[u8]) -> (Self, Result<(), String>) {
96        let mut t = Self::default();
97        let result = unmarshal(
98            raw,
99            "meta",
100            "TokenData",
101            &mut [
102                ("access_token", Slot::Str(&mut t.access_token)),
103                ("token_type", Slot::Str(&mut t.token_type)),
104                ("expires_in", Slot::Int(&mut t.expires_in, "int")),
105                ("expires_at", Slot::Int(&mut t.expires_at, "int64")),
106                ("error", Slot::Str(&mut t.error)),
107                ("error_description", Slot::Str(&mut t.error_description)),
108            ],
109        );
110        (t, result)
111    }
112}
113
114/// The mint endpoint's answer (MintedKeyResponse).
115#[derive(Debug, Clone, Default, PartialEq, Eq)]
116pub struct MintedKey {
117    pub api_key: String,
118    pub base_url: String,
119    pub user_email: String,
120    pub user_full_name: String,
121    pub subs_tier_name: String,
122    pub subs_tier_id: String,
123    pub is_subs_active: bool,
124    pub has_payment_method: bool,
125    pub require_payment: bool,
126    pub can_subscribe: bool,
127}
128
129impl MintedKey {
130    /// `json.Unmarshal` into MintedKeyResponse.
131    pub fn decode(raw: &[u8]) -> Result<Self, String> {
132        let mut m = Self::default();
133        unmarshal(
134            raw,
135            "meta",
136            "MintedKeyResponse",
137            &mut [
138                ("api_key", Slot::Str(&mut m.api_key)),
139                ("base_url", Slot::Str(&mut m.base_url)),
140                ("user_email", Slot::Str(&mut m.user_email)),
141                ("user_full_name", Slot::Str(&mut m.user_full_name)),
142                ("subs_tier_name", Slot::Str(&mut m.subs_tier_name)),
143                ("subs_tier_id", Slot::Str(&mut m.subs_tier_id)),
144                ("is_subs_active", Slot::Bool(&mut m.is_subs_active)),
145                ("has_payment_method", Slot::Bool(&mut m.has_payment_method)),
146                ("require_payment", Slot::Bool(&mut m.require_payment)),
147                ("can_subscribe", Slot::Bool(&mut m.can_subscribe)),
148            ],
149        )?;
150        Ok(m)
151    }
152}
153
154/// Token data, minted key and user identity from one login (MetaAuthBundle).
155#[derive(Debug, Clone, Default, PartialEq, Eq)]
156pub struct Bundle {
157    pub token: TokenData,
158    pub minted: Option<MintedKey>,
159    pub email: String,
160    pub name: String,
161}
162
163/// Why minting failed: Go's message without the mint endpoint's response body. Go appends
164/// the body, which can carry key material, and the message reaches logs and API clients;
165/// it is never kept here, so no formatting of this error can leak it.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub enum MintError {
168    /// A non-2xx answer (its HTTP status).
169    Status(u16),
170    Other(String),
171}
172
173impl MintError {
174    /// The message, safe for logs and API clients.
175    pub fn redacted(&self) -> String {
176        self.to_string()
177    }
178}
179
180impl std::fmt::Display for MintError {
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        match self {
183            Self::Status(status) => write!(f, "meta auth: mint key failed (HTTP {status})"),
184            Self::Other(message) => f.write_str(message),
185        }
186    }
187}
188
189/// The mint endpoint: `META_MINT_URL` when set, otherwise Meta's production URL.
190pub fn mint_url() -> String {
191    std::env::var("META_MINT_URL")
192        .ok()
193        .map(|v| v.trim().to_owned())
194        .filter(|v| !v.is_empty())
195        .unwrap_or_else(|| DEFAULT_MINT_URL.to_owned())
196}
197
198/// One Meta OAuth client (MetaAuth). Endpoints are fixed in production; tests point them
199/// at local mocks.
200#[derive(Clone)]
201pub struct MetaAuth {
202    client: wreq::Client,
203    device_url: String,
204    token_url: String,
205    mint_url: String,
206    /// Length of one server-side second while polling; shortened only in tests.
207    poll_unit: Duration,
208    /// Fixed clock for tests; `None` is the wall clock.
209    fixed_now: Option<DateTime<Utc>>,
210}
211
212impl MetaAuth {
213    pub fn new(client: wreq::Client) -> Self {
214        Self {
215            client,
216            device_url: format!("{AUTH_HOST}/oidc/device/authorization/"),
217            token_url: format!("{AUTH_HOST}/oidc/device/token/"),
218            mint_url: mint_url(),
219            poll_unit: Duration::from_secs(1),
220            fixed_now: None,
221        }
222    }
223
224    fn now(&self) -> DateTime<Utc> {
225        self.fixed_now.unwrap_or_else(Utc::now)
226    }
227
228    /// Points device authorization and token polling at another host (local mocks).
229    pub fn with_auth_host(mut self, host: &str) -> Self {
230        let host = host.trim_end_matches('/');
231        self.device_url = format!("{host}/oidc/device/authorization/");
232        self.token_url = format!("{host}/oidc/device/token/");
233        self
234    }
235
236    /// Overrides the mint endpoint (SetMintURL).
237    pub fn with_mint_url(mut self, url: &str) -> Self {
238        let url = url.trim();
239        if !url.is_empty() {
240            self.mint_url = url.to_owned();
241        }
242        self
243    }
244
245    #[cfg(test)]
246    pub(crate) fn with_poll_unit(mut self, unit: Duration) -> Self {
247        self.poll_unit = unit;
248        self
249    }
250
251    #[cfg(test)]
252    pub(crate) fn with_fixed_now(mut self, now: DateTime<Utc>) -> Self {
253        self.fixed_now = Some(now);
254        self
255    }
256
257    async fn post(
258        &self,
259        url: &str,
260        headers: GoHeaders,
261        body: impl Into<bytes::Bytes>,
262    ) -> Result<(u16, bytes::Bytes), String> {
263        let upstream = send(&self.client, url, headers, body, Some(HTTP_TIMEOUT))
264            .await
265            .map_err(|e| String::from_utf8_lossy(&e.body).into_owned())?;
266        let status = upstream.status;
267        let body = read_all(upstream.body, MAX_ERROR_BODY, false)
268            .await
269            .map_err(|e| String::from_utf8_lossy(&e.body).into_owned())?;
270        Ok((status, body))
271    }
272
273    fn form_headers() -> GoHeaders {
274        let mut h = GoHeaders::new();
275        h.set("Content-Type", "application/x-www-form-urlencoded");
276        h.set("Accept", "application/json");
277        h.set("User-Agent", AUTH_USER_AGENT);
278        h
279    }
280
281    /// StartDeviceFlow.
282    pub async fn start_device_flow(&self) -> Result<DeviceCode, String> {
283        let (status, body) = self
284            .post(
285                &self.device_url,
286                Self::form_headers(),
287                form(&[("client_id", CLIENT_ID)]),
288            )
289            .await
290            .map_err(|e| format!("meta device flow: request failed: {e}"))?;
291        if !(200..300).contains(&status) {
292            // Go appends the response body; it is withheld from logs and clients.
293            return Err(format!("meta device flow failed (HTTP {status})"));
294        }
295        let code = DeviceCode::decode(&body).map_err(|e| format!("meta device flow: parse response: {e}"))?;
296        if code.device_code.trim().is_empty() || code.user_code.trim().is_empty() {
297            return Err("meta device flow: response missing required device_code or user_code".into());
298        }
299        Ok(code)
300    }
301
302    /// WaitForAuthorization: polls on a ticker until approved, denied or expired, then
303    /// mints the API key. A mint failure is logged and the bundle carries only the DCA token.
304    pub async fn wait_for_authorization(&self, code: &DeviceCode) -> Result<Bundle, String> {
305        if code.device_code.is_empty() {
306            return Err("meta auth: missing device code response".into());
307        }
308        let mut interval = if code.interval > 0 {
309            code.interval as u64
310        } else {
311            DEFAULT_POLL_INTERVAL
312        };
313        let mut max_seconds = MAX_POLL_SECONDS;
314        if code.expires_in > 0 {
315            max_seconds = max_seconds.min(code.expires_in as u64);
316        }
317        let deadline = tokio::time::Instant::now() + self.poll_unit * max_seconds as u32;
318        let ticker = |seconds: u64| {
319            let period = self.poll_unit * seconds as u32;
320            let mut t = tokio::time::interval_at(tokio::time::Instant::now() + period, period);
321            // Go's ticker channel holds one pending tick; a slow poll is followed by one
322            // immediate poll, not a burst.
323            t.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
324            t
325        };
326        let mut tick = ticker(interval);
327        let timed_out = || "meta auth: authorization timed out or canceled: context deadline exceeded".to_owned();
328        loop {
329            tokio::select! {
330                _ = tokio::time::sleep_until(deadline) => return Err(timed_out()),
331                _ = tick.tick() => {}
332            }
333            let body = form(&[
334                ("grant_type", DEVICE_GRANT),
335                ("device_code", &code.device_code),
336                ("client_id", CLIENT_ID),
337            ]);
338            let polled =
339                match tokio::time::timeout_at(deadline, self.post(&self.token_url, Self::form_headers(), body)).await {
340                    Err(_) => return Err(timed_out()),
341                    Ok(polled) => polled,
342                };
343            let (status, body) = match polled {
344                Ok(answer) => answer,
345                Err(_) => {
346                    tracing::warn!("meta auth: poll request error (retrying)");
347                    continue;
348                }
349            };
350            if status == 200 {
351                let (mut token, decoded) = TokenData::decode(&body);
352                decoded.map_err(|e| format!("meta auth: parse token response: {e}"))?;
353                if token.access_token.is_empty() {
354                    return Err("meta auth: response missing access_token".into());
355                }
356                if token.expires_in > 0 {
357                    token.expires_at = self.now().timestamp() + token.expires_in;
358                }
359                let mut bundle = Bundle {
360                    token,
361                    ..Bundle::default()
362                };
363                let minted = tokio::time::timeout_at(deadline, self.mint_api_key(&bundle.token.access_token))
364                    .await
365                    .unwrap_or_else(|_| {
366                        Err(MintError::Other(
367                            "meta auth: mint request failed: context deadline exceeded".into(),
368                        ))
369                    });
370                match minted {
371                    Err(e) => tracing::warn!("meta auth: could not mint api_key from dca_token: {}", e.redacted()),
372                    Ok(minted) => {
373                        if !minted.user_email.is_empty() {
374                            bundle.email = minted.user_email.clone();
375                        }
376                        if !minted.user_full_name.is_empty() {
377                            bundle.name = minted.user_full_name.clone();
378                        }
379                        bundle.minted = Some(minted);
380                    }
381                }
382                return Ok(bundle);
383            }
384            // Go ignores decode errors here and keeps whatever fields matched.
385            let (answer, _) = TokenData::decode(&body);
386            match answer.error.as_str() {
387                "authorization_pending" => {}
388                "slow_down" => {
389                    interval += 5;
390                    tick = ticker(interval);
391                }
392                "access_denied" => return Err("meta auth: access was denied by user".into()),
393                "expired_token" => return Err("meta auth: device code has expired".into()),
394                "" => tracing::warn!("meta auth: unexpected response {status}"),
395                other => {
396                    return Err(format!(
397                        "meta auth: error from authorization server: {other}: {}",
398                        answer.error_description
399                    ));
400                }
401            }
402        }
403    }
404
405    /// MintAPIKey, single-flighted per mint endpoint and DCA token across the process
406    /// (metaRefreshGroup). Callers that go away do not cancel it.
407    pub async fn mint_api_key(&self, dca_token: &str) -> Result<MintedKey, MintError> {
408        let dca_token = dca_token.trim().to_owned();
409        if dca_token.is_empty() {
410            return Err(MintError::Other("meta auth: missing dca token".into()));
411        }
412        type Flight = Shared<BoxFuture<'static, Result<MintedKey, MintError>>>;
413        static FLIGHTS: LazyLock<Mutex<HashMap<String, Flight>>> = LazyLock::new(Mutex::default);
414        let key = format!("{}\n{dca_token}", self.mint_url);
415        let flight = {
416            let mut flights = FLIGHTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
417            if let Some(flight) = flights.get(&key) {
418                flight.clone()
419            } else {
420                let auth = self.clone();
421                let task_key = key.clone();
422                let task = tokio::spawn(async move {
423                    let result = auth.mint_once(&dca_token).await;
424                    FLIGHTS
425                        .lock()
426                        .unwrap_or_else(std::sync::PoisonError::into_inner)
427                        .remove(&task_key);
428                    result
429                });
430                let flight = async move {
431                    task.await
432                        .map_err(|_| MintError::Other("meta auth: mint request failed".into()))?
433                }
434                .boxed()
435                .shared();
436                flights.insert(key, flight.clone());
437                flight
438            }
439        };
440        flight.await
441    }
442
443    async fn mint_once(&self, dca_token: &str) -> Result<MintedKey, MintError> {
444        let mut headers = GoHeaders::new();
445        headers.set("Authorization", format!("Bearer {dca_token}"));
446        headers.set("User-Agent", AUTH_USER_AGENT);
447        headers.set("Content-Type", "application/json");
448        headers.set("Accept", "application/json");
449        let mut body = br#"{"dca_token":"#.to_vec();
450        body.extend_from_slice(&gj::quote(dca_token));
451        body.push(b'}');
452        let (status, body) = self
453            .post(&self.mint_url, headers, body)
454            .await
455            .map_err(|e| MintError::Other(format!("meta auth: mint request failed: {e}")))?;
456        if !(200..300).contains(&status) {
457            return Err(MintError::Status(status));
458        }
459        let minted =
460            MintedKey::decode(&body).map_err(|e| MintError::Other(format!("meta auth: parse mint response: {e}")))?;
461        if minted.api_key.trim().is_empty() {
462            return Err(MintError::Other("meta auth: mint response missing api_key".into()));
463        }
464        Ok(minted)
465    }
466}
467
468/// Persisted credential fields (MetaTokenStorage). `type` and `auth_kind` are forced on
469/// write and have no field.
470#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize)]
471#[serde(default)]
472pub struct TokenStorage {
473    pub access_token: String,
474    pub dca_token: String,
475    pub api_key: String,
476    pub token_type: String,
477    pub expires_in: i64,
478    pub expired: String,
479    pub dca_expired: String,
480    pub dca_expires_at: i64,
481    pub last_refresh: String,
482    pub base_url: String,
483    pub email: String,
484    pub name: String,
485}
486
487/// CreateTokenStorage. With a minted key the key is the access token and `expired` stays
488/// empty; without one the DCA token is used and its expiry is tracked.
489pub fn create_token_storage(bundle: &Bundle, now: DateTime<Utc>) -> TokenStorage {
490    let dca_expired = if bundle.token.expires_at > 0 {
491        DateTime::from_timestamp(bundle.token.expires_at, 0)
492            .map(rfc3339_utc)
493            .unwrap_or_default()
494    } else {
495        String::new()
496    };
497    let (mut api_key, mut base_url) = (String::new(), DEFAULT_API_BASE_URL.to_owned());
498    let (mut email, mut name) = (bundle.email.clone(), bundle.name.clone());
499    if let Some(minted) = &bundle.minted {
500        api_key = minted.api_key.clone();
501        if !minted.base_url.trim().is_empty() {
502            base_url = minted.base_url.trim().to_owned();
503        }
504        if !minted.user_email.is_empty() {
505            email = minted.user_email.clone();
506        }
507        if !minted.user_full_name.is_empty() {
508            name = minted.user_full_name.clone();
509        }
510    }
511    let (access_token, expired) = if api_key.is_empty() {
512        (bundle.token.access_token.clone(), dca_expired.clone())
513    } else {
514        (api_key.clone(), String::new())
515    };
516    TokenStorage {
517        access_token,
518        dca_token: bundle.token.access_token.clone(),
519        api_key,
520        token_type: bundle.token.token_type.clone(),
521        expires_in: bundle.token.expires_in,
522        expired,
523        dca_expired,
524        dca_expires_at: bundle.token.expires_at,
525        last_refresh: rfc3339_utc(now),
526        base_url,
527        email,
528        name,
529    }
530}
531
532/// CredentialFileName: a readable account name plus an identity hash, so distinct emails
533/// that sanitize identically never share a file.
534pub fn credential_file_name(email: &str, sub: &str) -> String {
535    let hash = |s: &str| hex8(&Sha256::digest(s.as_bytes()));
536    let clean = email.trim();
537    if !clean.is_empty() {
538        let mut sanitized: String = clean
539            .chars()
540            .map(|c| {
541                if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
542                    c
543                } else {
544                    '_'
545                }
546            })
547            .collect();
548        sanitized.truncate(120);
549        return format!("meta-{sanitized}-{}.json", hash(clean));
550    }
551    let sub = sub.trim();
552    if !sub.is_empty() {
553        return format!("meta-{}.json", hash(sub));
554    }
555    "meta-oauth.json".into()
556}
557
558fn hex8(digest: &[u8]) -> String {
559    digest[..8].iter().map(|b| format!("{b:02x}")).collect()
560}
561
562/// Fields the custom writer owns. They are never restored from disk or metadata.
563const CREDENTIAL_FIELDS: [&str; 11] = [
564    "type",
565    "auth_kind",
566    "access_token",
567    "token_type",
568    "dca_token",
569    "api_key",
570    "expires_in",
571    "expired",
572    "dca_expired",
573    "dca_expires_at",
574    "last_refresh",
575];
576
577/// A Go `map[string]any` as the custom writer sees it.
578pub(crate) type GoMap = BTreeMap<String, GoValue>;
579
580/// Go `json.Unmarshal` into `map[string]any`: numbers become float64, so they re-encode
581/// in Go's float form (`1.0` -> `1`, `1e21` -> `1e+21`). A number that overflows float64
582/// becomes `null` and marks the decode as failed (Go keeps the partial map and returns an
583/// error). `None` when Go leaves the map nil: invalid JSON or a non-object.
584pub(crate) fn go_map_from_json(raw: &[u8]) -> Option<(GoMap, bool)> {
585    check_valid(raw).ok()?;
586    match GoValue::parse(raw)?.into_object() {
587        Ok(map) => {
588            // Go keeps decoding after an overflow and keeps the error even when a later
589            // duplicate key overwrites the value, so every number in the document counts.
590            let mut clean = all_numbers_finite(raw);
591            let mut value = GoValue::Object(map);
592            value.visit_mut(|v| {
593                if let GoValue::Number(literal) = v {
594                    *v = match go_float(literal) {
595                        Some(number) => GoValue::Number(number),
596                        None => {
597                            clean = false;
598                            GoValue::Null
599                        }
600                    };
601                }
602            });
603            Some((value.into_object().ok()?, clean))
604        }
605        _ => None,
606    }
607}
608
609/// Whether every number literal in valid JSON `raw` fits a float64, in one scan: outside
610/// strings, a number is the only token that starts with `-` or a digit.
611fn all_numbers_finite(raw: &[u8]) -> bool {
612    let mut i = 0;
613    while let Some(&c) = raw.get(i) {
614        match c {
615            b'"' => {
616                i += 1;
617                while let Some(&c) = raw.get(i) {
618                    i += if c == b'\\' { 2 } else { 1 };
619                    if c == b'"' {
620                        break;
621                    }
622                }
623            }
624            b'-' | b'0'..=b'9' => {
625                let start = i;
626                while raw
627                    .get(i)
628                    .is_some_and(|c| matches!(c, b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9'))
629                {
630                    i += 1;
631                }
632                if go_float(&String::from_utf8_lossy(&raw[start..i])).is_none() {
633                    return false;
634                }
635            }
636            _ => i += 1,
637        }
638    }
639    true
640}
641
642/// Go's encoding of a float64 decoded from `literal`, or `None` when the literal
643/// overflows float64 (Go: UnmarshalTypeError).
644fn go_float(literal: &str) -> Option<String> {
645    gj::json_float(literal.parse::<f64>().ok()?)
646}
647
648/// SaveTokenToFile's content. With a `snapshot` (managed saves) its non-credential keys
649/// override storage; without one, non-credential keys from `disk` fill only missing keys.
650pub(crate) fn encode_token_file(storage: &TokenStorage, snapshot: Option<&GoMap>, disk: Option<&[u8]>) -> String {
651    let s = |v: &str| GoValue::String(v.to_owned());
652    let mut data = GoMap::new();
653    data.insert("type".into(), s("meta"));
654    data.insert("auth_kind".into(), s("oauth"));
655    data.insert("access_token".into(), s(&storage.access_token));
656    let optional = [
657        ("dca_token", &storage.dca_token),
658        ("api_key", &storage.api_key),
659        ("token_type", &storage.token_type),
660        ("expired", &storage.expired),
661        ("dca_expired", &storage.dca_expired),
662        ("last_refresh", &storage.last_refresh),
663        ("base_url", &storage.base_url),
664        ("email", &storage.email),
665        ("name", &storage.name),
666    ];
667    for (key, value) in optional {
668        if !value.is_empty() {
669            data.insert(key.into(), s(value));
670        }
671    }
672    if storage.expires_in > 0 {
673        data.insert("expires_in".into(), GoValue::Number(storage.expires_in.to_string()));
674    }
675    if storage.dca_expires_at > 0 {
676        data.insert(
677            "dca_expires_at".into(),
678            GoValue::Number(storage.dca_expires_at.to_string()),
679        );
680    }
681    // Go ignores the decode error and uses whatever the map holds.
682    let from_disk = if snapshot.is_none() {
683        disk.and_then(go_map_from_json).map(|(map, _)| map)
684    } else {
685        None
686    };
687    if let Some(metadata) = snapshot.or(from_disk.as_ref()) {
688        for (key, value) in metadata {
689            if CREDENTIAL_FIELDS.contains(&key.as_str()) {
690                continue;
691            }
692            if snapshot.is_some() || !data.contains_key(key) {
693                data.insert(key.clone(), value.clone());
694            }
695        }
696    }
697    String::from_utf8_lossy(&GoValue::Object(data).encode_indented()).into_owned()
698}
699
700/// SaveTokenToFile: indented JSON plus newline, atomically replaced through a private
701/// temporary file in the same directory.
702pub(crate) fn save_token_file(path: &Path, storage: &TokenStorage, snapshot: Option<&GoMap>) -> std::io::Result<()> {
703    let disk = if snapshot.is_none() {
704        std::fs::read(path).ok()
705    } else {
706        None
707    };
708    write_private(path, encode_token_file(storage, snapshot, disk.as_deref()).as_bytes())
709}
710
711/// `IsAuthTokenPayloadKey`: token fields a re-login always replaces.
712fn is_token_payload_key(key: &str) -> bool {
713    matches!(
714        key.trim().to_ascii_lowercase().as_str(),
715        "access_token"
716            | "refresh_token"
717            | "id_token"
718            | "session_id"
719            | "expired"
720            | "last_refresh"
721            | "expires_in"
722            | "timestamp"
723            | "token_type"
724            | "user_code"
725            | "verification_uri"
726            | "verification_uri_complete"
727    )
728}
729
730/// `CanonicalCredentialMetadataKey`.
731fn canonical_key(key: &str) -> &str {
732    match key {
733        "api-key" => "api_key",
734        "base-url" => "base_url",
735        "disable-cooling" => "disable_cooling",
736        "excluded-models" => "excluded_models",
737        "fingerprint-profile" => "fingerprint_profile",
738        "model-aliases" => "model_aliases",
739        "openapi-location" => "openapi_location",
740        "openapi-models" => "openapi_models",
741        "proxy-url" => "proxy_url",
742        "request-retry" => "request_retry",
743        "request-scoped-errors" => "request_scoped_errors",
744        "tool-prefix-disabled" => "tool_prefix_disabled",
745        other => other,
746    }
747}
748
749/// `MergeExistingAuthMetadata` for a login that lands on an existing file: user settings
750/// survive, token payload (and Meta's key material) does not. Returns the disabled flag
751/// the file carried, unless the new metadata sets one.
752pub(crate) fn merge_existing(metadata: &mut GoMap, existing: &GoMap, provider: &str) -> Option<bool> {
753    let disabled = match (metadata.contains_key("disabled"), existing.get("disabled")) {
754        (false, Some(GoValue::Bool(b))) => Some(*b),
755        _ => None,
756    };
757    let meta = provider.trim().eq_ignore_ascii_case("meta");
758    for (key, value) in existing {
759        if is_token_payload_key(key) {
760            continue;
761        }
762        if meta
763            && matches!(
764                canonical_key(key),
765                "api_key" | "dca_token" | "dca_expired" | "dca_expires_at"
766            )
767        {
768            continue;
769        }
770        metadata.entry(key.clone()).or_insert_with(|| value.clone());
771    }
772    disabled
773}
774
775/// `NormalizeCredentialMetadata`: alias keys become canonical; an explicit canonical key wins.
776pub(crate) fn normalize_metadata(metadata: &mut GoMap) {
777    let aliases: Vec<String> = metadata
778        .keys()
779        .filter(|k| canonical_key(k) != k.as_str())
780        .cloned()
781        .collect();
782    for alias in aliases {
783        let canonical = canonical_key(&alias).to_owned();
784        if let Some(value) = metadata.remove(&alias) {
785            metadata.entry(canonical).or_insert(value);
786        }
787    }
788}
789
790/// The login record sdk/auth/meta.go builds before the token store merges and saves it.
791pub(crate) fn login_metadata(storage: &TokenStorage, bundle: &Bundle) -> GoMap {
792    let s = |v: &str| GoValue::String(v.to_owned());
793    let n = |v: i64| GoValue::Number(v.to_string());
794    let mut m = GoMap::new();
795    m.insert("type".into(), s("meta"));
796    m.insert("access_token".into(), s(&storage.access_token));
797    m.insert("token_type".into(), s(&storage.token_type));
798    m.insert("expires_in".into(), n(storage.expires_in));
799    m.insert("expired".into(), s(&storage.expired));
800    m.insert("last_refresh".into(), s(&storage.last_refresh));
801    m.insert("base_url".into(), s(&storage.base_url));
802    m.insert("auth_kind".into(), s("oauth"));
803    if !storage.dca_expired.is_empty() {
804        m.insert("dca_expired".into(), s(&storage.dca_expired));
805    }
806    if storage.dca_expires_at > 0 {
807        m.insert("dca_expires_at".into(), n(storage.dca_expires_at));
808    }
809    for (key, value) in [
810        ("api_key", &storage.api_key),
811        ("dca_token", &storage.dca_token),
812        ("email", &storage.email),
813        ("name", &storage.name),
814    ] {
815        if !value.is_empty() {
816            m.insert(key.into(), s(value));
817        }
818    }
819    if let Some(minted) = &bundle.minted {
820        m.insert("subs_tier_name".into(), s(&minted.subs_tier_name));
821        m.insert("subs_tier_id".into(), s(&minted.subs_tier_id));
822        m.insert("is_subs_active".into(), GoValue::Bool(minted.is_subs_active));
823        m.insert("has_payment_method".into(), GoValue::Bool(minted.has_payment_method));
824    }
825    m
826}
827
828/// A saved login.
829#[derive(Debug, Clone, PartialEq, Eq)]
830pub struct LoginOutcome {
831    pub path: PathBuf,
832    pub label: String,
833}
834
835/// Builds and writes the credential for `bundle` the way Manager.Login and the file
836/// token store do: merge an existing file's settings, normalize keys, validate the weight,
837/// stamp `disabled`, then the custom writer.
838pub fn save_login(auth_dir: &Path, bundle: &Bundle, now: DateTime<Utc>) -> Result<LoginOutcome, String> {
839    let storage = create_token_storage(bundle, now);
840    if storage.access_token.trim().is_empty() {
841        return Err("meta token storage missing access token".into());
842    }
843    let file_name = credential_file_name(&storage.email, &storage.dca_token);
844    let label = match storage.email.trim() {
845        "" => "Meta".to_owned(),
846        email => email.to_owned(),
847    };
848    let mut metadata = login_metadata(&storage, bundle);
849    let path = auth_dir.join(&file_name);
850    let mut disabled = false;
851    // Manager.Login merges only a cleanly decoded, non-empty existing file.
852    if let Ok(raw) = std::fs::read(&path)
853        && let Some((existing, true)) = go_map_from_json(&raw)
854        && !existing.is_empty()
855        && let Some(flag) = merge_existing(&mut metadata, &existing, "meta")
856    {
857        disabled = flag;
858    }
859    normalize_metadata(&mut metadata);
860    if let Some(weight) = metadata.get("weight") {
861        let json: Value = serde_json::from_slice(&weight.marshal()).unwrap_or(Value::Null);
862        cpa_core::config::credentials::parse_weight(&json)
863            .map_err(|e| format!("auth filestore: invalid metadata weight: {e}"))?;
864    }
865    metadata.insert("disabled".into(), GoValue::Bool(disabled));
866    save_token_file(&path, &storage, Some(&metadata)).map_err(|e| format!("meta token storage: {e}"))?;
867    Ok(LoginOutcome { path, label })
868}
869
870/// `--meta-login`: device flow through `requests.proxy-url`, then the credential file in
871/// `auth-dir`.
872pub async fn login(cfg: &cpa_core::config::Config, no_browser: bool) -> Result<PathBuf, ExecError> {
873    let proxy = cfg
874        .document
875        .get("requests")
876        .and_then(|r| r.get("proxy-url"))
877        .and_then(|v| v.as_str())
878        .unwrap_or_default();
879    let client = crate::proxy::GoClients::new(crate::proxy::Hooks::default()).get(&crate::proxy::Proxy::parse(proxy));
880    let outcome = login_with(MetaAuth::new(client), &cfg.auth_dir, no_browser)
881        .await
882        .map_err(|e| {
883            ExecError::local(
884                500,
885                FailureScope::Credential,
886                format!("Meta authentication failed: {e}"),
887            )
888        })?;
889    println!("Authentication saved to {}", outcome.path.display());
890    println!("Authenticated as {}", outcome.label);
891    println!("Meta authentication successful!");
892    Ok(outcome.path)
893}
894
895pub(crate) async fn login_with(auth: MetaAuth, auth_dir: &Path, no_browser: bool) -> Result<LoginOutcome, String> {
896    println!("Starting Meta (Muse) authentication...");
897    let code = auth
898        .start_device_flow()
899        .await
900        .map_err(|e| format!("meta: failed to start device flow: {e}"))?;
901    let url = match code.verification_uri_complete.trim() {
902        "" => code.verification_uri.trim(),
903        complete => complete,
904    };
905    print!("\nTo authenticate, please visit:\n{url}\n\n");
906    if !code.user_code.is_empty() {
907        print!("Then enter this code: {}\n\n", code.user_code);
908    }
909    if !no_browser {
910        if open_browser(url) {
911            println!("Browser opened automatically.");
912        } else {
913            tracing::warn!("No browser available; please open the URL manually");
914        }
915    }
916    println!("Waiting for authorization...");
917    if code.expires_in > 0 {
918        println!("(This will timeout in {} seconds if not authorized)", code.expires_in);
919    }
920    let bundle = auth
921        .wait_for_authorization(&code)
922        .await
923        .map_err(|e| format!("meta: {e}"))?;
924    println!("Meta authentication successful");
925    let auth_dir = auth_dir.to_owned();
926    let now = auth.now();
927    tokio::task::spawn_blocking(move || save_login(&auth_dir, &bundle, now))
928        .await
929        .map_err(|_| "meta: credential publication failed".to_owned())?
930}
931
932#[cfg(test)]
933mod tests {
934    use super::*;
935
936    /// An existing credential at encoding/json's depth limit converts its numbers to
937    /// float64 on a 2 MiB stack; an overflowing literal anywhere marks it unclean.
938    #[test]
939    fn go_map_from_json_handles_the_depth_limit() {
940        std::thread::Builder::new()
941            .stack_size(2 << 20)
942            .spawn(|| {
943                let deep = |leaf: &str| format!(r#"{{"a":{}{leaf}{}}}"#, r#"[{"d":"#.repeat(4_999), "}]".repeat(4_999));
944                let (map, clean) = go_map_from_json(deep("1.50").as_bytes()).unwrap();
945                assert!(clean);
946                assert_eq!(GoValue::Object(map).marshal(), deep("1.5").into_bytes());
947                let (map, clean) = go_map_from_json(deep(r#"["x\"1e400",1e400]"#).as_bytes()).unwrap();
948                assert!(!clean);
949                assert_eq!(
950                    GoValue::Object(map).marshal(),
951                    deep(r#"["x\"1e400",null]"#).into_bytes()
952                );
953                let (_, clean) = go_map_from_json(deep(r#""-1e400""#).as_bytes()).unwrap();
954                assert!(clean, "a number inside a string does not count");
955            })
956            .unwrap()
957            .join()
958            .unwrap();
959    }
960
961    #[test]
962    fn go_float_matches_strconv() {
963        // Expected strings from Go: json.Marshal(float64(x)).
964        for (literal, go) in [
965            ("1", "1"),
966            ("1.0", "1"),
967            ("0.10", "0.1"),
968            ("1e3", "1000"),
969            ("1e21", "1e+21"),
970            ("1.5e-7", "1.5e-7"),
971            ("1e-10", "1e-10"),
972            ("0.000001", "0.000001"),
973            ("-2.50", "-2.5"),
974            ("9007199254740993", "9007199254740992"),
975            ("123456789012345678901", "123456789012345680000"),
976        ] {
977            assert_eq!(go_float(literal).as_deref(), Some(go), "{literal}");
978        }
979        assert_eq!(go_float("1e400"), None, "float64 overflow is a decode error");
980    }
981
982    #[test]
983    fn merge_skips_token_payload_and_meta_key_material() {
984        let mut metadata = GoMap::new();
985        metadata.insert("email".into(), GoValue::String("new@x".into()));
986        let (existing, clean) = go_map_from_json(
987            br#"{"email":"old@x","EXPIRED":"x","api-key":"k","dca_token":"d","prefix":"p","disabled":true}"#,
988        )
989        .unwrap();
990        assert!(clean);
991        assert_eq!(merge_existing(&mut metadata, &existing, "meta"), Some(true));
992        let keys: Vec<&str> = metadata.keys().map(String::as_str).collect();
993        assert_eq!(keys, ["disabled", "email", "prefix"]);
994        assert_eq!(metadata["email"], GoValue::String("new@x".into()));
995        // Other providers keep the key material.
996        let mut other = GoMap::new();
997        merge_existing(&mut other, &existing, "kimi");
998        assert!(other.contains_key("api-key") && other.contains_key("dca_token"));
999    }
1000}