link-assistant-router 1.4.4

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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
//! Subscription OAuth credential readers for vendor coding CLIs.
//!
//! Vendor coding assistants cache subscription OAuth credentials in well-known
//! home-directory files; this module reads all four supported layouts into one
//! normalized token shape.
//!
//! Vendor-specific layouts normalize into [`SubscriptionToken`].

use serde::Deserialize;
use std::path::{Path, PathBuf};

mod external;

mod types;
pub use types::{SubscriptionProvider, SubscriptionToken};

/// Errors raised while reading subscription credentials.
#[derive(Debug)]
pub enum SubscriptionError {
    /// No credential file existed in any candidate location.
    NoCredentials(String),
    /// A credential file existed but could not be read.
    ReadError(String),
    /// A credential file existed but could not be parsed.
    ParseError(String),
    /// A credential file parsed but contained no usable access token.
    NoToken(String),
}

impl std::fmt::Display for SubscriptionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoCredentials(m)
            | Self::ReadError(m)
            | Self::ParseError(m)
            | Self::NoToken(m) => write!(f, "{m}"),
        }
    }
}

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

impl From<std::io::Error> for SubscriptionError {
    fn from(_error: std::io::Error) -> Self {
        Self::ReadError("credential transaction lock failed".into())
    }
}

/// Mark a copied credential as belonging to an external rotating refresh
/// chain.
///
/// The marker lives in the same atomically replaced JSON document, so it
/// cannot be committed independently of the credential it protects.
pub use external::{
    has_promotion_receipt, mark_external_refresh_owner, mark_promotion_receipt,
    reference_external_credential,
};

fn credential_file_lock_path(path: &Path) -> PathBuf {
    let mut lock = path.as_os_str().to_os_string();
    lock.push(".router-transaction.lock");
    PathBuf::from(lock)
}

/// One credential selected for adoption: its bytes, parsed token, and owner.
///
/// A single selection produces all fields, so validation and reporting cannot
/// describe different credentials. Fresh imports reference `path`; retained
/// Router-owned transactions may promote `document` (issue #280).
#[derive(Debug, Clone)]
pub struct ImportSource {
    /// The credential exactly as stored, used for validation and recovery.
    ///
    /// Not re-serialized from `token`: that type models no `id_token`,
    /// `auth_mode`, or `scope`, and Codex derives its account id from
    /// `id_token` on every read.
    pub document: String,
    /// What `document` parses to, for reporting expiry and probing the vendor.
    pub token: SubscriptionToken,
    /// Which store `document` came from, for ownership and reporting.
    pub origin: crate::platform_keychain::Origin,
    /// Writable file holding the selected document, when it has one.
    pub path: Option<PathBuf>,
}

/// Replacement policy for a Router-owned credential install.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallMode {
    /// Replace the authoritative recognized document after taking the shared
    /// lock, falling back to the canonical vendor path when the home is empty.
    Replace,
    /// Install only when none of the provider's recognized files exists.
    IfAbsent,
}

/// Successful credential-install outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstallDocumentResult {
    /// The candidate document was installed at the authoritative vendor path.
    Installed(PathBuf),
    /// A recognized credential appeared before installation and was preserved.
    AlreadyPresent(PathBuf),
}

/// Reads and normalizes a single provider's subscription credentials.
#[derive(Debug, Clone)]
pub struct SubscriptionReader {
    provider: SubscriptionProvider,
    home: PathBuf,
}

fn credential_lock_error(provider: SubscriptionProvider, error: &std::io::Error) -> String {
    let action = if error.kind() == std::io::ErrorKind::WouldBlock {
        "timed out waiting for"
    } else {
        "could not acquire"
    };
    format!("{action} the durable {provider} credential lock")
}

impl SubscriptionReader {
    /// Create a reader for `provider` rooted at an explicit home directory.
    #[must_use]
    pub fn new(provider: SubscriptionProvider, home: impl Into<PathBuf>) -> Self {
        Self {
            provider,
            home: home.into(),
        }
    }

    /// Create a reader using the provider's default/overridden home directory.
    #[must_use]
    pub fn from_user_home(provider: SubscriptionProvider, user_home: &str) -> Self {
        Self::new(provider, provider.resolve_home(user_home))
    }

    /// The provider this reader serves.
    #[must_use]
    pub const fn provider(&self) -> SubscriptionProvider {
        self.provider
    }

