Skip to main content

cpa_exec/
devin_auth.rs

1//! Devin login and account status (internal/auth/devin, sdk/auth/devin.go,
2//! internal/cmd/devin_login.go).
3//!
4//! Devin uses a browser PKCE flow on app.devin.ai that yields a permanent session token
5//! (`devin-session-token$<jwt>`); there is no refresh token. Account details, plan and
6//! quota come from the Connect-RPC `GetUserStatus` call on the Codeium server, used at
7//! login and by the executor's refresh.
8//!
9//! The management login (Go `RequestDevinToken`) builds on [`DevinAuth`]: it uses
10//! [`DevinAuth::build_authorization_url`] with `http://127.0.0.1:<port>/callback`,
11//! receives the code on the main server's `/callback` route, then calls
12//! [`DevinAuth::exchange_code`], [`DevinAuth::create_auth_record`] and [`save_record`].
13
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16use std::time::Duration;
17
18use base64::Engine;
19use base64::engine::general_purpose::URL_SAFE_NO_PAD;
20use bytes::Bytes;
21use chrono::{DateTime, TimeZone, Utc};
22use cpa_common::json::{self as gj, GoValue};
23use serde_json::{Map, Value};
24use sha2::{Digest, Sha256};
25
26use crate::devin_wire::{device_fingerprint, pb};
27use crate::meta_auth::{GoMap, go_map_from_json, merge_existing, normalize_metadata};
28use crate::proxy::{GoHeaders, read_all, request};
29
30/// `DefaultAppBaseURL`.
31pub const DEFAULT_APP_BASE_URL: &str = "https://app.devin.ai";
32/// `DefaultAPIBaseURL`.
33pub const DEFAULT_API_BASE_URL: &str = "https://api.devin.ai";
34/// `DefaultServerURL`.
35pub const DEFAULT_SERVER_URL: &str = "https://server.codeium.com";
36const TOKEN_PREFIX: &str = "devin-session-token$";
37/// `DevinGetUserStatusPath`.
38pub const USER_STATUS_PATH: &str = "/exa.seat_management_pb.SeatManagementService/GetUserStatus";
39const BODY_LIMIT: usize = 1 << 20;
40const STATUS_LIMIT: usize = 4 << 20;
41const LOGIN_TIMEOUT: Duration = Duration::from_secs(30);
42
43/// `FormatSessionToken`: a bare JWT gets the `devin-session-token$` prefix.
44pub fn format_session_token(raw: &str) -> String {
45    let t = raw.trim();
46    if !t.starts_with(TOKEN_PREFIX) && t.starts_with("eyJ") {
47        return format!("{TOKEN_PREFIX}{t}");
48    }
49    t.to_owned()
50}
51
52/// `PKCECodes`.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Pkce {
55    pub verifier: String,
56    pub challenge: String,
57}
58
59/// `GeneratePKCECodes`: a 64-byte random verifier and its S256 challenge.
60pub fn generate_pkce() -> Result<Pkce, String> {
61    let mut bytes = [0u8; 64];
62    getrandom::fill(&mut bytes).map_err(|e| format!("failed to generate random bytes: {e}"))?;
63    let verifier = URL_SAFE_NO_PAD.encode(bytes);
64    let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
65    Ok(Pkce { verifier, challenge })
66}
67
68/// `misc.GenerateRandomState`: 16 random bytes, hex.
69pub fn random_state() -> Result<String, String> {
70    let mut bytes = [0u8; 16];
71    getrandom::fill(&mut bytes).map_err(|e| format!("failed to generate random bytes: {e}"))?;
72    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
73}
74
75/// `DevinUserStatus`: plan, quota and account metadata from `GetUserStatus`.
76#[derive(Debug, Clone, Default, PartialEq)]
77pub struct UserStatus {
78    pub email: String,
79    pub user_name: String,
80    pub user_id: String,
81    pub team_id: String,
82    pub org_id: String,
83    pub org_name: String,
84    pub plan: String,
85    pub daily_quota_remaining_percent: i64,
86    pub weekly_quota_remaining_percent: i64,
87    pub daily_quota_reset_at: Option<DateTime<Utc>>,
88    pub weekly_quota_reset_at: Option<DateTime<Utc>>,
89    pub plan_start: Option<DateTime<Utc>>,
90    pub plan_end: Option<DateTime<Utc>>,
91}
92
93impl UserStatus {
94    /// The quota observation signals Go writes on refresh and login.
95    pub fn quota_signals(&self) -> Vec<(&'static str, String)> {
96        let mut out = Vec::new();
97        if !self.plan.is_empty() {
98            out.push(("plan", self.plan.clone()));
99        }
100        out.push((
101            "daily_quota_remaining_percent",
102            format!("{}%", self.daily_quota_remaining_percent),
103        ));
104        out.push((
105            "weekly_quota_remaining_percent",
106            format!("{}%", self.weekly_quota_remaining_percent),
107        ));
108        for (key, at) in [
109            ("daily_quota_reset_at", self.daily_quota_reset_at),
110            ("weekly_quota_reset_at", self.weekly_quota_reset_at),
111            ("plan_start", self.plan_start),
112            ("plan_end", self.plan_end),
113        ] {
114            if let Some(at) = at {
115                out.push((key, rfc3339(at)));
116            }
117        }
118        out
119    }
120}
121
122/// Go `time.Time.Format(time.RFC3339)` for a UTC time.
123fn rfc3339(at: DateTime<Utc>) -> String {
124    at.format("%Y-%m-%dT%H:%M:%SZ").to_string()
125}
126
127fn unix(secs: i64) -> Option<DateTime<Utc>> {
128    Utc.timestamp_opt(secs, 0).single()
129}
130
131/// `BuildGetUserStatusRequest`.
132pub(crate) fn user_status_request(session_token: &str, fingerprint: &str) -> Vec<u8> {
133    let fingerprint = if fingerprint.is_empty() {
134        device_fingerprint(session_token)
135    } else {
136        fingerprint.to_owned()
137    };
138    let mut meta = Vec::with_capacity(1024);
139    pb::bytes(&mut meta, 1, b"chisel");
140    pb::bytes(&mut meta, 2, b"3000.10.21");
141    pb::bytes(&mut meta, 3, session_token.as_bytes());
142    pb::bytes(&mut meta, 4, b"en");
143    pb::bytes(&mut meta, 5, crate::kimi_http::go_os().as_bytes());
144    pb::bytes(&mut meta, 7, b"3000.10.21");
145    pb::bytes(&mut meta, 12, b"chisel");
146    pb::bytes(&mut meta, 31, fingerprint.as_bytes());
147    let mut out = Vec::with_capacity(meta.len() + 4);
148    pb::bytes(&mut out, 1, &meta);
149    out
150}
151
152/// Visits each field of a protobuf message; stops quietly at the first parse error.
153/// `f` receives the field number and either its bytes or its varint.
154fn fields(data: &[u8], mut f: impl FnMut(i64, Field<'_>)) -> Result<(), pb::Error> {
155    let mut pos = 0;
156    while pos < data.len() {
157        let (num, wire, n) = pb::consume_tag(&data[pos..])?;
158        pos += n;
159        match wire {
160            pb::BYTES => {
161                let (b, n) = pb::consume_bytes(&data[pos..])?;
162                pos += n;
163                f(num, Field::Bytes(b));
164            }
165            pb::VARINT => {
166                let (v, n) = pb::consume_varint(&data[pos..])?;
167                pos += n;
168                f(num, Field::Varint(v));
169            }
170            _ => pos += pb::consume_field_value(num, wire, &data[pos..])?,
171        }
172    }
173    Ok(())
174}
175
176enum Field<'a> {
177    Bytes(&'a [u8]),
178    Varint(u64),
179}
180
181fn text(b: &[u8]) -> String {
182    String::from_utf8_lossy(b).into_owned()
183}
184
185/// `parseSecondsSubfield`: the varint field 1, 0 when absent or malformed.
186fn seconds(data: &[u8]) -> i64 {
187    let mut pos = 0;
188    while pos < data.len() {
189        let Ok((num, wire, n)) = pb::consume_tag(&data[pos..]) else {
190            return 0;
191        };
192        pos += n;
193        if wire == pb::VARINT {
194            let Ok((v, n)) = pb::consume_varint(&data[pos..]) else {
195                return 0;
196            };
197            pos += n;
198            if num == 1 {
199                return v as i64;
200            }
201        } else {
202            let Ok(n) = pb::consume_field_value(num, wire, &data[pos..]) else {
203                return 0;
204            };
205            pos += n;
206        }
207    }
208    0
209}
210
211/// `ParseGetUserStatusResponse`.
212pub fn parse_user_status(data: &[u8]) -> Result<UserStatus, String> {
213    if data.is_empty() {
214        return Err("empty response data".into());
215    }
216    let mut status = UserStatus::default();
217    let mut pos = 0;
218    while pos < data.len() {
219        let (num, wire, n) = pb::consume_tag(&data[pos..]).map_err(|e| e.to_string())?;
220        pos += n;
221        if num == 1 && wire == pb::BYTES {
222            let (user, n) = pb::consume_bytes(&data[pos..]).map_err(|e| e.to_string())?;
223            pos += n;
224            parse_user(user, &mut status);
225        } else {
226            pos += pb::consume_field_value(num, wire, &data[pos..]).map_err(|e| e.to_string())?;
227        }
228    }
229    Ok(status)
230}
231
232fn parse_user(data: &[u8], status: &mut UserStatus) {
233    let _ = fields(data, |num, field| {
234        if let Field::Bytes(b) = field {
235            match num {
236                3 => status.user_name = text(b),
237                5 => status.team_id = text(b),
238                7 => status.email = text(b),
239                13 => parse_plan_status(b, status),
240                36 => status.user_id = text(b),
241                _ => {}
242            }
243        }
244    });
245}
246
247fn parse_plan_status(data: &[u8], status: &mut UserStatus) {
248    let _ = fields(data, |num, field| match field {
249        Field::Bytes(b) => match num {
250            1 => parse_plan_info(b, status),
251            2 => {
252                let sec = seconds(b);
253                if sec > 0 {
254                    status.plan_start = unix(sec);
255                }
256            }
257            3 => {
258                let sec = seconds(b);
259                if sec > 0 {
260                    status.plan_end = unix(sec);
261                }
262            }
263            _ => {}
264        },
265        Field::Varint(v) => match num {
266            14 => status.daily_quota_remaining_percent = v as i64,
267            15 => status.weekly_quota_remaining_percent = v as i64,
268            17 if v > 0 => status.daily_quota_reset_at = unix(v as i64),
269            18 if v > 0 => status.weekly_quota_reset_at = unix(v as i64),
270            _ => {}
271        },
272    });
273}
274
275fn parse_plan_info(data: &[u8], status: &mut UserStatus) {
276    let _ = fields(data, |num, field| {
277        if let Field::Bytes(b) = field {
278            match num {
279                2 => status.plan = text(b),
280                33 => {
281                    let _ = fields(b, |num, field| {
282                        if let Field::Bytes(b) = field {
283                            match num {
284                                4 => status.org_id = text(b),
285                                8 => status.org_name = text(b),
286                                _ => {}
287                            }
288                        }
289                    });
290                }
291                _ => {}
292            }
293        }
294    });
295}
296
297/// `DevinAuthService`: PKCE URL, code exchange, profile and seat status.
298#[derive(Clone)]
299pub struct DevinAuth {
300    client: wreq::Client,
301    app_base: String,
302    api_base: String,
303    server_base: String,
304    /// The executor's Devin transport (`NewDevinHTTPClient`): no automatic gzip.
305    devin_transport: bool,
306}
307
308impl DevinAuth {
309    pub fn new(client: wreq::Client) -> Self {
310        Self {
311            client,
312            app_base: DEFAULT_APP_BASE_URL.into(),
313            api_base: DEFAULT_API_BASE_URL.into(),
314            server_base: DEFAULT_SERVER_URL.into(),
315            devin_transport: false,
316        }
317    }
318
319    fn base(url: &str) -> Option<String> {
320        let url = url.trim();
321        (!url.is_empty()).then(|| url.trim_end_matches('/').to_owned())
322    }
323
324    /// `SetAppBaseURL`.
325    pub fn with_app_base(mut self, url: &str) -> Self {
326        if let Some(b) = Self::base(url) {
327            self.app_base = b;
328        }
329        self
330    }
331
332    /// `SetAPIBaseURL`.
333    pub fn with_api_base(mut self, url: &str) -> Self {
334        if let Some(b) = Self::base(url) {
335            self.api_base = b;
336        }
337        self
338    }
339
340    /// `SetServerBaseURL`.
341    pub fn with_server_base(mut self, url: &str) -> Self {
342        if let Some(b) = Self::base(url) {
343            self.server_base = b;
344        }
345        self
346    }
347
348    /// Sends through the executor's Devin transport (no automatic gzip).
349    pub(crate) fn with_devin_transport(mut self) -> Self {
350        self.devin_transport = true;
351        self
352    }
353
354    /// `BuildAuthorizationURL`: query parameters in the Devin CLI's order; without a
355    /// redirect URI it is the headless manual-code URL (`cli_pkce_marker=1`).
356    pub fn build_authorization_url(&self, redirect_uri: &str, code_challenge: &str, state: &str) -> String {
357        let redirect = redirect_uri.trim();
358        let mut parts = Vec::new();
359        if !redirect.is_empty() {
360            parts.push(format!("redirect_uri={}", query_escape(redirect)));
361        }
362        if !state.is_empty() {
363            parts.push(format!("state={}", query_escape(state)));
364        }
365        parts.push("prompt=select_account".into());
366        parts.push(format!("code_challenge={}", query_escape(code_challenge)));
367        parts.push("code_challenge_method=S256".into());
368        if redirect.is_empty() {
369            parts.push("cli_pkce_marker=1".into());
370        }
371        format!(
372            "{}/auth/cli/continue?{}",
373            self.app_base.trim_end_matches('/'),
374            parts.join("&")
375        )
376    }
377
378    fn headers(&self) -> GoHeaders {
379        let mut h = GoHeaders::new();
380        if self.devin_transport {
381            h.disable_compression();
382        }
383        h
384    }
385
386    /// `ExchangeCodeForToken`: the session token for an authorization code.
387    pub async fn exchange_code(&self, code: &str, code_verifier: &str) -> Result<String, String> {
388        let mut body = br#"{"code":"#.to_vec();
389        gj::marshal_str(&mut body, code.trim().as_bytes(), true);
390        body.extend_from_slice(br#","code_verifier":"#);
391        gj::marshal_str(&mut body, code_verifier.trim().as_bytes(), true);
392        body.push(b'}');
393        let mut h = self.headers();
394        h.set("Content-Type", "application/json");
395        h.set("Accept", "application/json");
396        let url = format!("{}/auth/cli/token", self.api_base.trim_end_matches('/'));
397        let upstream = request(
398            &self.client,
399            wreq::Method::POST,
400            &url,
401            h,
402            Some(Bytes::from(body)),
403            Some(LOGIN_TIMEOUT),
404        )
405        .await
406        .map_err(|e| format!("devin token exchange failed: {}", lossy(&e.body)))?;
407        let status = upstream.status;
408        let data = read_all(upstream.body, BODY_LIMIT, false)
409            .await
410            .map_err(|e| format!("read token exchange response: {}", lossy(&e.body)))?;
411        // Go appends the response body to both errors; it can carry the session token and
412        // the message is logged, so it is withheld.
413        if !(200..300).contains(&status) {
414            return Err(format!("token exchange failed with status {status}"));
415        }
416        let token = gj::get(&data, "token").str().trim().to_owned();
417        if token.is_empty() {
418            return Err("response did not contain a valid token".into());
419        }
420        Ok(token)
421    }
422
423    /// `FetchSelfProfile`: user name, user ID and org ID from `/v3/self` (empty unless
424    /// the answer is 200).
425    pub async fn fetch_self_profile(&self, session_token: &str) -> Result<(String, String, String), String> {
426        let mut h = self.headers();
427        h.set("Authorization", format!("Bearer {session_token}"));
428        h.set("Accept", "application/json");
429        let url = format!("{}/v3/self", self.api_base.trim_end_matches('/'));
430        let upstream = request(&self.client, wreq::Method::GET, &url, h, None, Some(LOGIN_TIMEOUT))
431            .await
432            .map_err(|e| lossy(&e.body))?;
433        let data = read_all(upstream.body, BODY_LIMIT, false)
434            .await
435            .map_err(|e| lossy(&e.body))?;
436        if upstream.status != 200 {
437            return Ok(Default::default());
438        }
439        let field = |p: &str| gj::get(&data, p).str().into_owned();
440        Ok((field("user_name"), field("user_id"), field("org_id")))
441    }
442
443    /// `FetchUserStatus`: `GetUserStatus` over Connect-RPC unary protobuf.
444    pub async fn fetch_user_status(&self, session_token: &str, device_seed: &str) -> Result<UserStatus, String> {
445        let token = session_token.trim();
446        if token.is_empty() {
447            return Err("devin auth service: session token is required".into());
448        }
449        let body = user_status_request(token, &device_fingerprint(device_seed));
450        let mut h = self.headers();
451        h.set("Authorization", format!("Basic {token}-{token}"));
452        h.set("Connect-Protocol-Version", "1");
453        h.set("Content-Type", "application/proto");
454        h.set("Accept", "*/*");
455        h.set("User-Agent", "");
456        let url = format!("{}{USER_STATUS_PATH}", self.server_base.trim_end_matches('/'));
457        let upstream = request(
458            &self.client,
459            wreq::Method::POST,
460            &url,
461            h,
462            Some(Bytes::from(body)),
463            Some(LOGIN_TIMEOUT),
464        )
465        .await
466        .map_err(|e| lossy(&e.body))?;
467        let data = read_all(upstream.body, STATUS_LIMIT, false)
468            .await
469            .map_err(|e| lossy(&e.body))?;
470        if upstream.status != 200 {
471            // Go appends the response body; it is withheld from logs and clients.
472            return Err(format!("devin seat management error (status {})", upstream.status));
473        }
474        parse_user_status(&data)
475    }
476
477    /// `CreateAuthRecord`: the credential for a session token. Profile and status are
478    /// best-effort; the file name never takes path components from upstream values.
479    pub async fn create_auth_record(&self, token: &str) -> Result<AuthRecord, String> {
480        let session_token = format_session_token(token);
481        if session_token.is_empty() {
482            return Err("devin session token is required".into());
483        }
484        let (mut user_name, mut user_id, mut org_id) = match self.fetch_self_profile(&session_token).await {
485            Ok(profile) => profile,
486            Err(_) => {
487                tracing::warn!("failed to fetch devin user profile");
488                Default::default()
489            }
490        };
491        let status = match self.fetch_user_status(&session_token, "").await {
492            Ok(status) => Some(status),
493            Err(_) => {
494                tracing::warn!("failed to fetch devin user status and quota");
495                None
496            }
497        };
498        let (mut email, mut plan) = (String::new(), String::new());
499        if let Some(s) = &status {
500            if user_name.is_empty() {
501                user_name.clone_from(&s.user_name);
502            }
503            if user_id.is_empty() {
504                user_id.clone_from(&s.user_id);
505            }
506            if org_id.is_empty() {
507                org_id.clone_from(&s.org_id);
508            }
509            email.clone_from(&s.email);
510            plan.clone_from(&s.plan);
511        }
512        let mut identifier = if user_name.is_empty() {
513            user_id.clone()
514        } else {
515            user_name.clone()
516        };
517        if identifier.is_empty() {
518            identifier = format!("user-{}", hex8(session_token.as_bytes()));
519        }
520        let safe: String = identifier
521            .chars()
522            .map(|c| {
523                if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '@') {
524                    c
525                } else {
526                    '_'
527                }
528            })
529            .collect();
530        let file_identifier = if safe != identifier || safe.len() > 160 {
531            format!("user-{}", hex8(identifier.as_bytes()))
532        } else {
533            safe
534        };
535        let file_name = format!("devin-{file_identifier}.json");
536        let label = if email.is_empty() {
537            format!("Devin ({identifier})")
538        } else {
539            format!("Devin ({identifier} - {email})")
540        };
541        let mut attributes = BTreeMap::new();
542        let mut metadata = Map::new();
543        metadata.insert("type".into(), "devin".into());
544        for (key, value) in [
545            ("api_key", &session_token),
546            ("session_token", &session_token),
547            ("user_name", &user_name),
548            ("user_id", &user_id),
549            ("org_id", &org_id),
550        ] {
551            attributes.insert(key.to_owned(), value.clone());
552            metadata.insert(key.into(), value.clone().into());
553        }
554        attributes.insert("base_url".into(), DEFAULT_SERVER_URL.into());
555        attributes.insert("auth_kind".into(), "oauth".into());
556        metadata.insert("auth_kind".into(), "oauth".into());
557        for (key, value) in [("email", &email), ("plan", &plan)] {
558            if !value.is_empty() {
559                attributes.insert(key.into(), value.clone());
560                metadata.insert(key.into(), value.clone().into());
561            }
562        }
563        let quota_signals = status
564            .as_ref()
565            .map(|s| s.quota_signals().into_iter().map(|(k, v)| (k.to_owned(), v)).collect())
566            .unwrap_or_else(|| {
567                let mut only_plan = BTreeMap::new();
568                if !plan.is_empty() {
569                    only_plan.insert("plan".to_owned(), plan.clone());
570                }
571                only_plan
572            });
573        Ok(AuthRecord {
574            file_name,
575            label,
576            attributes,
577            metadata,
578            quota_signals,
579        })
580    }
581}
582
583fn lossy(b: &[u8]) -> String {
584    String::from_utf8_lossy(b).into_owned()
585}
586
587/// `fmt.Sprintf("%x", sha256(b)[:8])`.
588fn hex8(b: &[u8]) -> String {
589    Sha256::digest(b)[..8].iter().map(|x| format!("{x:02x}")).collect()
590}
591
592/// Go `url.QueryEscape`.
593fn query_escape(s: &str) -> String {
594    let mut out = String::with_capacity(s.len());
595    for b in s.bytes() {
596        match b {
597            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
598            b' ' => out.push('+'),
599            _ => out.push_str(&format!("%{b:02X}")),
600        }
601    }
602    out
603}
604
605/// The credential a Devin login produces (Go's `*coreauth.Auth` from `CreateAuthRecord`).
606#[derive(Debug, Clone, PartialEq)]
607pub struct AuthRecord {
608    /// `devin-<identifier>.json`; also the credential ID.
609    pub file_name: String,
610    pub label: String,
611    pub attributes: BTreeMap<String, String>,
612    /// What the file store persists.
613    pub metadata: Map<String, Value>,
614    /// Initial quota observation (plan, daily and weekly remaining, resets).
615    pub quota_signals: BTreeMap<String, String>,
616}
617
618/// `Manager.Login` persistence for a Devin record (`FileTokenStore.Save`'s metadata
619/// branch): an existing file's settings are merged in (never its token payload), keys
620/// normalized, the weight validated, `disabled` stamped, then Go's compact JSON. An
621/// unchanged file is left alone. Returns the path.
622pub fn save_record(auth_dir: &Path, record: &AuthRecord) -> Result<PathBuf, String> {
623    save_metadata_file(auth_dir, &record.file_name, &record.metadata, "devin")
624}
625
626/// `Manager.Login` + `FileTokenStore.Save` (metadata branch) for any provider's login
627/// record: see [`save_record`]. Shared with the Antigravity login.
628pub(crate) fn save_metadata_file(
629    auth_dir: &Path,
630    file_name: &str,
631    metadata: &Map<String, Value>,
632    provider: &str,
633) -> Result<PathBuf, String> {
634    let path = auth_dir.join(file_name);
635    let mut metadata: GoMap = metadata
636        .iter()
637        .map(|(k, v)| (k.clone(), GoValue::from_json(v)))
638        .collect();
639    let mut disabled = false;
640    let existing = std::fs::read(&path).ok();
641    if let Some(raw) = existing.as_deref().filter(|r| !r.is_empty())
642        && let Some((map, true)) = go_map_from_json(raw)
643        && !map.is_empty()
644        && let Some(flag) = merge_existing(&mut metadata, &map, provider)
645    {
646        disabled = flag;
647    }
648    normalize_metadata(&mut metadata);
649    if let Some(weight) = metadata.get("weight") {
650        let json: Value = serde_json::from_slice(&weight.marshal()).unwrap_or(Value::Null);
651        cpa_core::config::credentials::parse_weight(&json)
652            .map_err(|e| format!("auth filestore: invalid metadata weight: {e}"))?;
653    }
654    metadata.insert("disabled".into(), GoValue::Bool(disabled));
655    let raw = GoValue::Object(metadata).marshal();
656    // jsonEqual: an existing file with the same content is not rewritten.
657    if let Some(old) = existing
658        && serde_json::from_slice::<Value>(&old).ok() == serde_json::from_slice::<Value>(&raw).ok()
659        && serde_json::from_slice::<Value>(&old).is_ok()
660    {
661        return Ok(path);
662    }
663    crate::kimi_auth::write_private(&path, &raw).map_err(|e| format!("auth filestore: write file failed: {e}"))?;
664    Ok(path)
665}
666
667/// A pasted value that is neither a code, a callback URL nor a token
668/// (`errDevinUnrecognizedPaste`).
669pub const UNRECOGNIZED_PASTE: &str = "unrecognized devin authorization code or token format";
670
671/// `parseDevinManualPaste`: `(code, token)` from a pasted authorization code, callback
672/// URL or session token. Empty input gives two empty values.
673pub fn parse_manual_paste(input: &str, expected_state: &str) -> Result<(String, String), String> {
674    let trimmed = input.trim().trim_matches(['"', '\'']).trim();
675    if trimmed.is_empty() {
676        return Ok(Default::default());
677    }
678    if trimmed.starts_with(TOKEN_PREFIX) || trimmed.starts_with("eyJ") {
679        return Ok((String::new(), trimmed.to_owned()));
680    }
681    if let Ok(Some(parsed)) = crate::claude_login::parse_callback_input(trimmed) {
682        let mut error = parsed.error.trim().to_owned();
683        if !error.is_empty() {
684            let description = parsed.description.trim();
685            if !description.is_empty() {
686                error = format!("{error}: {description}");
687            }
688            return Err(format!("devin oauth error: {error}"));
689        }
690        if !parsed.code.is_empty() {
691            if !expected_state.is_empty() && !parsed.state.is_empty() && parsed.state != expected_state {
692                return Err("devin oauth state mismatch (possible CSRF)".into());
693            }
694            return Ok((parsed.code, String::new()));
695        }
696    }
697    if !trimmed.contains([' ', '\t', '\r', '\n', '/', '?', '#', '=']) {
698        return Ok((trimmed.to_owned(), String::new()));
699    }
700    Err(UNRECOGNIZED_PASTE.into())
701}
702
703const LOGIN_SUCCESS_HTML: &str = r#"<!DOCTYPE html>
704<html lang="en">
705<head>
706    <meta charset="UTF-8">
707    <title>Authentication Successful - Devin</title>
708    <style>
709        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #0f172a; color: #f8fafc; }
710        .card { background: #1e293b; padding: 2.5rem; border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.4); text-align: center; max-width: 420px; }
711        h2 { margin-top: 0; color: #38bdf8; }
712        p { color: #94a3b8; font-size: 15px; }
713    </style>
714</head>
715<body>
716    <div class="card">
717        <h2>Authentication Complete</h2>
718        <p>You have successfully logged in to Devin via CLIProxyAPI.</p>
719        <p>You may safely close this window and return to your terminal.</p>
720    </div>
721</body>
722</html>"#;
723
724const LOGIN_FAILURE_HTML: &str = r#"<!DOCTYPE html>
725<html lang="en">
726<head>
727    <meta charset="UTF-8">
728    <title>Authentication Failed - Devin</title>
729    <style>
730        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #0f172a; color: #f8fafc; }
731        .card { background: #1e293b; padding: 2.5rem; border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.4); text-align: center; max-width: 420px; }
732        h2 { margin-top: 0; color: #f87171; }
733        p { color: #94a3b8; font-size: 15px; }
734    </style>
735</head>
736<body>
737    <div class="card">
738        <h2>Authentication Failed</h2>
739        <p>Devin authentication encountered an error: %s</p>
740        <p>Please check your terminal and try again.</p>
741    </div>
742</body>
743</html>"#;
744
745/// Go `html.EscapeString`.
746fn html_escape(s: &str) -> String {
747    let mut out = String::with_capacity(s.len());
748    for c in s.chars() {
749        match c {
750            '<' => out.push_str("&lt;"),
751            '>' => out.push_str("&gt;"),
752            '&' => out.push_str("&amp;"),
753            '\'' => out.push_str("&#39;"),
754            '"' => out.push_str("&#34;"),
755            c => out.push(c),
756        }
757    }
758    out
759}
760
761/// What the loopback `/callback` received (`OAuthResult`).
762#[derive(Debug, Clone, Default, PartialEq, Eq)]
763pub struct CallbackResult {
764    pub code: String,
765    pub state: String,
766    pub error: String,
767}
768
769/// `OAuthServer.handleCallback`: the HTTP status, page and result for a callback query.
770pub(crate) fn callback_response(query: &str) -> (u16, String, CallbackResult) {
771    let get = |name: &str| {
772        url::form_urlencoded::parse(query.as_bytes())
773            .find(|(k, _)| k == name)
774            .map(|(_, v)| v.trim().to_owned())
775            .unwrap_or_default()
776    };
777    let (code, state, error, description) = (get("code"), get("state"), get("error"), get("error_description"));
778    if !error.is_empty() || code.is_empty() {
779        let mut message = error.clone();
780        if !description.is_empty() {
781            message = format!("{error}: {description}");
782        }
783        if message.is_empty() {
784            message = "missing authorization code".into();
785        }
786        let page = LOGIN_FAILURE_HTML.replacen("%s", &html_escape(&message), 1);
787        return (
788            400,
789            page,
790            CallbackResult {
791                error: message,
792                ..Default::default()
793            },
794        );
795    }
796    (
797        200,
798        LOGIN_SUCCESS_HTML.to_owned(),
799        CallbackResult {
800            code,
801            state,
802            error: String::new(),
803        },
804    )
805}
806
807/// Go's `OAuthServer` on `127.0.0.1:<port>`: answers `/callback`, 404 elsewhere, and
808/// sends the first result to `results`.
809async fn serve_callbacks(listener: tokio::net::TcpListener, results: tokio::sync::mpsc::Sender<CallbackResult>) {
810    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
811    loop {
812        let Ok((socket, _)) = listener.accept().await else {
813            continue;
814        };
815        let results = results.clone();
816        tokio::spawn(async move {
817            let work = async move {
818                let (read, mut write) = socket.into_split();
819                let mut reader = BufReader::new(read);
820                let mut line = String::new();
821                reader.read_line(&mut line).await.ok()?;
822                let target = line.split_whitespace().nth(1)?.to_owned();
823                loop {
824                    let mut header = String::new();
825                    if reader.read_line(&mut header).await.ok()? == 0 || header.trim().is_empty() {
826                        break;
827                    }
828                }
829                let (path, query) = target.split_once('?').unwrap_or((&target, ""));
830                let (status, page) = if path == "/callback" {
831                    let (status, page, result) = callback_response(query);
832                    let _ = results.try_send(result);
833                    (status, page)
834                } else {
835                    (404, "404 page not found\n".to_owned())
836                };
837                let reason = if status == 200 {
838                    "OK"
839                } else if status == 400 {
840                    "Bad Request"
841                } else {
842                    "Not Found"
843                };
844                let content_type = if status == 404 {
845                    "text/plain; charset=utf-8"
846                } else {
847                    "text/html; charset=utf-8"
848                };
849                let response = format!(
850                    "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{page}",
851                    page.len()
852                );
853                write.write_all(response.as_bytes()).await.ok()
854            };
855            let _ = tokio::time::timeout(Duration::from_secs(10), work).await;
856        });
857    }
858}
859
860/// One prompt read on a detached thread (`misc.AsyncPrompt`).
861async fn prompt(message: &'static str) -> std::io::Result<String> {
862    let (tx, rx) = tokio::sync::oneshot::channel();
863    std::thread::spawn(move || {
864        use std::io::Write;
865        print!("{message}");
866        let _ = std::io::stdout().flush();
867        let mut line = String::new();
868        let read = std::io::stdin().read_line(&mut line).map(|_| line);
869        let _ = tx.send(read);
870    });
871    rx.await
872        .unwrap_or_else(|_| Err(std::io::Error::other("prompt thread ended")))
873}
874
875/// `DevinAuthenticator.Login`: the session token from a browser callback, a pasted
876/// callback URL or code, or a pasted token; then the auth record.
877pub(crate) async fn login_with(auth: &DevinAuth, no_browser: bool, callback_port: u16) -> Result<AuthRecord, String> {
878    let pkce = generate_pkce().map_err(|e| format!("devin pkce generation failed: {e}"))?;
879    let state = random_state().map_err(|e| format!("devin state generation failed: {e}"))?;
880    let (code, token) = if no_browser {
881        let url = auth.build_authorization_url("", &pkce.challenge, &state);
882        print!("Visit the following URL to continue Devin authentication:\n{url}\n\n");
883        let input = prompt("Paste the Devin authorization code or session token directly: ")
884            .await
885            .map_err(|e| format!("failed to read devin input: {e}"))?;
886        let (code, token) = parse_manual_paste(&input, &state)?;
887        if code.is_empty() && token.is_empty() {
888            return Err("devin authentication canceled: empty input received".into());
889        }
890        (code, token)
891    } else {
892        browser_callback(auth, &pkce, &state, callback_port).await?
893    };
894    let session_token = if !token.is_empty() {
895        format_session_token(&token)
896    } else if !code.is_empty() {
897        let token = auth
898            .exchange_code(&code, &pkce.verifier)
899            .await
900            .map_err(|e| format!("failed to exchange devin authorization code: {e}"))?;
901        format_session_token(&token)
902    } else {
903        return Err("no authorization code or token received".into());
904    };
905    auth.create_auth_record(&session_token).await
906}
907
908/// The browser half of `Login`: a loopback callback, with a manual paste offered after
909/// five seconds and a five-minute limit.
910async fn browser_callback(auth: &DevinAuth, pkce: &Pkce, state: &str, port: u16) -> Result<(String, String), String> {
911    let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.map_err(|e| {
912        format!(
913            "failed to start devin oauth callback server: failed to bind local OAuth server to 127.0.0.1:{port}: {e}"
914        )
915    })?;
916    let actual = listener.local_addr().map(|a| a.port()).unwrap_or(port);
917    let (tx, mut rx) = tokio::sync::mpsc::channel(1);
918    let server = tokio::spawn(serve_callbacks(listener, tx));
919    let _stop = AbortOnDrop(server);
920    let redirect = format!("http://127.0.0.1:{actual}/callback");
921    let url = auth.build_authorization_url(&redirect, &pkce.challenge, state);
922    println!("Opening browser for Devin authentication...");
923    if !crate::kimi_auth::open_browser(&url) {
924        tracing::warn!("No browser available; please open the URL manually");
925        crate::claude_login::print_ssh_tunnel_instructions(actual);
926        println!("Visit the following URL to continue authentication:\n{url}");
927    }
928    println!("Waiting for Devin authentication callback...");
929    let deadline = tokio::time::sleep(Duration::from_secs(5 * 60));
930    tokio::pin!(deadline);
931    let manual_delay = tokio::time::sleep(Duration::from_secs(5));
932    tokio::pin!(manual_delay);
933    let mut delay_done = false;
934    let mut manual: Option<std::pin::Pin<Box<dyn std::future::Future<Output = std::io::Result<String>> + Send>>> = None;
935    let accept = |result: CallbackResult| -> Result<(String, String), String> {
936        if !result.error.is_empty() {
937            return Err(format!("devin oauth error: {}", result.error));
938        }
939        if !state.is_empty() && result.state != state {
940            return Err("devin oauth state mismatch (possible CSRF)".into());
941        }
942        Ok((result.code, String::new()))
943    };
944    loop {
945        tokio::select! {
946            Some(result) = rx.recv() => return accept(result),
947            () = &mut deadline => {
948                return Err("devin oauth callback failed: devin authentication timed out".into());
949            }
950            () = &mut manual_delay, if !delay_done => {
951                delay_done = true;
952                if let Ok(result) = rx.try_recv() {
953                    return accept(result);
954                }
955                manual = Some(Box::pin(prompt(
956                    "Paste the Devin callback URL, authorization code, or session token directly (or press Enter to keep waiting): ",
957                )));
958            }
959            input = async { manual.as_mut().expect("guarded").await }, if manual.is_some() => {
960                manual = None;
961                let Ok(input) = input else {
962                    continue;
963                };
964                match parse_manual_paste(&input, state) {
965                    Err(e) if e == UNRECOGNIZED_PASTE => continue,
966                    Err(e) => return Err(e),
967                    Ok((code, token)) if !token.is_empty() || !code.is_empty() => return Ok((code, token)),
968                    Ok(_) => {}
969                }
970            }
971        }
972    }
973}
974
975struct AbortOnDrop(tokio::task::JoinHandle<()>);
976
977impl Drop for AbortOnDrop {
978    fn drop(&mut self) {
979        self.0.abort();
980    }
981}
982
983/// `--devin-login` (`DoDevinLogin`): browser or headless login through
984/// `requests.proxy-url`, then the credential in `auth-dir`. Failures are logged and the
985/// command still exits normally, as in Go.
986pub async fn login(cfg: &cpa_core::config::Config, no_browser: bool, callback_port: u16) -> Option<PathBuf> {
987    let proxy = cfg
988        .document
989        .get("requests")
990        .and_then(|r| r.get("proxy-url"))
991        .and_then(|v| v.as_str())
992        .unwrap_or_default();
993    let client = crate::proxy::GoClients::new(crate::proxy::Hooks::default()).get(&crate::proxy::Proxy::parse(proxy));
994    let auth = DevinAuth::new(client);
995    let record = match login_with(&auth, no_browser, callback_port).await {
996        Ok(record) => record,
997        Err(e) => {
998            tracing::error!("Devin authentication failed: {e}");
999            return None;
1000        }
1001    };
1002    let auth_dir = cfg.auth_dir.clone();
1003    let saved = {
1004        let record = record.clone();
1005        tokio::task::spawn_blocking(move || save_record(&auth_dir, &record))
1006            .await
1007            .map_err(|_| "credential publication failed".to_owned())
1008            .and_then(|r| r)
1009    };
1010    let path = match saved {
1011        Ok(path) => path,
1012        Err(e) => {
1013            tracing::error!("Devin authentication failed: {e}");
1014            return None;
1015        }
1016    };
1017    println!("Authentication saved to {}", path.display());
1018    if !record.label.is_empty() {
1019        println!("Authenticated as {}", record.label);
1020    }
1021    println!("Devin authentication successful!");
1022    Some(path)
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027    use super::*;
1028
1029    #[test]
1030    fn pkce_challenge_is_s256_of_the_verifier() {
1031        let pkce = generate_pkce().unwrap();
1032        assert_eq!(pkce.verifier.len(), 86, "64 bytes, base64url without padding");
1033        assert_eq!(
1034            pkce.challenge,
1035            URL_SAFE_NO_PAD.encode(Sha256::digest(pkce.verifier.as_bytes()))
1036        );
1037    }
1038
1039    #[test]
1040    fn callback_page_escapes_the_error() {
1041        let (status, page, result) = callback_response("error=a%3Cb&error_description=x%26y");
1042        assert_eq!(status, 400);
1043        assert_eq!(result.error, "a<b: x&y");
1044        assert!(page.contains("encountered an error: a&lt;b: x&amp;y</p>"));
1045        let (status, _, result) = callback_response("state=s");
1046        assert_eq!((status, result.error.as_str()), (400, "missing authorization code"));
1047        let (status, page, result) = callback_response("code=%20c%20&state=s");
1048        assert_eq!((status, result.code.as_str(), result.state.as_str()), (200, "c", "s"));
1049        assert_eq!(page, LOGIN_SUCCESS_HTML);
1050    }
1051}