link-assistant-router 1.4.6

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
//! `router auth import` — adopt a login this machine already has.
//!
//! Split from `auth_cli.rs` to keep that file within the repository's
//! 1000-line limit.
//!
//! Authorizing and importing are different operations, not variations of one:
//! authorizing goes and gets a new credential interactively, importing adopts
//! one that already exists. They differ in prerequisites, side effects, and
//! whether a human has to be present — which decides whether a headless
//! deployment can be provisioned at all (issue #278).

use std::process::ExitCode;

use link_assistant_router::cli::{AuthOp, ImportProvider};
use link_assistant_router::credential_acceptance::AcceptedCredential as ValidatedCandidate;
#[cfg(test)]
use link_assistant_router::credential_acceptance::catalog_base_for_candidate;
use link_assistant_router::subscription::{
    ImportSource, InstallDocumentResult, InstallMode, SubscriptionProvider, SubscriptionReader,
};

#[path = "auth_import_result.rs"]
mod import_result;
#[path = "auth_import_resume.rs"]
mod import_resume;

use import_result::{ImportExecution, ImportFailure, ImportOutcome, ImportPhase, finish};

/// Vendor evidence gathered before an import may touch its destination.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
enum CredentialProbe {
    Accepted,
    Rejected,
    Unverified,
}

/// Destination and rejection policy selected by the public import flags.
#[derive(Debug, Clone, Copy, Default)]
struct ImportPolicy {
    if_absent: bool,
    /// Whether the caller explicitly asserted the safe-flow capability. This
    /// is diagnostic only and never bypasses candidate validation.
    capability_asserted: bool,
    /// A retained acceptance transaction contains a Router-owned successor
    /// whose refresh chain may be advanced during recovery. Fresh imports keep
    /// this false because the source remains owned by the vendor client.
    router_owned_candidate: bool,
}

/// Adopt an existing vendor login, when this invocation asked to.
///
/// `None` means no import was requested and the ordinary path should run.
pub async fn run_import(
    config: &link_assistant_router::config::Config,
    op: &AuthOp,
) -> Option<ExitCode> {
    let json = matches!(op, AuthOp::Import { json: true, .. });
    // Import writes this machine's credential home. When another router is the
    // target, doing that anyway produced an error naming the *local* home as
    // though it were the one asked about — a wrong-target action wearing an
    // answer that looks coherent (issue #291). Refuse before any local work.
    if let Some(failure) = refuse_a_remote_import(op).await {
        return Some(finish(&[ImportExecution::failed(None, failure)], json));
    }
    let policy = match op {
        AuthOp::Import {
            if_absent, force, ..
        } => ImportPolicy {
            if_absent: *if_absent,
            capability_asserted: *force,
            router_owned_candidate: false,
        },
        _ => ImportPolicy::default(),
    };
    let requested: Vec<(
        ImportProvider,
        String,
        Option<import_resume::ResumeCandidate>,
    )> = match op {
        AuthOp::Claude {
            from_claude_home: Some(source),
            ..
        } => vec![(ImportProvider::Claude, source.clone(), None)],
        AuthOp::Codex {
            from_codex_home: Some(source),
            ..
        } => vec![(ImportProvider::Codex, source.clone(), None)],
        AuthOp::Import {
            resume: Some(transaction_id),
            ..
        } => match import_resume::resolve_claimed(&config.data_dir, transaction_id).await {
            Ok(candidate) => vec![(
                candidate.provider,
                candidate.source.clone(),
                Some(candidate),
            )],
            Err(failure) => {
                return Some(finish(&[ImportExecution::failed(None, failure)], json));
            }
        },
        AuthOp::Import { all: true, .. } => [
            ImportProvider::Claude,
            ImportProvider::Codex,
            ImportProvider::Gemini,
            ImportProvider::Qwen,
            ImportProvider::Gh,
        ]
        .into_iter()
        .map(|provider| (provider, String::new(), None))
        .collect(),
        AuthOp::Import {
            provider: Some(provider),
            dir,
            ..
        } => vec![(*provider, dir.clone().unwrap_or_default(), None)],
        _ => return None,
    };
    // `--all` adopts what is there and reports what is not, rather than failing
    // on the first provider this machine never logged in to: a workstation with
    // two of five logins is the ordinary case, not an error.
    let adopting_everything = matches!(op, AuthOp::Import { all: true, .. });
    let mut executions = Vec::with_capacity(requested.len());
    for (provider, source, resumed) in requested {
        let outcome = match provider {
            ImportProvider::Gh if policy.if_absent => Err(ImportFailure::not_attempted(
                "--if-absent is supported only for Claude, Codex, Gemini, and Qwen; GitHub import keeps its existing replacement behavior",
            )),
            ImportProvider::Gh => import_github(&config.data_dir, &source)
                .map(|messages| ImportExecution::promoted("github", messages))
                .map_err(ImportFailure::not_attempted),
            other => {
                let Some(subscription) = subscription_of(other) else {
                    continue;
                };
                let mut provider_policy = policy;
                provider_policy.router_owned_candidate = resumed.is_some();
                if resumed.as_ref().is_some_and(|candidate| {
                    destination_has_receipt(config, subscription, &candidate.transaction_id)
                }) {
                    Ok(ImportExecution::promoted(
                        subscription.to_string(),
                        vec![format!(
                            "{subscription:<8} promotion was already committed; completing retained transaction cleanup"
                        )],
                    ))
                } else {
                    import_provider(
                        config,
                        subscription,
                        &source,
                        provider_policy,
                        resumed
                            .as_ref()
                            .map(|candidate| candidate.transaction_id.as_str()),
                    )
                    .await
                }
            }
        };
        let outcome = if let Some(candidate) = resumed.as_ref() {
            reconcile_resumed_import(candidate, outcome)
        } else {
            outcome
        };
        let execution = match outcome {
            Ok(execution) => execution,
            Err(failure) => {
                let absent = adopting_everything && failure.error.starts_with("no ");
                let message = absent.then(|| {
                    format!(
                        "{}: nothing to adopt ({})",
                        provider_label(provider),
                        failure.error
                    )
                });
                let execution = ImportExecution::failed(Some(provider_label(provider)), failure);
                if let Some(message) = message {
                    execution.ignore_failure(message)
                } else {
                    execution
                }
            }
        };
        executions.push(execution);
    }
    Some(finish(&executions, json))
}