    /// The credential home directory this reader searches.
    #[must_use]
    pub fn home(&self) -> &Path {
        &self.home
    }

    /// Candidate credential file paths, most specific first.
    #[must_use]
    pub fn credential_paths(&self) -> Vec<PathBuf> {
        self.provider
            .credential_filenames()
            .iter()
            .map(|name| self.home.join(name))
            .collect()
    }

    /// The credential document to adopt from this home, and where it came from.
    ///
    /// Import needs the *document*, not a [`SubscriptionToken`]: this type does
    /// not model `id_token`, `auth_mode`, `scope`, or `token_type`, and Codex's
    /// `account_id` is derived from `id_token` on every read. Re-serializing a
    /// token would therefore silently drop the field the next read depends on,
    /// which is the same reason [`write_token`](Self::write_token) merges into
    /// the existing document rather than replacing it.
    ///
    /// The platform store is consulted the same way the reader consults it, so
    /// an import on macOS adopts the credential the vendor client is actually
    /// using rather than the stale file sitting next to it (issue #249). It is
    /// preferred only when it is genuinely newer, by the same rule
    /// [`read_token_from`](Self::read_token_from) applies.
    ///
    /// The token is returned with the document because it *is* the document's
    /// token: reading the source a second time to describe it let the two
    /// diverge, since [`read_token`](Self::read_token) consults the platform
    /// store only for the vendor's default home while import consults it for
    /// any home. An import always names a source home that differs from the
    /// destination — otherwise there is nothing to adopt — so that condition
    /// held on every macOS import, and the report described the file while the
    /// Keychain credential was the one installed (issue #280). Returning both
    /// from one selection makes them agree by construction.
    ///
    /// # Errors
    ///
    /// Returns the file's error when neither store holds a usable credential.
    pub fn read_document_for_import(&self) -> Result<ImportSource, SubscriptionError> {
        self.import_from_store(self.import_source_keychain().as_deref())
    }

    /// Whether the authoritative Claude credential carries an exact OAuth scope.
    ///
    /// Scopes deliberately remain outside [`SubscriptionToken`]: they are
    /// authorization metadata owned by the source credential, not routing
    /// metadata that should be copied into requests or rewritten on refresh.
    pub(crate) fn has_claude_scope(&self, required: &str) -> Result<bool, SubscriptionError> {
        if self.provider != SubscriptionProvider::Claude {
            return Ok(false);
        }
        let source = self.read_document_for_import()?;
        let document =
            serde_json::from_str::<serde_json::Value>(&source.document).map_err(|_| {
                SubscriptionError::ParseError(
                    "Claude credential authorization metadata is invalid".into(),
                )
            })?;
        let block = document.get("claudeAiOauth").unwrap_or(&document);
        let in_array = block
            .get("scopes")
            .and_then(serde_json::Value::as_array)
            .is_some_and(|scopes| scopes.iter().any(|scope| scope.as_str() == Some(required)));
        let in_string = block
            .get("scope")
            .and_then(serde_json::Value::as_str)
            .is_some_and(|scopes| scopes.split_whitespace().any(|scope| scope == required));
        Ok(in_array || in_string)
    }

    /// [`read_document_for_import`](Self::read_document_for_import) against an
    /// already-read store entry.
    ///
    /// Split out for the same reason [`select_store`](Self::select_store) is:
    /// no test may read the real login Keychain, and none may write to it, so
    /// the store-versus-file half of import is otherwise unreachable from a
    /// test on any platform.
    fn import_from_store(
        &self,
        from_keychain: Option<&str>,
    ) -> Result<ImportSource, SubscriptionError> {
        // Decide with the same rule the reader uses, so import and serving
        // never disagree about which store is live.
        let (token, origin) =
            self.select_store(from_keychain.and_then(|raw| self.parse_store_credential(raw)))?;
        let (document, path) = match origin {
            crate::platform_keychain::Origin::Keychain => {
                let document = from_keychain.map(str::to_owned).ok_or_else(|| {
                    SubscriptionError::NoCredentials(format!(
                        "No {} credential in the platform store",
                        self.provider
                    ))
                })?;
                (document, None)
            }
            crate::platform_keychain::Origin::File
            | crate::platform_keychain::Origin::ExternalFile
            | crate::platform_keychain::Origin::AdoptedFile => {
                let path = self.discover_credential_path().ok_or_else(|| {
                    SubscriptionError::NoCredentials(format!(
                        "No {} credential file in {}",
                        self.provider,
                        self.home.display()
                    ))
                })?;
                let stored = external::read_document(&path)?;
                (stored.raw, Some(stored.path))
            }
        };
        Ok(ImportSource {
            document,
            token,
            origin,
            path,
        })
    }

