link-assistant-router 0.43.0

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Login sessions that authorize a deployment without a pre-existing
//! credential file.
//!
//! The router can only *read* Claude Code credentials ([`crate::oauth`]), so a
//! fresh container has nothing to read and no way to produce it: the Claude
//! Code login is interactive, and the machine that would run it is not the
//! machine the router runs on (issue #47).
//!
//! This module closes that gap by driving Claude Code on a PTY and conducting
//! Codex device authorization directly. It exposes the irreducibly human step
//! — approving a URL in a browser — through provider-aware HTTP sessions:
//!
//! 1. [`LoginManager::begin`] starts the provider flow and returns its URL with
//!    a `login_id` (and, for Codex, a one-time device code).
//! 2. The human opens the URL and approves. Claude's code is submitted through
//!    [`LoginManager::submit_code`]; Codex is completed by background polling.
//! 3. The resulting credential is persisted in that provider's own home.
//!
//! # Why the session outlives the request
//!
//! Between steps 1 and 3 the router is waiting on a human — tens of seconds at
//! best, minutes realistically, possibly on another device. Re-spawning the
//! CLI is not an option, because a second run prints a *different* URL and the
//! code the user is holding no longer matches. So the child process, its PTY,
//! and its terminal state are owned by a registry entry keyed by `login_id`,
//! with their own generous TTL that is independent of any HTTP timeout.
//!
//! Sessions are bounded in both directions: at most
//! [`LoginConfig::max_sessions`] may be pending at once (so repeated `begin`
//! calls cannot spawn unbounded CLI processes), and every session is killed on
//! success, on expiry, or on [`LoginManager::cancel`].

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use chrono::{DateTime, Utc};
use portable_pty::CommandBuilder;
use serde::Serialize;

use crate::login_pty::{Key, PtySession, WaitError};
use crate::login_url::{extract_login_url, extract_token};
use crate::subscription::{SubscriptionProvider, SubscriptionReader};

/// Markers that mean the CLI accepted the code and finished.
const SUCCESS_MARKERS: &[&str] = &["Loginsuccessful", "successfullyauthenticated", "sk-ant-oat"];
/// Markers that mean the CLI rejected the code.
const FAILURE_MARKERS: &[&str] = &[
    "OAutherror",
    "PressEntertoretry",
    "Invalidcode",
    "invalid_grant",
    "Authenticationfailed",
    "Loginfailed",
];

/// Stable text on the first-run screens that block the Claude Code prompt.
///
/// Each marker names the screen whose currently selected safe/default action
/// is accepted with Enter. Unknown screens are deliberately left untouched so
/// a changed onboarding flow times out loudly instead of receiving blind input.
const THEME_PICKER_MARKER: &str = "Choosethetextstylethatlooksbestwithyourterminal";
const WORKSPACE_TRUST_MARKER: &str = "Quicksafetycheck:Isthisaprojectyoucreated";
const LOGIN_METHOD_MARKER: &str = "Selectloginmethod:";
const READY_PROMPT_MARKER: &str = "Tipsforgettingstarted";

/// Settings for the login flow.
#[derive(Clone, Debug)]
pub struct LoginConfig {
    /// Whether the login endpoints are served at all.
    pub enabled: bool,
    /// Program to drive, e.g. `claude`.
    pub command: String,
    /// Arguments passed to that program. Empty selects the default TUI
    /// `/login` flow; `["setup-token"]` selects the narrow-scope alternative.
    pub args: Vec<String>,
    /// Directory the resulting credential must land in. This is the same
    /// directory [`crate::oauth::OAuthProvider`] reads.
    pub claude_code_home: PathBuf,
    /// Directory where Codex credentials are written.
    pub codex_home: PathBuf,
    /// Codex OAuth issuer. Overridable for compatible deployments and tests.
    pub codex_issuer: String,
    /// Loopback callback port registered for the Codex OAuth client.
    pub codex_callback_port: u16,
    /// How long a pending session stays valid while waiting for the human.
    pub session_ttl: Duration,
    /// Maximum number of simultaneously pending sessions.
    pub max_sessions: usize,
    /// How long the terminal must be quiet before its output is considered a
    /// settled frame rather than a mid-repaint one.
    pub idle_settle: Duration,
    /// How long to wait for the authorization URL to appear.
    pub url_timeout: Duration,
    /// How long to wait for the CLI to react to a submitted code.
    pub code_timeout: Duration,
}

