Skip to main content

cpa_exec/
kimi_auth.rs

1//! Kimi (.com and .ai) RFC 8628 device login, token refresh and credential files
2//! (internal/auth/kimi, sdk/auth/kimi.go).
3//!
4//! The public functions are the building blocks the CLI flags and the management
5//! `kimi-auth-url` flow both need: start, poll, build the record, write it.
6
7use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9use std::sync::{LazyLock, Mutex};
10use std::time::Duration;
11
12use chrono::{TimeZone, Utc};
13use cpa_core::credential::{Credential, MetadataPatch};
14use cpa_core::exec::{ExecError, FailureScope};
15use futures_util::FutureExt;
16use futures_util::future::{BoxFuture, Shared};
17use serde_json::{Map, Value, json};
18
19use crate::kimi_http::{BUILD_VERSION, auth_error, go_arch, go_os, hostname, rfc3339_utc};
20use crate::proxy::GoHeaders;
21use cpa_common::json::GoValue;
22
23pub const CLIENT_ID: &str = "17e5f671-d194-4dfb-9706-5516cb48c098";
24pub const DOMAIN_COM: &str = "kimi.com";
25pub const DOMAIN_AI: &str = "kimi.ai";
26pub const OAUTH_HOST_COM: &str = "https://auth.kimi.com";
27pub const OAUTH_HOST_AI: &str = "https://auth.kimi.ai";
28pub const API_BASE_COM: &str = "https://api.kimi.com/coding";
29pub const API_BASE_AI: &str = "https://api.kimi.ai/coding";
30/// SDK refresh lead (sdk/auth/kimi.go).
31pub const REFRESH_LEAD: Duration = Duration::from_secs(300);
32const MIN_POLL_INTERVAL: Duration = Duration::from_secs(5);
33const MAX_POLL_DURATION: Duration = Duration::from_secs(15 * 60);
34const DEVICE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
35
36pub fn is_ai_domain(domain: &str) -> bool {
37    let d = domain.trim().to_ascii_lowercase();
38    d == "kimi.ai" || d == "ai" || d == "kimi-ai" || d.ends_with(".kimi.ai")
39}
40
41pub fn is_com_domain(domain: &str) -> bool {
42    let d = domain.trim().to_ascii_lowercase();
43    d == "kimi.com" || d == "com" || d == "kimi" || d.ends_with(".kimi.com")
44}
45
46fn host_of(raw: &str) -> String {
47    let raw = raw.trim();
48    // net/url accepts scheme-relative authorities ("//host/path").
49    let absolute = if raw.starts_with("//") {
50        format!("http:{raw}")
51    } else {
52        raw.to_owned()
53    };
54    url::Url::parse(&absolute)
55        .ok()
56        .and_then(|u| u.host_str().map(str::to_ascii_lowercase))
57        .unwrap_or_default()
58}
59
60fn is_ai_host(raw: &str) -> bool {
61    let host = host_of(raw);
62    host == "kimi.ai" || host.ends_with(".kimi.ai")
63}
64
65fn is_com_host(raw: &str) -> bool {
66    let host = host_of(raw);
67    host == "kimi.com" || host.ends_with(".kimi.com")
68}
69
70pub fn normalize_domain(domain: &str) -> &'static str {
71    if is_ai_domain(domain) { DOMAIN_AI } else { DOMAIN_COM }
72}
73
74pub fn oauth_host(domain: &str) -> &'static str {
75    if is_ai_domain(domain) {
76        OAUTH_HOST_AI
77    } else {
78        OAUTH_HOST_COM
79    }
80}
81
82pub fn api_base(domain: &str) -> &'static str {
83    if is_ai_domain(domain) {
84        API_BASE_AI
85    } else {
86        API_BASE_COM
87    }
88}
89
90/// `ResolveKimiDomainFromAuth`: explicit domain, base URL and type win over the provider
91/// and finally the file name.
92pub fn resolve_domain(credential: &Credential) -> &'static str {
93    let classify_domain = |d: &str| {
94        if is_ai_domain(d) {
95            Some(DOMAIN_AI)
96        } else if is_com_domain(d) {
97            Some(DOMAIN_COM)
98        } else {
99            None
100        }
101    };
102    let classify_url = |u: &str| {
103        if is_ai_host(u) {
104            Some(DOMAIN_AI)
105        } else if is_com_host(u) {
106            Some(DOMAIN_COM)
107        } else {
108            None
109        }
110    };
111    let attr = |k: &str| {
112        credential
113            .attributes
114            .get(k)
115            .map(String::as_str)
116            .filter(|s| !s.is_empty())
117    };
118    let meta = |k: &str| credential.str(k).filter(|s| !s.trim().is_empty());
119    attr("domain")
120        .and_then(classify_domain)
121        .or_else(|| attr("base_url").and_then(classify_url))
122        .or_else(|| meta("domain").and_then(classify_domain))
123        .or_else(|| meta("base_url").and_then(classify_url))
124        .or_else(|| meta("type").and_then(classify_domain))
125        .or_else(|| classify_domain(&credential.provider))
126        .unwrap_or_else(|| {
127            let id = credential.id.to_ascii_lowercase();
128            let file = Path::new(&id)
129                .file_name()
130                .and_then(|f| f.to_str())
131                .unwrap_or_default()
132                .to_owned();
133            if [&id, &file]
134                .iter()
135                .any(|s| s.contains("kimi-ai") || s.contains("kimi.ai"))
136            {
137                DOMAIN_AI
138            } else {
139                DOMAIN_COM
140            }
141        })
142}
143
144/// Go `url.QueryEscape` for form bodies.
145fn query_escape(s: &str) -> String {
146    let mut out = String::with_capacity(s.len());
147    for b in s.bytes() {
148        match b {
149            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
150            b' ' => out.push('+'),
151            _ => out.push_str(&format!("%{b:02X}")),
152        }
153    }
154    out
155}
156
157/// Go `url.Values.Encode`: keys sorted.
158pub(crate) fn form(pairs: &[(&str, &str)]) -> String {
159    let mut pairs = pairs.to_vec();
160    pairs.sort_by(|a, b| a.0.cmp(b.0));
161    pairs
162        .iter()
163        .map(|(k, v)| format!("{}={}", query_escape(k), query_escape(v)))
164        .collect::<Vec<_>>()
165        .join("&")
166}
167
168/// Device-flow device model (`getDeviceModel`), unlike the executor's lowercase form.
169fn device_model() -> String {
170    match go_os() {
171        "darwin" => format!("macOS {}", go_arch()),
172        "windows" => format!("Windows {}", go_arch()),
173        "linux" => format!("Linux {}", go_arch()),
174        os => format!("{os} {}", go_arch()),
175    }
176}
177
178/// Device authorization response (RFC 8628).
179#[derive(Debug, Clone, Default)]
180pub struct DeviceCode {
181    pub device_code: String,
182    pub user_code: String,
183    pub verification_uri: String,
184    pub verification_uri_complete: String,
185    pub expires_in: i64,
186    pub interval: i64,
187}
188
189/// Go `json.Unmarshal` into typed fields: missing or null keep the zero value, a wrong
190/// JSON type is an error.
191#[derive(serde::Deserialize, Default)]
192#[serde(default)]
193struct DeviceCodeWire {
194    device_code: Option<String>,
195    user_code: Option<String>,
196    verification_uri: Option<String>,
197    verification_uri_complete: Option<String>,
198    expires_in: Option<i64>,
199    interval: Option<i64>,
200}
201
202#[derive(serde::Deserialize, Default)]
203#[serde(default)]
204struct TokenWire {
205    access_token: Option<String>,
206    refresh_token: Option<String>,
207    token_type: Option<String>,
208    expires_in: Option<f64>,
209    scope: Option<String>,
210}
211
212#[derive(serde::Deserialize, Default)]
213#[serde(default)]
214struct PollWire {
215    error: Option<String>,
216    error_description: Option<String>,
217    #[serde(flatten)]
218    token: TokenWire,
219}
220
221/// Token endpoint result. `expires_at` is Unix seconds, 0 when the server sent none.
222#[derive(Debug, Clone, Default, PartialEq, Eq)]
223pub struct Tokens {
224    pub access_token: String,
225    pub refresh_token: String,
226    pub token_type: String,
227    pub expires_at: i64,
228    pub scope: String,
229}
230
231/// One device-flow client: fixed domain, OAuth host and device identity.
232#[derive(Clone)]
233pub struct DeviceFlow {
234    client: wreq::Client,
235    oauth_host: String,
236    device_id: String,
237    min_interval: Duration,
238}
239
240impl DeviceFlow {
241    /// `device_id` empty creates a fresh in-memory UUID, as Go does per login.
242    pub fn new(client: wreq::Client, domain: &str, device_id: &str) -> Self {
243        let device_id = device_id.trim();
244        Self {
245            client,
246            oauth_host: oauth_host(domain).to_owned(),
247            device_id: if device_id.is_empty() {
248                uuid::Uuid::new_v4().to_string()
249            } else {
250                device_id.to_owned()
251            },
252            min_interval: MIN_POLL_INTERVAL,
253        }
254    }
255
256    /// Lowers the 5s polling floor so tests do not wait for real time.
257    #[cfg(test)]
258    pub(crate) fn with_min_interval(mut self, interval: Duration) -> Self {
259        self.min_interval = interval;
260        self
261    }
262
263    /// Points the flow at a local mock. Never derive this from credential metadata.
264    pub fn with_oauth_host(mut self, host: &str) -> Self {
265        self.oauth_host = host.trim_end_matches('/').to_owned();
266        self
267    }
268
269    pub fn device_id(&self) -> &str {
270        &self.device_id
271    }
272
273    fn token_url(&self) -> String {
274        format!("{}/api/oauth/token", self.oauth_host)
275    }
276
277    async fn post(&self, url: &str, body: String) -> Result<(u16, Vec<u8>), ExecError> {
278        let mut headers = GoHeaders::new();
279        headers.set("User-Agent", "Go-http-client/1.1");
280        headers.set("Content-Type", "application/x-www-form-urlencoded");
281        headers.set("Accept", "application/json");
282        headers.set("X-Msh-Platform", "CLIProxyAPI");
283        headers.set("X-Msh-Version", BUILD_VERSION);
284        headers.set("X-Msh-Device-Name", hostname().unwrap_or_else(|| "unknown".into()));
285        headers.set("X-Msh-Device-Model", device_model());
286        headers.set("X-Msh-Device-Id", self.device_id.clone());
287        let upstream = crate::proxy::send(&self.client, url, headers, body, Some(Duration::from_secs(30)))
288            .await
289            .map_err(|_| ExecError::local(502, FailureScope::Transport, "kimi: token request failed"))?;
290        let status = upstream.status;
291        let body = crate::proxy::read_all(upstream.body, crate::proxy::MAX_ERROR_BODY, false)
292            .await
293            .map_err(|_| ExecError::local(502, FailureScope::Transport, "kimi: failed to read token response"))?;
294        Ok((status, body.to_vec()))
295    }
296
297    /// Starts the device flow.
298    pub async fn request_device_code(&self) -> Result<DeviceCode, ExecError> {
299        let url = format!("{}/api/oauth/device_authorization", self.oauth_host);
300        let (status, body) = self.post(&url, form(&[("client_id", CLIENT_ID)])).await?;
301        if status != 200 {
302            return Err(auth_error(
303                status,
304                format!("kimi: device code request failed with status {status}"),
305            ));
306        }
307        let wire: DeviceCodeWire =
308            serde_json::from_slice(&body).map_err(|_| auth_error(502, "kimi: failed to parse device code response"))?;
309        Ok(DeviceCode {
310            device_code: wire.device_code.unwrap_or_default(),
311            user_code: wire.user_code.unwrap_or_default(),
312            verification_uri: wire.verification_uri.unwrap_or_default(),
313            verification_uri_complete: wire.verification_uri_complete.unwrap_or_default(),
314            expires_in: wire.expires_in.unwrap_or_default(),
315            interval: wire.interval.unwrap_or_default(),
316        })
317    }
318
319    /// One poll. `Ok(None)` means keep polling (authorization_pending / slow_down).
320    async fn exchange(&self, device_code: &str) -> Result<Option<Tokens>, ExecError> {
321        let body = form(&[
322            ("client_id", CLIENT_ID),
323            ("device_code", device_code),
324            ("grant_type", DEVICE_GRANT),
325        ]);
326        let (_, body) = self.post(&self.token_url(), body).await?;
327        let wire: PollWire =
328            serde_json::from_slice(&body).map_err(|_| auth_error(502, "kimi: failed to parse token response"))?;
329        match wire.error.as_deref().unwrap_or_default() {
330            "" => {}
331            "authorization_pending" | "slow_down" => return Ok(None),
332            "expired_token" => return Err(auth_error(400, "kimi: device code expired")),
333            "access_denied" => return Err(auth_error(403, "kimi: access denied by user")),
334            other => {
335                let description = wire.error_description.unwrap_or_default();
336                return Err(auth_error(400, format!("kimi: OAuth error: {other} - {description}")));
337            }
338        }
339        tokens(wire.token)
340            .map(Some)
341            .ok_or_else(|| auth_error(502, "kimi: empty access token in response"))
342    }
343
344    /// Polls until authorized, denied or expired (interval at least 5s, at most 15 minutes).
345    pub async fn poll(&self, code: &DeviceCode) -> Result<Tokens, ExecError> {
346        let interval = Duration::from_secs(code.interval.max(0) as u64).max(self.min_interval);
347        let mut deadline = tokio::time::Instant::now() + MAX_POLL_DURATION;
348        if code.expires_in > 0 {
349            deadline = deadline.min(tokio::time::Instant::now() + Duration::from_secs(code.expires_in as u64));
350        }
351        let mut ticker = tokio::time::interval_at(tokio::time::Instant::now() + interval, interval);
352        loop {
353            ticker.tick().await;
354            if tokio::time::Instant::now() > deadline {
355                return Err(auth_error(400, "kimi: device code expired"));
356            }
357            if let Some(tokens) = self.exchange(&code.device_code).await? {
358                return Ok(tokens);
359            }
360        }
361    }
362
363    /// Refresh grant, single-flighted per token endpoint and refresh token across every
364    /// client in the process (kimiRefreshGroup). Callers that go away do not cancel it.
365    pub async fn refresh(&self, refresh_token: &str) -> Result<Tokens, ExecError> {
366        let refresh_token = refresh_token.trim().to_owned();
367        if refresh_token.is_empty() {
368            return Err(auth_error(400, "kimi: refresh token is required"));
369        }
370        type Flight = Shared<BoxFuture<'static, Result<Tokens, ExecError>>>;
371        static FLIGHTS: LazyLock<Mutex<HashMap<String, Flight>>> = LazyLock::new(Mutex::default);
372        let key = format!("{}:{refresh_token}", self.token_url());
373        let flight = {
374            let mut flights = FLIGHTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
375            if let Some(flight) = flights.get(&key) {
376                flight.clone()
377            } else {
378                let flow = self.clone();
379                let task_key = key.clone();
380                let task = tokio::spawn(async move {
381                    let result = flow.refresh_once(&refresh_token).await;
382                    FLIGHTS
383                        .lock()
384                        .unwrap_or_else(std::sync::PoisonError::into_inner)
385                        .remove(&task_key);
386                    result
387                });
388                let flight = async move { task.await.map_err(|_| auth_error(502, "kimi: refresh task failed"))? }
389                    .boxed()
390                    .shared();
391                flights.insert(key, flight.clone());
392                flight
393            }
394        };
395        flight.await
396    }
397
398    async fn refresh_once(&self, refresh_token: &str) -> Result<Tokens, ExecError> {
399        let body = form(&[
400            ("client_id", CLIENT_ID),
401            ("grant_type", "refresh_token"),
402            ("refresh_token", refresh_token),
403        ]);
404        let (status, body) = self.post(&self.token_url(), body).await?;
405        if status == 401 || status == 403 {
406            return Err(auth_error(
407                status,
408                format!("kimi: refresh token rejected (status {status})"),
409            ));
410        }
411        if status != 200 {
412            // ponytail: Go appends the response body; it is withheld here because token
413            // endpoints may echo credentials and this message can reach clients.
414            return Err(auth_error(status, format!("kimi: refresh failed with status {status}")));
415        }
416        let wire: TokenWire =
417            serde_json::from_slice(&body).map_err(|_| auth_error(502, "kimi: failed to parse refresh response"))?;
418        tokens(wire).ok_or_else(|| auth_error(502, "kimi: empty access token in refresh response"))
419    }
420}
421
422fn tokens(wire: TokenWire) -> Option<Tokens> {
423    let access = wire.access_token.unwrap_or_default();
424    if access.is_empty() {
425        return None;
426    }
427    let expires_in = wire.expires_in.unwrap_or(0.0);
428    Some(Tokens {
429        access_token: access,
430        refresh_token: wire.refresh_token.unwrap_or_default(),
431        token_type: wire.token_type.unwrap_or_default(),
432        expires_at: if expires_in > 0.0 {
433            Utc::now().timestamp() + expires_in as i64
434        } else {
435            0
436        },
437        scope: wire.scope.unwrap_or_default(),
438    })
439}
440
441fn expiry_string(expires_at: i64) -> Option<String> {
442    (expires_at > 0)
443        .then(|| Utc.timestamp_opt(expires_at, 0).single().map(rfc3339_utc))
444        .flatten()
445}
446
447/// Metadata patch for a successful refresh (KimiExecutor.Refresh). `base_url` is the
448/// effective base the executor resolved for this credential.
449pub fn refresh_patch(credential: &Credential, tokens: &Tokens, base_url: &str, now_local: String) -> MetadataPatch {
450    let domain = resolve_domain(credential);
451    let mut patch = MetadataPatch::default();
452    patch
453        .set
454        .insert("access_token".into(), tokens.access_token.clone().into());
455    if !tokens.refresh_token.is_empty() {
456        patch
457            .set
458            .insert("refresh_token".into(), tokens.refresh_token.clone().into());
459    }
460    if let Some(expired) = expiry_string(tokens.expires_at) {
461        patch.set.insert("expired".into(), expired.into());
462    }
463    if credential.str("type").is_none_or(str::is_empty) {
464        let kind = if is_ai_domain(domain) { "kimi-ai" } else { "kimi" };
465        patch.set.insert("type".into(), kind.into());
466    }
467    if !credential.metadata.contains_key("domain") {
468        patch.set.insert("domain".into(), domain.into());
469    }
470    if !credential.metadata.contains_key("base_url") {
471        patch.set.insert("base_url".into(), base_url.into());
472    }
473    patch.set.insert("last_refresh".into(), now_local.into());
474    patch
475}
476
477/// A finished login: the credential file name and its JSON object.
478pub struct LoginRecord {
479    pub file_name: String,
480    pub metadata: Map<String, Value>,
481    pub label: String,
482}
483
484/// Builds the saved credential exactly as Go's token storage plus flattened metadata,
485/// including FileStore's `disabled: false`.
486pub fn login_record(provider: &str, tokens: &Tokens, device_id: &str, now_ms: i64) -> LoginRecord {
487    let ai = provider != "kimi";
488    let (domain, prefix, display) = if ai {
489        (DOMAIN_AI, "kimi-ai", "Kimi.ai")
490    } else {
491        (DOMAIN_COM, "kimi", "Kimi")
492    };
493    let base_url = api_base(domain);
494    let mut metadata = Map::new();
495    // Typed fields first (KimiTokenStorage tags), then metadata overrides them.
496    metadata.insert("access_token".into(), tokens.access_token.clone().into());
497    metadata.insert("refresh_token".into(), tokens.refresh_token.clone().into());
498    metadata.insert("token_type".into(), tokens.token_type.clone().into());
499    if !tokens.scope.is_empty() {
500        metadata.insert("scope".into(), tokens.scope.clone().into());
501    }
502    let device_id = device_id.trim();
503    if !device_id.is_empty() {
504        metadata.insert("device_id".into(), device_id.into());
505    }
506    if let Some(expired) = expiry_string(tokens.expires_at) {
507        metadata.insert("expired".into(), expired.clone().into());
508    }
509    metadata.insert("type".into(), provider.into());
510    metadata.insert("domain".into(), domain.into());
511    metadata.insert("base_url".into(), base_url.into());
512    for (k, v) in [
513        ("type", json!(provider)),
514        ("access_token", json!(tokens.access_token)),
515        ("refresh_token", json!(tokens.refresh_token)),
516        ("token_type", json!(tokens.token_type)),
517        ("scope", json!(tokens.scope)),
518        ("timestamp", json!(now_ms)),
519        ("domain", json!(domain)),
520        ("base_url", json!(base_url)),
521        ("disabled", json!(false)),
522    ] {
523        metadata.insert(k.into(), v);
524    }
525    LoginRecord {
526        file_name: format!("{prefix}-{now_ms}.json"),
527        metadata,
528        label: format!("{display} User"),
529    }
530}
531
532/// Go `json.Encoder` output of a credential map: sorted keys, two-space indent, newline.
533pub(crate) fn encode_credential(metadata: &Map<String, Value>) -> String {
534    String::from_utf8_lossy(&GoValue::from_json(&Value::Object(metadata.clone())).encode_indented()).into_owned()
535}
536
537/// Writes a credential file atomically with mode 0600 in a 0700 directory.
538///
539/// Go uses `os.Create` (0666 before umask) and an in-place write; on Unix a private temp
540/// file and rename is the deliberate, safer choice here (contracts review). Windows has
541/// no mode bits, so it gets Go's behaviour: create the directory, then create or
542/// truncate the file in place.
543#[cfg(not(unix))]
544pub(crate) fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
545    std::fs::create_dir_all(path.parent().unwrap_or_else(|| Path::new(".")))?;
546    std::fs::write(path, contents)
547}
548
549/// Writes a credential file atomically with mode 0600 in a 0700 directory.
550///
551/// Go uses `os.Create` (0666 before umask) and an in-place write; a private temp file and
552/// rename is the deliberate, safer choice here (contracts review).
553#[cfg(unix)]
554pub(crate) fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
555    use std::io::Write;
556    let directory = path.parent().unwrap_or_else(|| Path::new("."));
557    let mut builder = std::fs::DirBuilder::new();
558    builder.recursive(true);
559    {
560        use std::os::unix::fs::DirBuilderExt;
561        builder.mode(0o700);
562    }
563    builder.create(directory)?;
564    let mut suffix = [0u8; 8];
565    getrandom::fill(&mut suffix).map_err(std::io::Error::other)?;
566    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("credential");
567    let temporary = directory.join(format!(
568        ".{name}.{}.tmp",
569        suffix.iter().map(|b| format!("{b:02x}")).collect::<String>()
570    ));
571    let result = (|| {
572        let mut options = std::fs::OpenOptions::new();
573        options.write(true).create_new(true);
574        {
575            use std::os::unix::fs::OpenOptionsExt;
576            options.mode(0o600);
577        }
578        let mut file = options.open(&temporary)?;
579        file.write_all(contents)?;
580        file.sync_all()?;
581        std::fs::rename(&temporary, path)?;
582        std::fs::File::open(directory)?.sync_all()
583    })();
584    if result.is_err() {
585        let _ = std::fs::remove_file(&temporary);
586    }
587    result
588}
589
590/// Opens `url` in the desktop browser; returns whether a launcher started.
591pub(crate) fn open_browser(url: &str) -> bool {
592    let launcher = match go_os() {
593        "darwin" => "open",
594        "windows" => "rundll32",
595        _ => "xdg-open",
596    };
597    let mut command = std::process::Command::new(launcher);
598    if go_os() == "windows" {
599        command.arg("url.dll,FileProtocolHandler");
600    }
601    command
602        .arg(url)
603        .stdout(std::process::Stdio::null())
604        .stderr(std::process::Stdio::null())
605        .spawn()
606        .is_ok()
607}
608
609/// Writes a finished login into `auth_dir` under its Go file name (management
610/// `kimi-auth-url`); returns the path.
611pub fn write_login(auth_dir: &Path, record: &LoginRecord) -> Result<PathBuf, ExecError> {
612    let path = auth_dir.join(&record.file_name);
613    write_private(&path, encode_credential(&record.metadata).as_bytes())
614        .map_err(|_| auth_error(500, "kimi: cannot write credential file"))?;
615    Ok(path)
616}
617
618/// `--kimi-login` (`provider` "kimi") or `--kimi-ai-login` ("kimi-ai"): device flow
619/// through the configured `requests.proxy-url`, then the credential file in `auth-dir`.
620pub async fn login(provider: &str, cfg: &cpa_core::config::Config, no_browser: bool) -> Result<PathBuf, ExecError> {
621    let domain = if provider == "kimi" { DOMAIN_COM } else { DOMAIN_AI };
622    let proxy = cfg
623        .document
624        .get("requests")
625        .and_then(|r| r.get("proxy-url"))
626        .and_then(|v| v.as_str())
627        .unwrap_or_default();
628    let client = crate::proxy::GoClients::new(crate::proxy::Hooks::default()).get(&crate::proxy::Proxy::parse(proxy));
629    let flow = DeviceFlow::new(client, domain, "");
630    login_with(flow, provider, &cfg.auth_dir, no_browser).await
631}
632
633pub(crate) async fn login_with(
634    flow: DeviceFlow,
635    provider: &str,
636    auth_dir: &Path,
637    no_browser: bool,
638) -> Result<PathBuf, ExecError> {
639    let display = if provider == "kimi" { "Kimi" } else { "Kimi.ai" };
640    println!("Starting {display} authentication...");
641    let code = flow.request_device_code().await?;
642    let url = if code.verification_uri_complete.is_empty() {
643        &code.verification_uri
644    } else {
645        &code.verification_uri_complete
646    };
647    print!("\nTo authenticate, please visit:\n{url}\n\n");
648    if !code.user_code.is_empty() {
649        print!("User code: {}\n\n", code.user_code);
650    }
651    if !no_browser && open_browser(url) {
652        println!("Browser opened automatically.");
653    }
654    println!("Waiting for authorization...");
655    if code.expires_in > 0 {
656        println!("(This will timeout in {} seconds if not authorized)", code.expires_in);
657    }
658    let tokens = flow.poll(&code).await?;
659    print!("\n{display} authentication successful!\n");
660    let record = login_record(provider, &tokens, flow.device_id(), Utc::now().timestamp_millis());
661    let path = auth_dir.join(&record.file_name);
662    println!("Saving credentials to {}", path.display());
663    let contents = encode_credential(&record.metadata);
664    let target = path.clone();
665    tokio::task::spawn_blocking(move || write_private(&target, contents.as_bytes()))
666        .await
667        .map_err(|_| auth_error(500, "kimi: credential publication failed"))?
668        .map_err(|_| auth_error(500, "kimi: cannot write credential file"))?;
669    println!("Authentication saved to {}", path.display());
670    println!("Authenticated as {}", record.label);
671    println!("{display} authentication successful!");
672    Ok(path)
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678
679    fn credential(id: &str, provider: &str, meta: Value) -> Credential {
680        let mut c = Credential::from_file(
681            Path::new("/a"),
682            &Path::new("/a").join(id),
683            meta.as_object().unwrap().clone(),
684        )
685        .unwrap();
686        c.provider = provider.into();
687        c
688    }
689
690    #[test]
691    fn domain_resolution_follows_go_precedence() {
692        // Cases from kimi_test.go TestResolveKimiDomainFromAuth.
693        let c = credential(
694            "x.json",
695            "kimi",
696            json!({"type":"kimi","base_url":"https://api.kimi.ai/coding"}),
697        );
698        assert_eq!(resolve_domain(&c), DOMAIN_AI, "base_url beats type");
699        let c = credential("x.json", "kimi", json!({"type":"kimi-ai","domain":"kimi.com"}));
700        assert_eq!(resolve_domain(&c), DOMAIN_COM, "domain beats type");
701        let c = credential("kimi-ai-1.json", "kimi", json!({"type":"x"}));
702        assert_eq!(resolve_domain(&c), DOMAIN_COM, "provider kimi is explicit");
703        let c = credential("kimi-ai-1.json", "other", json!({"type":"x"}));
704        assert_eq!(resolve_domain(&c), DOMAIN_AI, "file name is the last resort");
705        let mut c = credential("x.json", "kimi", json!({"type":"kimi","domain":"kimi.com"}));
706        c.attributes.insert("domain".into(), "kimi.ai".into());
707        assert_eq!(resolve_domain(&c), DOMAIN_AI, "attributes beat metadata");
708        assert!(is_ai_domain(" SUB.Kimi.AI ") && !is_ai_domain("notkimi.ai"));
709    }
710
711    #[test]
712    fn scheme_relative_base_url_resolves_domain() {
713        let c = credential("x.json", "other", json!({"type":"x","base_url":"//api.kimi.ai/coding"}));
714        assert_eq!(resolve_domain(&c), DOMAIN_AI);
715    }
716
717    #[test]
718    fn oauth_fields_decode_with_go_types() {
719        let ok: TokenWire =
720            serde_json::from_str(r#"{"access_token":"a","expires_in":3600.5,"scope":null,"x":1}"#).unwrap();
721        assert_eq!(ok.expires_in, Some(3600.5));
722        assert!(serde_json::from_str::<TokenWire>(r#"{"access_token":"new","expires_in":"3600"}"#).is_err());
723        assert!(serde_json::from_str::<TokenWire>(r#"{"access_token":"new","refresh_token":5}"#).is_err());
724        assert!(serde_json::from_str::<DeviceCodeWire>(r#"{"device_code":"d","interval":1.5}"#).is_err());
725    }
726
727    #[test]
728    fn form_matches_go_values_encode() {
729        assert_eq!(
730            form(&[("grant_type", DEVICE_GRANT), ("client_id", "a b*~")]),
731            "client_id=a+b%2A~&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code"
732        );
733    }
734}