    /// The raw platform-store entry to consider when importing from this home.
    ///
    /// Gated on the home being the vendor's default, exactly as the serving
    /// path is. The store is a single machine-wide entry, so consulting it for
    /// *any* home let it answer for a directory it does not describe: on macOS
    /// it usually holds the newest credential, so it beat every explicitly
    /// named source and no spelling of `auth import <provider> <dir>` could
    /// reach the file the operator pointed at (issue #285).
    ///
    /// This was written unguarded on purpose, reasoning that an operator naming
    /// a directory is telling us where to look and that the pool-collapse risk
    /// does not apply because nothing is served from this reader. The first
    /// half is right and is what the guard now honours; the second half was
    /// wrong. Import *writes the credential a deployment then serves*, so
    /// collapsing a pool of per-account directories onto one machine-wide
    /// entry is exactly as damaging here as on the serving path — see
    /// [`is_vendor_default_home`](Self::is_vendor_default_home).
    ///
    /// An unqualified import still resolves to the vendor's own home, so the
    /// case this was built for — a live Keychain credential beside a stale file
    /// in the vendor's home (issue #249) — keeps working.
    fn import_source_keychain(&self) -> Option<String> {
        if !self.consults_platform_store_for_import() {
            return None;
        }
        crate::platform_keychain::lookup(self.provider)
    }

    /// Whether an import from this home may consult the platform store.
    ///
    /// Split from the lookup so the *decision* can be asserted on every
    /// platform. The lookup itself finds nothing off macOS and depends on the
    /// developer's own login on it, so a test that went through it would pass
    /// vacuously on CI and read a real credential locally — which no test may
    /// do.
    fn consults_platform_store_for_import(&self) -> bool {
        self.is_vendor_default_home()
    }

    /// Install a credential document owner-only and atomically.
    pub fn install_document(&self, document: &str) -> Result<PathBuf, String> {
        // Where the provider's own client writes, so an adopted credential
        // lands exactly where a fresh login would put it.
        let path = self
            .home
            .join(self.provider.canonical_credential_filename());
        Self::install_document_at(&path, document)
    }

    fn install_document_at(path: &Path, document: &str) -> Result<PathBuf, String> {
        let lock_path = credential_file_lock_path(path);
        crate::durable_file::with_exclusive_lock::<_, std::io::Error>(&lock_path, || {
            crate::durable_file::transactional_write_owner_only(path, document.as_bytes())
        })
        .map_err(|error| crate::durable_file::describe_write_failure(path, &error))?;
        Ok(path.to_path_buf())
    }

    /// Install while holding the provider/account refresh lock.
    pub async fn install_document_locked(
        &self,
        data_dir: &Path,
        account: &str,
        document: &str,
        mode: InstallMode,
    ) -> Result<InstallDocumentResult, String> {
        self.install_document_locked_with_refusal(data_dir, account, document, mode, None)
            .await
    }

    /// Check for any recognized primary or recovery credential while holding
    /// the same transaction lock used by refresh, login, and installation.
    ///
    /// Conditional import uses this as a non-destructive preflight so an
    /// already-provisioned destination can win without spending the staged
    /// candidate's rotating refresh token. Installation still performs the
    /// same check again under its own lock after validation, closing the race.
    pub async fn existing_document_locked(
        &self,
        data_dir: &Path,
        account: &str,
    ) -> Result<Option<PathBuf>, String> {
        let lock_path = crate::credential_recovery_store::credential_lock_path(
            data_dir,
            self.provider,
            account,
        );
        let _lock = crate::durable_file::lock_exclusive_async(
            &lock_path,
            crate::credential_recovery_store::CREDENTIAL_LOCK_TIMEOUT,
        )
        .await
        .map_err(|error| credential_lock_error(self.provider, &error))?;
        self.existing_document(data_dir, account)
    }