impl Default for LoginConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            command: "claude".to_string(),
            args: vec![],
            claude_code_home: PathBuf::from("/data/claude"),
            codex_home: PathBuf::from("/data/codex"),
            codex_issuer: crate::auth::CODEX_ISSUER.to_string(),
            codex_callback_port: 1455,
            session_ttl: Duration::from_secs(900),
            max_sessions: 4,
            idle_settle: Duration::from_millis(750),
            url_timeout: Duration::from_secs(60),
            code_timeout: Duration::from_secs(120),
        }
    }
}

/// Lifecycle state of a login session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LoginStatus {
    /// The URL was returned; the router is waiting for the human's code.
    AwaitingCode,
    /// The URL was returned; a provider-owned loopback listener awaits OAuth.
    AwaitingCallback,
    /// A provider-issued user code is waiting for browser approval.
    AwaitingDevice,
    /// A credential is now readable by the router.
    Authorized,
    /// The flow ended without a credential; restarting is required.
    Failed,
    /// The human did not come back before the TTL elapsed.
    Expired,
}

/// Public view of a login session.
#[derive(Clone, Debug, Serialize)]
pub struct LoginView {
    /// Identifier used to address this session.
    pub login_id: String,
    /// Subscription provider being authorized.
    pub provider: SubscriptionProvider,
    /// Current lifecycle state.
    pub status: LoginStatus,
    /// Authorization URL the human must open. Present while pending.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// One-time code entered at `url` for a device authorization.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_code: Option<String>,
    /// When this *session* stops accepting a code.
    pub session_expires_at: DateTime<Utc>,
    /// When the obtained *credential* expires, when the CLI reports it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<i64>,
    /// Human-readable failure reason.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Why a login operation could not be carried out.
#[derive(Debug)]
pub enum LoginError {
    /// The login API is switched off.
    Disabled,
    /// `max_sessions` pending logins already exist.
    TooManySessions(usize),
    /// No session with that id (it may have been cleaned up).
    NotFound,
    /// The session exists but no longer accepts a code.
    NotPending(LoginStatus),
    /// The CLI could not be started.
    Spawn(String),
    /// The CLI started but never produced an authorization URL.
    NoUrl(String),
    /// The credential directory is unusable.
    Storage(String),
}

impl std::fmt::Display for LoginError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Disabled => write!(f, "the login API is disabled"),
            Self::TooManySessions(max) => {
                write!(f, "too many pending logins (limit {max}); cancel one first")
            }
            Self::NotFound => write!(f, "unknown login_id"),
            Self::NotPending(status) => {
                write!(f, "login is not awaiting a code (status: {status:?})")
            }
            Self::Spawn(msg) => write!(f, "could not start the login flow: {msg}"),
            Self::NoUrl(msg) => write!(f, "no authorization URL appeared: {msg}"),
            Self::Storage(msg) => write!(f, "credential directory is unusable: {msg}"),
        }
    }
}

impl std::error::Error for LoginError {}

/// One pending or finished login.
struct Session {
    id: String,
    provider: SubscriptionProvider,
    url: String,
    user_code: Option<String>,
    deadline: DateTime<Utc>,
    state: Mutex<SessionState>,
}