/// A resume begins with an already uncertain transaction. Only promotion can
/// retire that uncertainty. A fresh uncertain retry replaces the predecessor
/// transaction; every other result keeps the original recovery ID authoritative.
fn reconcile_resumed_import(
    candidate: &import_resume::ResumeCandidate,
    outcome: Result<ImportExecution, ImportFailure>,
) -> Result<ImportExecution, ImportFailure> {
    match outcome {
        Ok(mut execution) if execution.is_promoted() => {
            if let Err(warning) = import_resume::retire(candidate) {
                execution.mark_cleanup_pending(
                    candidate.transaction_id.clone(),
                    format!("{warning}; retry this transaction ID to complete cleanup"),
                );
            }
            Ok(execution)
        }
        Ok(_) => Err(ImportFailure::retained(
            ImportPhase::Preflight,
            candidate.transaction_id.clone(),
            format!(
                "the destination is already present; retained import transaction {} still requires recovery",
                candidate.transaction_id
            ),
        )),
        Err(failure)
            if matches!(
                failure.outcome,
                ImportOutcome::ExchangeUncertain
                    | ImportOutcome::PersistenceUncertain
                    | ImportOutcome::SuccessorRetained
            ) =>
        {
            let _retired_predecessor = import_resume::retire(candidate);
            Err(failure)
        }
        Err(failure) => Err(ImportFailure::retained(
            failure.phase,
            candidate.transaction_id.clone(),
            format!(
                "{}; retained import transaction {} still requires recovery",
                failure.error, candidate.transaction_id
            ),
        )),
    }
}