    /// Enforce `refusal` only after the locked absence check.
    pub async fn install_document_locked_with_refusal(
        &self,
        data_dir: &Path,
        account: &str,
        document: &str,
        mode: InstallMode,
        refusal: Option<String>,
    ) -> Result<InstallDocumentResult, String> {
        let lock_path = crate::credential_recovery_store::credential_lock_path(
            data_dir,
            self.provider,
            account,
        );
        let _lock = crate::durable_file::lock_exclusive_async(
            &lock_path,
            crate::credential_recovery_store::CREDENTIAL_LOCK_TIMEOUT,
        )
        .await
        .map_err(|error| credential_lock_error(self.provider, &error))?;

        // Replacement must not report success over storage state that serving
        // will reject. A valid sidecar is reconciled naturally against the new
        // primary on the next reload; an unreadable or malformed one is
        // uncertainty and blocks every destination mutation.
        if mode == InstallMode::Replace {
            let _ = crate::credential_recovery_store::valid_recovery_record_path(
                data_dir,
                self.provider,
                account,
            )?;
        }

        if mode == InstallMode::IfAbsent {
            if let Some(path) = self.existing_document(data_dir, account)? {
                return Ok(InstallDocumentResult::AlreadyPresent(path));
            }
            if let Some(error) = refusal {
                return Err(error);
            }
        }

        let authoritative = (mode == InstallMode::Replace)
            .then(|| self.discover_credential_path())
            .flatten();
        // Invalidation is fallible and therefore belongs before the primary
        // replacement. If it fails, the working credential stays byte-for-byte
        // authoritative instead of a new credential being active behind an
        // error result (issue #424).
        crate::model_catalog::ModelCatalogCache::invalidate_persisted(
            data_dir,
            self.provider,
            account,
        )?;
        let installed = authoritative
            .map_or_else(
                || self.install_document(document),
                |path| Self::install_document_at(&path, document),
            )
            .map(InstallDocumentResult::Installed)?;
        Ok(installed)
    }

    fn existing_document(&self, data_dir: &Path, account: &str) -> Result<Option<PathBuf>, String> {
        for path in self.credential_paths() {
            match path.try_exists() {
                Ok(true) => return Ok(Some(path)),
                Ok(false) => {}
                Err(error) => {
                    return Err(format!(
                        "could not check the {} credential destination: {error}",
                        self.provider
                    ));
                }
            }
        }
        crate::credential_recovery_store::valid_recovery_record_path(
            data_dir,
            self.provider,
            account,
        )
    }

    /// Remove every credential file this provider is read from.
    ///
    /// All candidate names are removed, not just the one a login happens to
    /// write. Claude alone is read from five (`credentials.json`,
    /// `.credentials.json`, `auth.json`, `oauth.json`, `config.json`), so
    /// clearing only the written name would leave the reader finding another
    /// and reporting the credential as still present — a withdrawal that
    /// silently did not happen.
    ///
    /// Returns the paths actually removed. A platform secret store is *not*
    /// touched: that entry belongs to the vendor CLI, and deleting it would
    /// log the user out of a client the router does not own. Callers that can
    /// surface it should report it instead — see
    /// [`crate::platform_keychain::service_name`].
    ///
    /// # Errors
    ///
    /// Returns an operator-readable message when a file exists but cannot be
    /// removed.
    pub fn clear_credentials(&self) -> Result<Vec<PathBuf>, String> {
        let mut removed = Vec::new();
        for path in self.credential_paths() {
            match std::fs::remove_file(&path) {
                Ok(()) => removed.push(path),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => {
                    return Err(format!("could not remove {}: {error}", path.display()));
                }
            }
        }
        Ok(removed)
    }

    /// First existing credential file, if any (for diagnostics).
    #[must_use]
    pub fn discover_credential_path(&self) -> Option<PathBuf> {
        self.credential_paths().into_iter().find(|p| p.exists())
    }

    /// Read and normalize the subscription token.
    ///
    /// Consults the platform secret store as well as the credential file and
    /// returns whichever holds the newer credential; see [`read_token_from`](Self::read_token_from).
    pub fn read_token(&self) -> Result<SubscriptionToken, SubscriptionError> {
        self.read_token_from().map(|(token, _)| token)
    }