/// Mutable part of a [`Session`].
struct SessionState {
    status: LoginStatus,
    expires_at: Option<i64>,
    error: Option<String>,
    /// Dropped (and thus killed) as soon as the session stops being pending.
    pty: Option<Arc<PtySession>>,
    /// Provider authorization task; aborting it stops polling or the listener.
    auth_task: Option<tokio::task::JoinHandle<()>>,
    /// When the session reached a terminal state, which starts the clock on
    /// [`TERMINAL_RETENTION`].
    settled_at: Option<DateTime<Utc>>,
}

impl Session {
    fn view(&self) -> LoginView {
        let state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        LoginView {
            login_id: self.id.clone(),
            provider: self.provider,
            status: state.status.clone(),
            url: matches!(
                state.status,
                LoginStatus::AwaitingCode
                    | LoginStatus::AwaitingCallback
                    | LoginStatus::AwaitingDevice
            )
            .then(|| self.url.clone()),
            user_code: (state.status == LoginStatus::AwaitingDevice)
                .then(|| self.user_code.clone())
                .flatten(),
            session_expires_at: self.deadline,
            expires_at: state.expires_at,
            error: state.error.clone(),
        }
    }
}

/// How long a finished session is kept so its outcome can still be polled.
///
/// Long enough that a client which just submitted a code can read the verdict
/// even over a slow link; short enough that the registry cannot be grown into a
/// memory problem by repeated logins.
const TERMINAL_RETENTION_SECS: i64 = 300;

const fn terminal_retention() -> chrono::Duration {
    chrono::Duration::seconds(TERMINAL_RETENTION_SECS)
}

/// Registry of live login sessions.
#[derive(Clone)]
pub struct LoginManager {
    config: Arc<LoginConfig>,
    sessions: Arc<Mutex<HashMap<String, Arc<Session>>>>,
}