/// Refuse an import aimed at a router other than this machine.
///
/// A credential can only be installed where the process running the import can
/// write, and a router reads its subscription credentials from its own home at
/// startup. Nothing accepts a credential document over HTTP — `/api/management/login`
/// begins an interactive OAuth flow and `submit_code` takes a short-lived
/// code, neither of which adopts a credential that already exists. So there is
/// no remote import to perform, and the honest move is to say so.
///
/// The alternative is what shipped: `--server` parsed and was discarded, and
/// the command answered about the local home. `error: claude is already read
/// from /Users/me/.claude` reads as a coherent reply to a question about the
/// selected server, which is worse than a plain refusal — the operator cannot
/// tell the target was never consulted (issue #291).
///
/// `--local` is the way to ask for this machine, and `--managed` is a local
/// disposable container, so both keep the ordinary path.
async fn refuse_a_remote_import(op: &AuthOp) -> Option<ImportFailure> {
    // Decided from the flags alone, so `--local` never contacts a server and
    // never fails because one is unreachable. The per-provider
    // `--from-*-home` flags carry no target and stay local, as they always
    // were.
    if !op.may_be_remote() {
        return None;
    }
    let AuthOp::Import { target, .. } = op else {
        return None;
    };
    let server = match link_assistant_router::auth_remote::target_for(
        target.local,
        target.managed,
        target.server.as_deref(),
        target.management_server.as_deref(),
    )
    .await
    {
        Ok(Some(server)) => server,
        Ok(None) => return None,
        Err(error) => {
            // An unreachable *named* target is an error in its own right;
            // falling back to a local import is the surprise being fixed.
            return Some(ImportFailure::not_attempted(error));
        }
    };
    // Name the directory the credential would have to land in, when the router
    // will say. "Not from here" alone leaves the operator to guess the next
    // step; the path is the instruction.
    let destination = match op {
        AuthOp::Import {
            provider: Some(provider),
            ..
        } => {
            link_assistant_router::auth_remote::credential_home(&server, provider_label(*provider))
                .await
        }
        _ => None,
    };
    let error = link_assistant_router::auth_remote::remote_import_refusal(
        &server.base_url,
        destination.as_deref(),
    )
    .join("\n");
    Some(ImportFailure::not_attempted(error))
}

/// The subscription an import target names, when it names one.
const fn subscription_of(provider: ImportProvider) -> Option<SubscriptionProvider> {
    match provider {
        ImportProvider::Claude => Some(SubscriptionProvider::Claude),
        ImportProvider::Codex => Some(SubscriptionProvider::Codex),
        ImportProvider::Gemini => Some(SubscriptionProvider::Gemini),
        ImportProvider::Qwen => Some(SubscriptionProvider::Qwen),
        ImportProvider::Gh => None,
    }
}

/// How an import target names itself in a report.
const fn provider_label(provider: ImportProvider) -> &'static str {
    match provider {
        ImportProvider::Claude => "claude",
        ImportProvider::Codex => "codex",
        ImportProvider::Gemini => "gemini",
        ImportProvider::Qwen => "qwen",
        ImportProvider::Gh => "github",
    }
}

/// Adopt the GitHub credential a `gh` login already holds.
///
/// Shares `run_gh`'s reader so the two spellings cannot drift, and reports in
/// the same column format the subscription imports use.
fn import_github(data_dir: &std::path::Path, source: &str) -> Result<Vec<String>, String> {
    use link_assistant_router::github_proxy;

    let directory = Some(source)
        .filter(|source| !source.trim().is_empty())
        .map(std::path::PathBuf::from)
        .or_else(github_proxy::gh_config_directory)
        .ok_or_else(|| {
            String::from("no gh configuration directory; name one, or set GH_CONFIG_DIR")
        })?;
    let host = github_proxy::configured_credential_host()
        .ok_or_else(|| String::from("GITHUB_PROXY_BASE_URL does not name a valid GitHub host"))?;
    let token = github_proxy::token_from_gh_config(&directory, &host).ok_or_else(|| {
        format!(
            "no GitHub credential for {host} in {}; run `gh auth login --hostname {host}` there first",
            directory.display(),
        )
    })?;
    let path = github_proxy::store_credential(data_dir, &token)?;
    let mut messages = vec![format!(
        "github   imported {} from {}",
        path.display(),
        directory.display()
    )];
    // The GitHub routes are decided at startup from whether a credential
    // exists, so adopting one mid-run does not mount them.
    messages.push(
        "github   note: the GitHub routes are mounted at startup; restart to serve them"
            .to_string(),
    );
    Ok(messages)
}