    /// Read the subscription token and say which store it came from.
    ///
    /// On macOS the Claude Code credential file is a snapshot that nothing
    /// rotates while the live credential sits in the login Keychain, so reading
    /// only the file saw a token that had been dead for hours while the vendor
    /// client kept working (issue #249). Both stores are read and the newer
    /// credential wins, which keeps every other platform on exactly the file it
    /// used before — there, the keychain lookup simply finds nothing.
    ///
    /// "Newer" is decided by expiry: the two stores hold independent
    /// credentials rather than two copies of one, so the one that stays valid
    /// longer is the live chain. A credential with no expiry loses to one that
    /// has a usable expiry, since an unknown expiry cannot be shown to be
    /// newer.
    ///
    /// # Errors
    ///
    /// Returns the file's error when neither store yields a token, so a machine
    /// with no keychain entry reports exactly what it reported before.
    pub fn read_token_from(
        &self,
    ) -> Result<(SubscriptionToken, crate::platform_keychain::Origin), SubscriptionError> {
        self.select_store(self.read_token_from_keychain())
    }

    /// Choose between the credential file and an already-read store credential.
    ///
    /// Split from [`read_token_from`](Self::read_token_from) so the preference
    /// rule can be tested without a real login Keychain — which no test may
    /// depend on, and none may write to.
    fn select_store(
        &self,
        from_keychain: Option<SubscriptionToken>,
    ) -> Result<(SubscriptionToken, crate::platform_keychain::Origin), SubscriptionError> {
        let from_file = self.read_token_from_file();
        match (from_file, from_keychain) {
            (Ok((file, file_origin)), Some(keychain)) => {
                // Only a strictly later expiry displaces the file, so a store
                // that merely mirrors it changes nothing an operator sees.
                if keychain.expires_at_ms > file.expires_at_ms {
                    Ok((keychain, crate::platform_keychain::Origin::Keychain))
                } else {
                    Ok((file, file_origin))
                }
            }
            (Err(_), Some(keychain)) => Ok((keychain, crate::platform_keychain::Origin::Keychain)),
            (file, None) => file,
        }
    }

    /// Whether this reader describes the home the vendor client itself uses.
    ///
    /// The platform store is a single global entry, so it speaks only for the
    /// default home. A reader pointed somewhere else — a pooled account, a
    /// per-account directory, a mounted credential in a container — must keep
    /// reading exactly the file it was given: letting one machine-wide keychain
    /// entry answer for every account would collapse a pool onto one
    /// subscription.
    /// Whether this reader is pointed at a home the vendor's own client uses.
    ///
    /// Both spellings count: the conventional `~/.claude`, and whatever the
    /// provider's home variable names. Asking only the second meant that
    /// setting `CLAUDE_CODE_HOME` — which a deployment does, to name its
    /// *destination* — stopped `~/.claude` counting as the vendor's home, so
    /// the platform store went unconsulted and a stale file won over the live
    /// Keychain entry: the situation issue #249 was about, reachable through
    /// the variable named in issue #307.
    ///
    /// A directory named explicitly on the command line is neither, which is
    /// what keeps "this credential from *there*" meaning exactly that (#285).
    fn is_vendor_default_home(&self) -> bool {
        let conventional = std::env::var("HOME")
            .is_ok_and(|home| self.provider.conventional_home(&home) == self.home);
        conventional || self.provider.named_home() == Some(self.home.clone())
    }

    /// The credential the platform secret store holds, when there is one.
    fn read_token_from_keychain(&self) -> Option<SubscriptionToken> {
        if !self.is_vendor_default_home() {
            return None;
        }
        let raw = crate::platform_keychain::lookup(self.provider)?;
        self.parse_store_credential(&raw)
    }

    /// Whether this home currently has a usable credential in the platform
    /// store. Conditional import treats that as an existing destination even
    /// when no credential file exists.
    #[must_use]
    pub fn has_platform_store_credential(&self) -> bool {
        self.read_token_from_keychain().is_some()
    }

    /// Whether writing `candidate` to this home would still leave a newer
    /// platform-store credential authoritative.
    #[must_use]
    pub fn candidate_is_shadowed_by_platform_store(&self, candidate: &SubscriptionToken) -> bool {
        Self::candidate_is_shadowed_by_store(candidate, self.read_token_from_keychain())
    }

    fn candidate_is_shadowed_by_store(
        candidate: &SubscriptionToken,
        from_store: Option<SubscriptionToken>,
    ) -> bool {
        from_store.is_some_and(|stored| stored.expires_at_ms > candidate.expires_at_ms)
    }