impl LoginManager {
    /// Create a manager for the given configuration.
    #[must_use]
    pub fn new(config: LoginConfig) -> Self {
        Self {
            config: Arc::new(config),
            sessions: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// The configuration this manager was built with.
    #[must_use]
    pub fn config(&self) -> &LoginConfig {
        &self.config
    }

    /// Whether the login API is enabled.
    #[must_use]
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Start a login: spawn the CLI, wait for its authorization URL, and
    /// register the still-running session so a later request can finish it.
    pub async fn begin(&self) -> Result<LoginView, LoginError> {
        self.begin_for(SubscriptionProvider::Claude).await
    }

    /// Start the authorization flow supported by `provider`.
    pub async fn begin_for(&self, provider: SubscriptionProvider) -> Result<LoginView, LoginError> {
        if !self.config.enabled {
            return Err(LoginError::Disabled);
        }
        self.sweep();
        let pending = self.count_pending();
        if pending >= self.config.max_sessions {
            return Err(LoginError::TooManySessions(self.config.max_sessions));
        }
        if provider == SubscriptionProvider::Codex {
            return self.begin_codex().await;
        }
        if provider != SubscriptionProvider::Claude {
            return Err(LoginError::Spawn(format!(
                "{provider} authorization is not implemented; supported providers: claude, codex"
            )));
        }
        ensure_writable_dir(&self.config.claude_code_home)?;

        let config = Arc::clone(&self.config);
        let (pty, url) = tokio::task::spawn_blocking(move || spawn_and_wait_for_url(&config))
            .await
            .map_err(|e| LoginError::Spawn(e.to_string()))??;

        let id = uuid::Uuid::new_v4().to_string();
        let session = Arc::new(Session {
            id: id.clone(),
            provider,
            url,
            user_code: None,
            deadline: Utc::now()
                + chrono::Duration::from_std(self.config.session_ttl)
                    .unwrap_or_else(|_| chrono::Duration::seconds(900)),
            state: Mutex::new(SessionState {
                status: LoginStatus::AwaitingCode,
                expires_at: None,
                error: None,
                pty: Some(pty),
                auth_task: None,
                settled_at: None,
            }),
        });
        self.lock_sessions().insert(id, Arc::clone(&session));
        Ok(session.view())
    }

    async fn begin_codex(&self) -> Result<LoginView, LoginError> {
        let codex_home = self.config.codex_home.clone();
        ensure_writable_dir(&codex_home)?;
        let mut codex_config = crate::auth::CodexAuthConfig::production(
            codex_home,
            self.config.codex_callback_port,
            self.config.session_ttl,
        );
        codex_config.issuer.clone_from(&self.config.codex_issuer);
        let login = crate::auth::CodexDeviceLogin::begin(codex_config)
            .await
            .map_err(LoginError::Spawn)?;
        let id = uuid::Uuid::new_v4().to_string();
        let session = Arc::new(Session {
            id: id.clone(),
            provider: SubscriptionProvider::Codex,
            url: login.verification_url().to_string(),
            user_code: Some(login.user_code().to_string()),
            deadline: Utc::now()
                + chrono::Duration::from_std(self.config.session_ttl)
                    .unwrap_or_else(|_| chrono::Duration::seconds(900)),
            state: Mutex::new(SessionState {
                status: LoginStatus::AwaitingDevice,
                expires_at: None,
                error: None,
                pty: None,
                auth_task: None,
                settled_at: None,
            }),
        });
        self.lock_sessions().insert(id, Arc::clone(&session));
        let task_session = Arc::clone(&session);
        let task = tokio::spawn(async move {
            let outcome = login.complete().await;
            let mut state = task_session
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            match outcome {
                Ok(_) => {
                    state.status = LoginStatus::Authorized;
                    state.error = None;
                }
                Err(error) => {
                    state.status = if Utc::now() >= task_session.deadline {
                        LoginStatus::Expired
                    } else {
                        LoginStatus::Failed
                    };
                    state.error = Some(error);
                }
            }
            state.settled_at = Some(Utc::now());
        });
        session
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .auth_task = Some(task);
        Ok(session.view())
    }

    /// Look up a session's current state.
    #[must_use]
    pub fn status(&self, id: &str) -> Option<LoginView> {
        self.sweep();
        let session = self.lock_sessions().get(id).map(Arc::clone)?;
        Some(session.view())
    }

    /// Feed the human's authorization code to the session's live PTY.
    pub async fn submit_code(&self, id: &str, code: &str) -> Result<LoginView, LoginError> {
        if !self.config.enabled {
            return Err(LoginError::Disabled);
        }
        self.sweep();
        let session = self
            .lock_sessions()
            .get(id)
            .map(Arc::clone)
            .ok_or(LoginError::NotFound)?;

        let pty = {
            let state = session
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if state.status != LoginStatus::AwaitingCode {
                return Err(LoginError::NotPending(state.status.clone()));
            }
            state.pty.clone().ok_or(LoginError::NotFound)?
        };

        let config = Arc::clone(&self.config);
        let code = code.trim().to_string();
        let outcome =
            tokio::task::spawn_blocking(move || submit_and_finalize(&config, &pty, &code))
                .await
                .map_err(|e| LoginError::Spawn(e.to_string()))?;

        Self::finish(&session, outcome);
        Ok(session.view())
    }

    /// Terminate a session and forget it. Returns whether it existed.
    #[must_use]
    pub fn cancel(&self, id: &str) -> bool {
        self.lock_sessions().remove(id).is_some_and(|session| {
            Self::release(&session);
            true
        })
    }

    /// Number of sessions still waiting for a code.
    #[must_use]
    pub fn pending_count(&self) -> usize {
        self.sweep();
        self.count_pending()
    }

    /// Expire sessions whose TTL elapsed, killing their processes, and forget
    /// finished ones once their result has had time to be collected.
    ///
    /// Without the first half, an abandoned login would leak one CLI process
    /// per attempt, indefinitely. Without the second, the registry itself would
    /// grow without bound: a finished session releases its PTY but its map
    /// entry used to live as long as the process, so anyone who could call
    /// `begin` repeatedly could grow the map for the lifetime of the router.
    pub fn sweep(&self) {
        let now = Utc::now();
        let sessions: Vec<Arc<Session>> = self.lock_sessions().values().map(Arc::clone).collect();
        let mut evict = Vec::new();
        for session in sessions {
            let mut state = session
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let expired = matches!(
                state.status,
                LoginStatus::AwaitingCode
                    | LoginStatus::AwaitingCallback
                    | LoginStatus::AwaitingDevice
            ) && session.deadline <= now;
            if expired {
                state.status = LoginStatus::Expired;
                state.error = Some("login session expired before authorization completed".into());
                state.pty = None; // dropping the PTY kills the child
                if let Some(task) = state.auth_task.take() {
                    task.abort();
                }
                state.settled_at = Some(now);
            } else if state
                .settled_at
                .is_some_and(|at| now - at >= terminal_retention())
            {
                evict.push(session.id.clone());
            }
            drop(state);
            if expired {
                tracing::info!("login session {} expired", session.id);
            }
        }
        if !evict.is_empty() {
            let mut sessions = self.lock_sessions();
            for id in evict {
                sessions.remove(&id);
            }
        }
    }

    fn finish(session: &Arc<Session>, outcome: Outcome) {
        let mut state = session
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        match outcome {
            Outcome::Authorized { expires_at } => {
                state.status = LoginStatus::Authorized;
                state.expires_at = expires_at;
                state.error = None;
            }
            Outcome::Failed(error) => {
                state.status = LoginStatus::Failed;
                state.error = Some(error);
            }
        }
        state.pty = None;
        state.auth_task = None;
        state.settled_at = Some(Utc::now());
    }

    fn release(session: &Arc<Session>) {
        let mut state = session
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.pty = None;
        if let Some(task) = state.auth_task.take() {
            task.abort();
        }
        if matches!(
            state.status,
            LoginStatus::AwaitingCode | LoginStatus::AwaitingCallback | LoginStatus::AwaitingDevice
        ) {
            state.status = LoginStatus::Failed;
            state.error = Some("login session cancelled".into());
        }
    }

    fn count_pending(&self) -> usize {
        self.lock_sessions()
            .values()
            .filter(|session| {
                let status = session
                    .state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .status
                    .clone();
                matches!(
                    status,
                    LoginStatus::AwaitingCode
                        | LoginStatus::AwaitingCallback
                        | LoginStatus::AwaitingDevice
                )
            })
            .count()
    }

    fn lock_sessions(&self) -> std::sync::MutexGuard<'_, HashMap<String, Arc<Session>>> {
        self.sessions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

/// Result of feeding a code to the CLI.
enum Outcome {
    Authorized { expires_at: Option<i64> },
    Failed(String),
}

/// Spawn the login CLI and block until its authorization URL has settled.
fn spawn_and_wait_for_url(config: &LoginConfig) -> Result<(Arc<PtySession>, String), LoginError> {
    let mut command = CommandBuilder::new(&config.command);
    for arg in &config.args {
        command.arg(arg);
    }
    // The CLI decides where to write credentials from its environment, so it
    // is pointed at exactly the directory the router reads.
    command.env("CLAUDE_CONFIG_DIR", &config.claude_code_home);
    if let Some(parent) = config.claude_code_home.parent() {
        command.env("HOME", parent);
    }
    command.env("TERM", "xterm-256color");
    if let Ok(path) = std::env::var("PATH") {
        command.env("PATH", path);
    }

    let session =
        Arc::new(PtySession::spawn(command).map_err(|e| LoginError::Spawn(e.to_string()))?);
    let result = if config.args.is_empty() {
        drive_tui_to_login_url(&session, config)
    } else {
        wait_for_login_url(&session, config)
    };
    match result {
        Ok(url) => Ok((session, url)),
        Err(detail) => {
            session.kill();
            Err(LoginError::NoUrl(detail))
        }
    }
}

/// Progress through the known TUI screens without re-reacting to old text in
/// the append-only PTY transcript.
#[derive(Default)]
struct TuiProgress {
    completed: Vec<TuiAction>,
}

impl TuiProgress {
    fn needs(&self, action: TuiAction) -> bool {
        !self.completed.contains(&action)
    }

    fn complete(&mut self, action: TuiAction) {
        self.completed.push(action);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TuiAction {
    AcceptTheme,
    AcceptWorkspaceTrust,
    SendLogin,
    SelectLoginMethod,
}

fn next_tui_action(text: &str, progress: &TuiProgress) -> Option<TuiAction> {
    // Ink-based TUIs position words with cursor escapes instead of printing
    // literal spaces. `strip_ansi` intentionally removes those escapes, so a
    // rendered "Select login method:" may arrive as "Selectloginmethod:".
    let compact = compact_terminal_text(text);
    if progress.needs(TuiAction::AcceptTheme) && compact.contains(THEME_PICKER_MARKER) {
        Some(TuiAction::AcceptTheme)
    } else if progress.needs(TuiAction::AcceptWorkspaceTrust)
        && compact.contains(WORKSPACE_TRUST_MARKER)
    {
        Some(TuiAction::AcceptWorkspaceTrust)
    } else if progress.needs(TuiAction::SendLogin) && compact.contains(READY_PROMPT_MARKER) {
        Some(TuiAction::SendLogin)
    } else if progress.needs(TuiAction::SelectLoginMethod) && compact.contains(LOGIN_METHOD_MARKER)
    {
        Some(TuiAction::SelectLoginMethod)
    } else {
        None
    }
}

/// Match terminal text independently of whether a TUI printed spaces or used
/// cursor-positioning escapes that disappeared during ANSI stripping.
fn compact_terminal_text(text: &str) -> String {
    text.chars().filter(|ch| !ch.is_whitespace()).collect()
}

fn contains_marker(compact: &str, markers: &[&str]) -> bool {
    markers.iter().any(|marker| compact.contains(marker))
}

/// Drive bare `claude` to the full-scope OAuth URL exposed by its `/login`
/// command. The one timeout covers the whole startup sequence, not each screen.
fn drive_tui_to_login_url(session: &PtySession, config: &LoginConfig) -> Result<String, String> {
    let deadline = Instant::now() + config.url_timeout;
    let mut progress = TuiProgress::default();
    loop {
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Err(format!(
                "timed out; last output: {}",
                session.transcript_tail(400)
            ));
        }
        let text = session
            .wait_for(
                |text| {
                    extract_login_url(text).is_some() || next_tui_action(text, &progress).is_some()
                },
                config.idle_settle,
                remaining,
            )
            .map_err(|err| wait_error_detail(session, &err))?;
        if let Some(url) = extract_login_url(&text) {
            return Ok(url);
        }
        let action = next_tui_action(&text, &progress);
        match action {
            Some(TuiAction::AcceptTheme) => {
                session
                    .send_key(Key::Enter)
                    .map_err(|e| format!("could not accept the Claude Code theme screen: {e}"))?;
            }
            Some(TuiAction::AcceptWorkspaceTrust) => {
                session.send_key(Key::Enter).map_err(|e| {
                    format!("could not accept the Claude Code workspace trust screen: {e}")
                })?;
            }
            Some(TuiAction::SendLogin) => {
                session
                    .send_text("/login")
                    .and_then(|()| session.send_key(Key::Enter))
                    .map_err(|e| format!("could not type /login at the Claude Code prompt: {e}"))?;
            }
            Some(TuiAction::SelectLoginMethod) => {
                session.send_key(Key::Enter).map_err(|e| {
                    format!("could not select the Claude subscription login method: {e}")
                })?;
            }
            None => {
                return Err(format!(
                    "Claude Code reached an unrecognized screen; last output: {}",
                    session.transcript_tail(400)
                ));
            }
        }
        if let Some(action) = action {
            progress.complete(action);
        }
    }
}

/// Preserve the existing custom-argument behaviour: wait for whichever login
/// URL the configured command prints without sending TUI input first.
fn wait_for_login_url(session: &PtySession, config: &LoginConfig) -> Result<String, String> {
    let text = session
        .wait_for(
            |text| extract_login_url(text).is_some(),
            config.idle_settle,
            config.url_timeout,
        )
        .map_err(|err| wait_error_detail(session, &err))?;
    extract_login_url(&text).ok_or_else(|| {
        format!(
            "authorization URL disappeared; last output: {}",
            session.transcript_tail(400)
        )
    })
}

fn wait_error_detail(session: &PtySession, err: &WaitError) -> String {
    match err {
        WaitError::Timeout => format!("timed out; last output: {}", session.transcript_tail(400)),
        WaitError::ChildExited(_) => {
            format!("{err}; last output: {}", session.transcript_tail(400))
        }
    }
}

/// Type the code into the live session and decide what happened.
fn submit_and_finalize(config: &LoginConfig, pty: &PtySession, code: &str) -> Outcome {
    // The default flow is an Ink TUI. A real terminal wraps pasted text so the
    // controlled input receives it as one transaction instead of racing its
    // repaint one keypress at a time. Preserve raw input for the explicit
    // `setup-token` alternative, whose line reader does not enable this mode.
    let send_result = if config.args.is_empty() {
        pty.send_bracketed_paste(code)
    } else {
        pty.send_text(code)
    };
    if let Err(e) = send_result {
        return Outcome::Failed(format!("could not send the code to the login process: {e}"));
    }
    if let Err(e) = pty.wait_idle(config.idle_settle, config.code_timeout) {
        return Outcome::Failed(format!(
            "login timed out while waiting for the pasted authorization code to settle: {e}"
        ));
    }
    if let Err(e) = pty.send_key(Key::Enter) {
        return Outcome::Failed(format!("could not submit the authorization code: {e}"));
    }

    // Either the CLI prints a verdict, or it simply exits. Both are handled;
    // the authoritative check is whether a credential exists afterwards.
    let verdict = pty.wait_for(
        |text| {
            let compact = compact_terminal_text(text);
            contains_marker(&compact, SUCCESS_MARKERS) || contains_marker(&compact, FAILURE_MARKERS)
        },
        config.idle_settle,
        config.code_timeout,
    );
    if !pty.is_running() {
        let _ = pty.wait_for_exit(Duration::from_secs(1));
    }

    let transcript = pty.transcript();
    if let Some(credential) = read_credential(&config.claude_code_home) {
        return Outcome::Authorized {
            expires_at: credential.expires_at,
        };
    }
    // `claude setup-token` prints a long-lived token instead of writing a
    // credential file. Persisting it in the layout `crate::oauth` reads is
    // what makes the deployment authorized.
    if let Some(token) = extract_token(&transcript) {
        return match write_credential(&config.claude_code_home, &token) {
            Ok(()) => Outcome::Authorized { expires_at: None },
            Err(e) => Outcome::Failed(format!(
                "login succeeded but the credential could not be saved: {e}"
            )),
        };
    }
    let compact = compact_terminal_text(&transcript);
    let failure = if contains_marker(&compact, FAILURE_MARKERS) {
        format!(
            "authorization code was rejected; CLI reported: {}. Request a fresh login URL and code",
            rejection_verdict(&compact)
        )
    } else if matches!(verdict, Err(WaitError::Timeout)) {
        format!(
            "login timed out waiting for the CLI to accept or reject the authorization code; last output: {}",
            excerpt(&transcript, code, 400)
        )
    } else {
        format!(
            "login process ended without producing a credential; last output: {}",
            excerpt(&transcript, code, 400)
        )
    };
    Outcome::Failed(failure)
}

/// Turn the CLI's known compacted verdicts back into readable API text.
fn rejection_verdict(compact: &str) -> String {
    const STATUS_PREFIX: &str = "OAutherror:Requestfailedwithstatuscode";

    if compact.contains("OAutherror:Invalidcode") {
        return "OAuth error: Invalid code. Please make sure the full code was copied".into();
    }
    if let Some(start) = compact.rfind(STATUS_PREFIX) {
        let rest = &compact[start + STATUS_PREFIX.len()..];
        let status: String = rest.chars().take_while(char::is_ascii_digit).collect();
        if !status.is_empty() {
            return format!("OAuth error: Request failed with status code {status}");
        }
    }
    if compact.contains("invalid_grant") {
        return "OAuth error: invalid_grant".into();
    }
    if compact.contains("Authenticationfailed") {
        return "Authentication failed".into();
    }
    if compact.contains("Loginfailed") {
        return "Login failed".into();
    }
    "OAuth error: the CLI rejected the authorization code".into()
}

/// A credential the router can now read.
struct FoundCredential {
    /// Expiry timestamp in milliseconds, when the credential carries one.
    expires_at: Option<i64>,
}

/// Probe the credential directory the same way the proxy does.
fn read_credential(home: &Path) -> Option<FoundCredential> {
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, home);
    reader.read_token().ok().map(|token| FoundCredential {
        expires_at: token.expires_at_ms,
    })
}

/// Write a Claude Code credential file in the nested layout the router reads.
fn write_credential(home: &Path, token: &str) -> std::io::Result<()> {
    std::fs::create_dir_all(home)?;
    let path = home.join(".credentials.json");
    let body = serde_json::json!({
        "claudeAiOauth": {
            "accessToken": token,
            "subscriptionType": "max",
        }
    });
    std::fs::write(&path, serde_json::to_vec_pretty(&body)?)?;
    restrict_permissions(&path);
    Ok(())
}

/// Credentials are secrets: keep them owner-only where the platform allows it.
#[cfg(unix)]
fn restrict_permissions(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}

#[cfg(not(unix))]
fn restrict_permissions(_path: &Path) {}

/// Fail early and clearly when the credential directory cannot be written,
/// rather than after the human has already completed a browser login.
fn ensure_writable_dir(home: &Path) -> Result<(), LoginError> {
    std::fs::create_dir_all(home).map_err(|e| {
        LoginError::Storage(format!(
            "{} is not writable ({e}); mount it read-write to use the login API",
            home.display()
        ))
    })?;
    let probe = home.join(".router-login-write-probe");
    std::fs::write(&probe, b"").map_err(|e| {
        LoginError::Storage(format!(
            "{} is not writable ({e}); mount it read-write to use the login API",
            home.display()
        ))
    })?;
    let _ = std::fs::remove_file(&probe);
    Ok(())
}

/// Last `limit` characters of a transcript, safe to return to a client.
///
/// Two kinds of secret live in a login transcript and both are removed before
/// the text is truncated: the account token the CLI prints (recognised by its
/// prefix) and the authorization code the human pasted, which the terminal
/// echoes back and which no pattern could identify — so it is passed in.
fn excerpt(text: &str, code: &str, limit: usize) -> String {
    let redacted = crate::login_url::redact_value(&crate::login_url::redact_secrets(text), code);
    tail(&redacted, limit)
}

/// Last `limit` characters of `text`, trimmed.
fn tail(text: &str, limit: usize) -> String {
    let trimmed = text.trim();
    let count = trimmed.chars().count();
    if count <= limit {
        return trimmed.to_string();
    }
    trimmed.chars().skip(count - limit).collect()
}

#[cfg(test)]
mod tests;