/// Adopt a vendor credential into this deployment's home, and say what it is.
async fn import_provider(
    config: &link_assistant_router::config::Config,
    provider: SubscriptionProvider,
    source: &str,
    policy: ImportPolicy,
    resumed_transaction_id: Option<&str>,
) -> Result<ImportExecution, ImportFailure> {
    let user_home = config.client_home.to_string_lossy().into_owned();
    let destination_home = provider_home(config, provider, &user_home);
    let catalog_base_url_override = import_catalog_base_url_override();
    import_provider_with_paths(
        &config.data_dir,
        &user_home,
        &destination_home,
        provider,
        source,
        policy,
        resumed_transaction_id,
        catalog_base_url_override.as_deref(),
    )
    .await
}

fn import_catalog_base_url_override() -> Option<String> {
    #[cfg(debug_assertions)]
    {
        std::env::var("LINK_ASSISTANT_ROUTER_TEST_CATALOG_BASE_URL")
            .ok()
            .filter(|value| !value.trim().is_empty())
    }
    #[cfg(not(debug_assertions))]
    {
        None
    }
}

#[allow(clippy::too_many_arguments)]
async fn import_provider_with_paths(
    data_dir: &std::path::Path,
    user_home: &str,
    destination_home: &std::path::Path,
    provider: SubscriptionProvider,
    source: &str,
    policy: ImportPolicy,
    resumed_transaction_id: Option<&str>,
    catalog_base_url_override: Option<&str>,
) -> Result<ImportExecution, ImportFailure> {
    // An empty value asks for the vendor's own default location.
    //
    // Deliberately not `resolve_home`, which honours `CLAUDE_CODE_HOME` and
    // friends — in a deployment those name the router's *destination*, so
    // resolving the source that way makes every unqualified import refuse
    // itself as a self-import (issue #278). The vendor's conventional home is
    // the thing an operator means by "the login this machine already has".
    let source_home = if source.trim().is_empty() {
        provider.conventional_home(user_home)
    } else {
        std::path::PathBuf::from(source)
    };
    if same_credential_home(&source_home, destination_home) {
        // A deployment that reads the vendor's own home already holds whatever
        // is there; there is nothing to copy, and copying a file onto itself
        // would truncate it.
        return Err(ImportFailure::not_attempted(format!(
            "{provider} is already read from {}, so there is nothing to adopt",
            destination_home.display()
        )));
    }

    let destination = SubscriptionReader::new(provider, destination_home);
    // Conditional provisioning must win without even reading a malformed or
    // externally owned source. Installation repeats the same check after the
    // catalog request while holding the destination transaction lock.
    if policy.if_absent && destination.has_platform_store_credential() {
        return Ok(ImportExecution::already_present(
            provider.to_string(),
            vec![format!(
                "{provider:<8} already present in the platform credential store; the candidate was not read, validated, or installed"
            )],
        ));
    }
    if policy.if_absent
        && let Some(path) = destination
            .existing_document_locked(
                data_dir,
                link_assistant_router::credential_recovery_store::PRIMARY_ACCOUNT,
            )
            .await
            .map_err(ImportFailure::not_attempted)?
    {
        return Ok(ImportExecution::already_present(
            provider.to_string(),
            vec![format!(
                "{provider:<8} already present at {}; the candidate was not read, validated, or installed",
                path.display()
            )],
        ));
    }

    let from = SubscriptionReader::new(provider, &source_home);
    // One selection yields the bytes, their verdict, and their origin. Reading
    // the source a second time to describe it is what let the report and the
    // installed credential name different things (issue #280).
    let source_credential = from.read_document_for_import().map_err(|error| {
        ImportFailure::not_attempted(match error {
            link_assistant_router::subscription::SubscriptionError::NoCredentials(message) => {
                format!("no {provider} credential to import: {message}")
            }
            other => format!("invalid {provider} candidate credential: {other}"),
        })
    })?;
    let ImportSource {
        document,
        token: _,
        origin,
        path,
    } = source_credential;
    let where_from = match origin {
        link_assistant_router::platform_keychain::Origin::Keychain => {
            link_assistant_router::platform_keychain::service_name(provider).map_or_else(
                || String::from("the platform keychain"),
                |service| format!("keychain {service:?}"),
            )
        }
        link_assistant_router::platform_keychain::Origin::File
        | link_assistant_router::platform_keychain::Origin::ExternalFile
        | link_assistant_router::platform_keychain::Origin::AdoptedFile => {
            path.as_ref().map_or_else(
                || source_home.display().to_string(),
                |path| path.display().to_string(),
            )
        }
    };
    let external_source = if policy.router_owned_candidate {
        None
    } else {
        Some(prepare_external_source(
            provider,
            origin,
            path.as_deref(),
            &destination,
        )?)
    };

    // A fresh import validates only the current access token. Redeeming its
    // refresh token would invalidate the vendor client's copy before Router
    // had installed anything. Only a claimed Router-owned recovery transaction
    // may advance its own chain here.
    let validated = validate_candidate_at(
        data_dir,
        provider,
        &document,
        policy.router_owned_candidate,
        None,
        catalog_base_url_override,
    )
    .await?;
    let report = describe_credential(validated.token());
    if (policy.if_absent && destination.has_platform_store_credential())
        || (!policy.if_absent
            && destination.candidate_is_shadowed_by_platform_store(validated.token()))
    {
        let error = format!(
            "the {provider} platform credential remains authoritative; the external source was not installed"
        );
        if policy.router_owned_candidate {
            return Err(retain_validated_candidate(
                validated,
                ImportPhase::Promotion,
                error,
            ));
        }
        drop(validated);
        return Err(ImportFailure::safe_failure(ImportPhase::Promotion, error));
    }
    let receipt_id = resumed_transaction_id
        .unwrap_or_else(|| validated.transaction_id())
        .to_string();
    let promotion_document = match external_source.as_ref().map_or_else(
        || {
            link_assistant_router::subscription::mark_promotion_receipt(
                validated.document(),
                &receipt_id,
            )
        },
        |source| {
            link_assistant_router::subscription::reference_external_credential(source, &receipt_id)
        },
    ) {
        Ok(document) => document,
        Err(error) => {
            if policy.router_owned_candidate {
                return Err(retain_validated_candidate(
                    validated,
                    ImportPhase::Promotion,
                    error,
                ));
            }
            drop(validated);
            return Err(ImportFailure::safe_failure(ImportPhase::Promotion, error));
        }
    };
    let promotion = install_candidate(
        &destination,
        data_dir,
        &promotion_document,
        CredentialProbe::Accepted,
        policy,
    )
    .await;
    let installed = match promotion {
        Ok(installed) => installed,
        Err(_error) if destination_has_receipt_at(&destination, &receipt_id) => {
            let path = destination.discover_credential_path().ok_or_else(|| {
                ImportFailure::safe_failure(
                    ImportPhase::Promotion,
                    format!("the committed {provider} credential could not be located"),
                )
            })?;
            InstallDocumentResult::Installed(path)
        }
        Err(error) => {
            if policy.router_owned_candidate {
                return Err(retain_validated_candidate(
                    validated,
                    ImportPhase::Promotion,
                    error,
                ));
            }
            drop(validated);
            return Err(ImportFailure::safe_failure(ImportPhase::Promotion, error));
        }
    };
    let execution = match installed {
        InstallDocumentResult::Installed(path) => {
            let messages = vec![
                format!(
                    "{provider:<8} imported {} from {where_from}",
                    path.display()
                ),
                external_source.as_ref().map_or_else(
                    || format!(
                        "{provider:<8} candidate {report}, Router-owned refresh chain validated and promoted"
                    ),
                    |source| format!(
                        "{provider:<8} candidate {report}, current access accepted without OAuth exchange; Router and the vendor client share the authoritative file at {}",
                        source.display()
                    ),
                ),
            ];
            // The isolated validation copy is never authoritative. A fresh
            // import leaves the complete bytes at the vendor source; a resumed
            // transaction has copied them into the destination above.
            drop(validated);
            ImportExecution::promoted(provider.to_string(), messages)
        }
        InstallDocumentResult::AlreadyPresent(path) => {
            if !policy.router_owned_candidate {
                drop(validated);
                return Ok(ImportExecution::already_present(
                    provider.to_string(),
                    vec![format!(
                        "{provider:<8} already present at {}; the external candidate from {where_from} was validated but not installed",
                        path.display()
                    )],
                ));
            }
            return Err(retain_validated_candidate(
                validated,
                ImportPhase::Promotion,
                format!(
                    "a credential appeared at {}; the validated {provider} successor from {where_from} was retained for recovery",
                    path.display()
                ),
            ));
        }
    };
    Ok(execution)
}