    /// Normalize a credential held by the platform store.
    ///
    /// The stored value is the same JSON shape the file holds, so the file
    /// parser is reused rather than duplicated. An entry this crate cannot read
    /// yields `None` and leaves the file as the source, which is the behaviour
    /// every platform had before the store was consulted at all.
    fn parse_store_credential(&self, raw: &str) -> Option<SubscriptionToken> {
        let parsed: RawCredentials = serde_json::from_str(raw)
            .map_err(|error| {
                tracing::debug!(
                    "keychain entry for {} is not usable JSON: {error}",
                    self.provider
                );
            })
            .ok()?;
        parsed.into_token(self.provider)
    }

    /// Read and normalize the subscription token from the credential file.
    fn read_token_from_file(
        &self,
    ) -> Result<(SubscriptionToken, crate::platform_keychain::Origin), SubscriptionError> {
        let mut last_err: Option<SubscriptionError> = None;
        for path in self.credential_paths() {
            let lock_path = credential_file_lock_path(&path);
            let parsed = crate::durable_file::with_exclusive_lock::<_, SubscriptionError>(
                &lock_path,
                || {
                    crate::durable_file::recover_transactional_write(&path).map_err(|error| {
                        SubscriptionError::ReadError(format!(
                            "Failed to recover {}: {error}",
                            path.display()
                        ))
                    })?;
                    if !path.exists() {
                        return Ok(None);
                    }
                    let stored = external::read_document(&path)?;
                    let origin = stored.origin;
                    let raw: RawCredentials =
                        serde_json::from_value(stored.value).map_err(|e| {
                            SubscriptionError::ParseError(format!(
                                "Failed to parse {}: {e}",
                                path.display()
                            ))
                        })?;
                    Ok(raw.into_token(self.provider).map(|token| (token, origin)))
                },
            )?;
            match parsed {
                Some(token) => return Ok(token),
                None => {
                    if path.exists() {
                        last_err = Some(SubscriptionError::NoToken(format!(
                            "No {} access token in {}",
                            self.provider,
                            path.display()
                        )));
                    }
                }
            }
        }
        Err(last_err.unwrap_or_else(|| {
            SubscriptionError::NoCredentials(format!(
                "No {} credential file found in {}",
                self.provider,
                self.home.display()
            ))
        }))
    }

    /// Write a refreshed token back into the existing credential file.
    ///
    /// Vendors rotate refresh tokens: the response to a refresh often carries a
    /// *new* `refresh_token` that supersedes the stored one. Keeping that only
    /// in memory means the next process start replays a spent token, turning a
    /// recoverable state into a mandatory re-login (issue #205).
    ///
    /// The refreshed values are merged into the document that is already there,
    /// rather than serialized from [`SubscriptionToken`], because the vendor
    /// CLIs rely on fields this crate does not model (`id_token`, `auth_mode`,
    /// `scope`, `token_type`). Only the file that was actually read is updated.
    ///
    /// # Errors
    ///
    /// Returns [`SubscriptionError::ReadError`] when no credential file exists,
    /// or when the file cannot be parsed or replaced — including a read-only
    /// mount, which is reported in terms of the mount rather than as a bare
    /// `errno`.
    pub fn write_token(&self, token: &SubscriptionToken) -> Result<(), SubscriptionError> {
        let path = self.discover_credential_path().ok_or_else(|| {
            SubscriptionError::NoCredentials(format!(
                "No {} credential file to update in {}",
                self.provider,
                self.home.display()
            ))
        })?;
        external::write_refreshed_token(&path, self.provider, token)
    }
}