fn prepare_external_source(
    provider: SubscriptionProvider,
    origin: link_assistant_router::platform_keychain::Origin,
    path: Option<&std::path::Path>,
    destination: &SubscriptionReader,
) -> Result<std::path::PathBuf, ImportFailure> {
    if origin == link_assistant_router::platform_keychain::Origin::Keychain {
        return Err(ImportFailure::not_attempted(format!(
            "the selected {provider} credential exists only in the platform keychain; let the vendor client expose a current writable credential file before import"
        )));
    }
    if origin == link_assistant_router::platform_keychain::Origin::ExternalFile {
        return Err(ImportFailure::not_attempted(format!(
            "the selected {provider} credential is externally owned but does not identify its authoritative writable source"
        )));
    }
    let path = path.ok_or_else(|| {
        ImportFailure::not_attempted(format!(
            "the selected {provider} credential has no authoritative writable source file"
        ))
    })?;
    let source = std::fs::canonicalize(path).map_err(|_| {
        ImportFailure::not_attempted(format!(
            "the selected {provider} credential source is not a readable file"
        ))
    })?;
    if destination
        .credential_paths()
        .iter()
        .filter_map(|candidate| std::fs::canonicalize(candidate).ok())
        .any(|candidate| candidate == source)
    {
        return Err(ImportFailure::not_attempted(format!(
            "the selected {provider} source is also a Router destination credential"
        )));
    }
    let parent = source.parent().ok_or_else(|| {
        ImportFailure::not_attempted(format!(
            "the selected {provider} credential source has no writable directory"
        ))
    })?;
    let probe = tempfile::Builder::new()
        .prefix(".router-import-write-check-")
        .tempfile_in(parent)
        .map_err(|_| {
            ImportFailure::not_attempted(format!(
                "the selected {provider} credential source cannot be replaced atomically; make its directory writable before import"
            ))
        })?;
    probe.as_file().sync_all().map_err(|_| {
        ImportFailure::not_attempted(format!(
            "the selected {provider} credential source cannot be persisted durably"
        ))
    })?;
    probe.close().map_err(|_| {
        ImportFailure::not_attempted(format!(
            "the selected {provider} credential source write check could not be cleaned up"
        ))
    })?;
    Ok(source)
}

fn destination_has_receipt(
    config: &link_assistant_router::config::Config,
    provider: SubscriptionProvider,
    transaction_id: &str,
) -> bool {
    let user_home = config.client_home.to_string_lossy().into_owned();
    let destination =
        SubscriptionReader::new(provider, provider_home(config, provider, &user_home));
    destination_has_receipt_at(&destination, transaction_id)
}

fn destination_has_receipt_at(destination: &SubscriptionReader, transaction_id: &str) -> bool {
    destination
        .discover_credential_path()
        .and_then(|path| std::fs::read_to_string(path).ok())
        .is_some_and(|document| {
            link_assistant_router::subscription::has_promotion_receipt(&document, transaction_id)
        })
}

async fn validate_candidate_at(
    data_dir: &std::path::Path,
    provider: SubscriptionProvider,
    document: &str,
    rotate_candidate: bool,
    token_url_override: Option<&str>,
    catalog_base_url_override: Option<&str>,
) -> Result<ValidatedCandidate, ImportFailure> {
    let accepted = if rotate_candidate {
        link_assistant_router::credential_acceptance::accept_candidate(
            data_dir,
            provider,
            document,
            token_url_override,
            catalog_base_url_override,
        )
        .await
    } else {
        link_assistant_router::credential_acceptance::accept_external_candidate(
            data_dir,
            provider,
            document,
            catalog_base_url_override,
        )
        .await
    };
    accepted.map_err(|failure| ImportFailure::from_acceptance(&failure))
}