/// Update the token fields of an existing credential document in place.
///
/// Each vendor stores the same three values under a different shape, and only
/// the keys already present are rewritten, so a file written by the vendor CLI
/// keeps its own layout and every field this crate does not model.
fn merge_refreshed_token(
    document: &mut serde_json::Value,
    provider: SubscriptionProvider,
    token: &SubscriptionToken,
) {
    let set = |target: &mut serde_json::Value, key: &str, value: Option<String>| {
        if let Some(value) = value.filter(|value| !value.is_empty()) {
            target[key] = serde_json::Value::String(value);
        }
    };

    match provider {
        SubscriptionProvider::Claude => {
            // Real Claude Code files nest the values; hand-written ones are flat.
            let nested = document.get("claudeAiOauth").is_some();
            let target = if nested {
                &mut document["claudeAiOauth"]
            } else {
                &mut *document
            };
            // Resolve every key before mutating: a file may use either the
            // camelCase or the snake_case spelling, and whichever it already
            // uses is the one kept.
            let key = |camel: &'static str, snake: &'static str| {
                if target.get(snake).is_some() && target.get(camel).is_none() {
                    snake
                } else {
                    camel
                }
            };
            let (access_key, refresh_key, expiry_key) = (
                key("accessToken", "access_token"),
                key("refreshToken", "refresh_token"),
                key("expiresAt", "expires_at"),
            );
            set(target, access_key, Some(token.access_token.clone()));
            set(target, refresh_key, token.refresh_token.clone());
            if let Some(expiry) = token.expires_at_ms {
                target[expiry_key] = serde_json::Value::from(expiry);
            }
        }
        SubscriptionProvider::Codex => {
            // Codex keeps its tokens under `tokens` and stamps `last_refresh`.
            let target = &mut document["tokens"];
            set(target, "access_token", Some(token.access_token.clone()));
            set(target, "refresh_token", token.refresh_token.clone());
            document["last_refresh"] = serde_json::Value::String(chrono::Utc::now().to_rfc3339());
        }
        SubscriptionProvider::Gemini | SubscriptionProvider::Qwen => {
            set(document, "access_token", Some(token.access_token.clone()));
            set(document, "refresh_token", token.refresh_token.clone());
            if let Some(expiry) = token.expires_at_ms {
                document["expiry_date"] = serde_json::Value::from(expiry);
            }
        }
    }
}

/// Construct readers for every vendor, honoring the configured Claude home.
#[must_use]
pub fn all_subscription_readers(claude_home: &str, user_home: &str) -> Vec<SubscriptionReader> {
    SubscriptionProvider::ALL
        .into_iter()
        .map(|provider| {
            if provider == SubscriptionProvider::Claude {
                SubscriptionReader::new(provider, claude_home)
            } else {
                SubscriptionReader::from_user_home(provider, user_home)
            }
        })
        .collect()
}

/// Reader used by an explicitly pinned non-Claude subscription provider.
#[must_use]
pub fn active_subscription_reader(
    upstream: crate::config::UpstreamProvider,
    readers: &[SubscriptionReader],
) -> Option<SubscriptionReader> {
    upstream
        .subscription_provider()
        .filter(|provider| *provider != SubscriptionProvider::Claude)
        .and_then(|provider| {
            readers
                .iter()
                .find(|reader| reader.provider() == provider)
                .cloned()
        })
}

/// Superset of every vendor credential layout. Each provider reads only the
/// fields it uses; serde `alias` covers `camelCase`/`snake_case` variants.
#[derive(Debug, Default, Deserialize)]
struct RawCredentials {
    // Flat layout (Gemini / Qwen / hand-written): top-level token fields.
    #[serde(alias = "accessToken")]
    access_token: Option<String>,
    #[serde(alias = "oauthToken", alias = "oauth_token")]
    token: Option<String>,
    #[serde(alias = "refreshToken")]
    refresh_token: Option<String>,
    /// Gemini/Qwen store expiry as `expiry_date` (ms); others use `expiresAt`.
    #[serde(alias = "expiryDate", alias = "expiresAt", alias = "expires_at")]
    expiry_date: Option<i64>,
    /// Qwen per-token base URL override.
    #[serde(alias = "resourceUrl")]
    resource_url: Option<String>,
    /// `ChatGPT` account id when stored at the top level.
    #[serde(alias = "accountId", alias = "chatgpt_account_id")]
    account_id: Option<String>,
    // Codex nested layout: `{ "tokens": { ... }, "last_refresh": ... }`.
    tokens: Option<CodexTokens>,
    // Claude nested layout: `{ "claudeAiOauth": { ... } }`.
    #[serde(alias = "claudeAiOauth")]
    claude_ai_oauth: Option<ClaudeBlock>,
}

#[derive(Debug, Default, Deserialize)]
struct CodexTokens {
    #[serde(alias = "accessToken")]
    access_token: Option<String>,
    #[serde(alias = "refreshToken")]
    refresh_token: Option<String>,
    #[serde(alias = "accountId")]
    account_id: Option<String>,
    #[serde(alias = "idToken")]
    id_token: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct ClaudeBlock {
    #[serde(alias = "accessToken")]
    access_token: Option<String>,
    #[serde(alias = "oauthToken", alias = "oauth_token")]
    token: Option<String>,
    #[serde(alias = "refreshToken")]
    refresh_token: Option<String>,
    #[serde(alias = "expiresAt", alias = "expires_at")]
    expires_at: Option<i64>,
}

fn non_empty(s: Option<String>) -> Option<String> {
    s.filter(|v| !v.is_empty())
}

impl RawCredentials {
    /// Resolve the provider-specific access token and routing metadata.
    fn into_token(self, provider: SubscriptionProvider) -> Option<SubscriptionToken> {
        match provider {
            SubscriptionProvider::Claude => self.claude_token(),
            SubscriptionProvider::Codex => self.codex_token(),
            // Gemini and Qwen both use the flat layout; Qwen adds resource_url.
            SubscriptionProvider::Gemini | SubscriptionProvider::Qwen => self.flat_token(),
        }
    }

    fn claude_token(self) -> Option<SubscriptionToken> {
        // Prefer the nested `claudeAiOauth` block (real Claude Code layout),
        // then fall back to flat fields.
        if let Some(block) = self.claude_ai_oauth
            && let Some(access) = non_empty(block.access_token).or_else(|| non_empty(block.token))
        {
            return Some(SubscriptionToken {
                access_token: access,
                refresh_token: non_empty(block.refresh_token),
                expires_at_ms: block.expires_at,
                account_id: None,
                resource_url: None,
            });
        }
        let access = non_empty(self.access_token).or_else(|| non_empty(self.token))?;
        Some(SubscriptionToken {
            access_token: access,
            refresh_token: non_empty(self.refresh_token),
            expires_at_ms: self.expiry_date,
            account_id: None,
            resource_url: None,
        })
    }

    fn codex_token(self) -> Option<SubscriptionToken> {
        let tokens = self.tokens.unwrap_or_default();
        let access = non_empty(tokens.access_token)?;
        let expires_at_ms = self.expiry_date.or_else(|| jwt_expiry_ms(&access));
        let account_id = non_empty(tokens.account_id)
            .or_else(|| non_empty(self.account_id))
            .or_else(|| {
                tokens
                    .id_token
                    .as_deref()
                    .and_then(account_id_from_id_token)
            });
        Some(SubscriptionToken {
            access_token: access,
            refresh_token: non_empty(tokens.refresh_token),
            expires_at_ms,
            account_id,
            resource_url: None,
        })
    }

    fn flat_token(self) -> Option<SubscriptionToken> {
        let access = non_empty(self.access_token).or_else(|| non_empty(self.token))?;
        Some(SubscriptionToken {
            access_token: access,
            refresh_token: non_empty(self.refresh_token),
            expires_at_ms: self.expiry_date,
            account_id: non_empty(self.account_id),
            resource_url: non_empty(self.resource_url),
        })
    }
}

/// Read a JWT `exp` claim without verifying the signature. This is only a
/// local expiry hint; the token endpoint and upstream remain authoritative.
fn jwt_expiry_ms(token: &str) -> Option<i64> {
    use base64::Engine as _;
    let payload = token.split('.').nth(1)?;
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(payload)
        .ok()?;
    let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
    claims.get("exp")?.as_i64()?.checked_mul(1000)
}

/// Extract the `ChatGPT` account id from a Codex `id_token` JWT.
///
/// Codex stores the account id directly, but older/edge auth files only carry
/// the `id_token`; its payload nests the id under
/// `https://api.openai.com/auth.chatgpt_account_id` (or `chatgpt_account_id`).
fn account_id_from_id_token(id_token: &str) -> Option<String> {
    use base64::Engine as _;
    let payload_b64 = id_token.split('.').nth(1)?;
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(payload_b64)
        .ok()?;
    let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
    let auth = claims.get("https://api.openai.com/auth");
    let candidate = auth
        .and_then(|a| a.get("chatgpt_account_id"))
        .or_else(|| claims.get("chatgpt_account_id"))
        .or_else(|| auth.and_then(|a| a.get("account_id")));
    candidate
        .and_then(serde_json::Value::as_str)
        .map(ToString::to_string)
}

#[cfg(test)]
#[path = "subscription_adopted_tests.rs"]
mod adopted_tests;
#[cfg(test)]
#[path = "subscription_install_tests.rs"]
mod install_tests;
#[cfg(test)]
#[path = "subscription_tests.rs"]
mod tests;