fn retain_validated_candidate(
    validated: ValidatedCandidate,
    phase: ImportPhase,
    error: String,
) -> ImportFailure {
    let transaction_id = validated.transaction_id().to_string();
    std::mem::forget(validated);
    ImportFailure::retained(phase, transaction_id, error)
}

fn same_credential_home(source: &std::path::Path, destination: &std::path::Path) -> bool {
    if source == destination {
        return true;
    }
    match (
        std::fs::canonicalize(source),
        std::fs::canonicalize(destination),
    ) {
        (Ok(source), Ok(destination)) => source == destination,
        _ => false,
    }
}

/// Validate a credential in a Router-owned store that is isolated from the
/// serving destination.
///
/// Endpoint overrides exist only so the unit matrix can exercise the exact
/// four vendor layouts and request order against a loopback vendor. Production
/// always uses the provider's public OAuth endpoint and a Router-validated
/// catalog origin; a candidate-controlled `resource_url` can therefore never
/// send the refreshed bearer token outside the vendor allowlist.
#[cfg(test)]
async fn validate_candidate_with(
    data_dir: &std::path::Path,
    provider: SubscriptionProvider,
    document: &str,
    token_url_override: Option<&str>,
    catalog_base_url_override: Option<&str>,
) -> Result<ValidatedCandidate, ImportFailure> {
    validate_candidate_at(
        data_dir,
        provider,
        document,
        true,
        token_url_override,
        catalog_base_url_override,
    )
    .await
}

/// Enforce candidate acceptance policy, then enter the shared writer boundary.
async fn install_candidate(
    destination: &SubscriptionReader,
    data_dir: &std::path::Path,
    document: &str,
    probe: CredentialProbe,
    policy: ImportPolicy,
) -> Result<InstallDocumentResult, String> {
    if policy.capability_asserted {
        tracing::debug!("caller asserted safe-refresh-chain-import-v1");
    }
    let refusal = (probe != CredentialProbe::Accepted).then(|| {
        format!(
            "{} candidate was not accepted by the vendor and cannot be installed",
            destination.provider()
        )
    });
    if !policy.if_absent
        && let Some(error) = refusal
    {
        return Err(error);
    }
    let mode = if policy.if_absent {
        InstallMode::IfAbsent
    } else {
        InstallMode::Replace
    };
    destination
        .install_document_locked_with_refusal(
            data_dir,
            link_assistant_router::credential_recovery_store::PRIMARY_ACCOUNT,
            document,
            mode,
            refusal,
        )
        .await
}

/// What an operator needs to know about a credential at import time.
pub fn describe_credential(
    token: &link_assistant_router::subscription::SubscriptionToken,
) -> String {
    let now = chrono::Utc::now().timestamp_millis();
    let expiry = token.expires_at_ms.map_or_else(
        || String::from("no recorded expiry"),
        |expires_at| {
            let minutes = (expires_at - now) / 60_000;
            if expires_at <= now {
                format!("EXPIRED {} ago", humanize_minutes(-minutes))
            } else {
                format!("expires in {}", humanize_minutes(minutes))
            }
        },
    );
    // Without a refresh token the credential cannot be rotated, so it stops
    // working at expiry and no recovery rung can save it. Worth saying plainly.
    let refresh = if token.refresh_token.is_some() {
        "refresh token present"
    } else {
        "NO refresh token, so it cannot be renewed"
    };
    format!("{expiry}, {refresh}")
}

/// A duration an operator reads at a glance.
///
/// Truncating to whole hours reported a credential with 119 minutes left as
/// "1 hours", which understates it enough to matter when the question being
/// asked is whether to re-authenticate now.
pub fn humanize_minutes(minutes: i64) -> String {
    if minutes < 90 {
        return format!("{minutes} minutes");
    }
    let hours = minutes / 60;
    if hours < 48 {
        return format!("{hours} hours");
    }
    format!("{} days", hours / 24)
}

/// The credential home this deployment reads `provider` from.
pub fn provider_home(
    config: &link_assistant_router::config::Config,
    provider: SubscriptionProvider,
    _user_home: &str,
) -> std::path::PathBuf {
    config.credential_home(provider)
}

#[cfg(test)]
#[path = "auth_import_tests.rs"]
mod tests;