torii-lib 0.10.0

Domain library of the torii git client — VCS operations, platform clients (GitHub/GitLab/Gitea/…), workspaces, config and auth. No CLI/TUI. Part of the Gitorii ecosystem (gitorii.com · torii.sh).
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
//! Credential storage for torii — both the gitorii.com cloud API key
//! and the per-platform tokens (GitHub, GitLab, Gitea, Forgejo,
//! Codeberg, crates.io) that the HTTPS transport and platform APIs use.
//!
//! Storage layout (`~/.config/torii/auth.toml`, chmod 600 on Unix):
//!
//! ```toml
//! [cloud]
//! key = "gitorii_sk_…"
//! endpoint = "https://api.gitorii.com"
//!
//! [tokens]
//! github = "ghp_…"
//! gitlab = "glpat-…"
//! gitea = "…"
//! forgejo = "…"
//! codeberg = "…"
//! cargo = "cio_…"
//! ```
//!
//! For backwards compatibility we also read the legacy formats:
//!
//! - `auth.toml` with `key = …` / `endpoint = …` at the top level (the
//!   pre-0.7.1 cloud-only format) — auto-rewrites to the new sectioned
//!   format on the next save.
//! - `config.toml`'s `[auth]` block (where platform tokens used to live)
//!   — also auto-migrated to `auth.toml [tokens]` on the next mutating
//!   call.
//!
//! Token precedence (resolved by [`resolve_token`]):
//!
//! 1. Provider-specific env var (`GITHUB_TOKEN`/`GH_TOKEN`,
//!    `GITLAB_TOKEN`, `CARGO_REGISTRY_TOKEN`, …)
//! 2. Generic env var `TORII_HTTPS_TOKEN`
//! 3. Local repo config (`<repo>/.torii/auth.toml`, same schema as
//!    global)
//! 4. Global config (`~/.config/torii/auth.toml`)
//!
//! Env var `TORII_API_KEY` overrides the cloud key the same way.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::error::{Result, ToriiError};

const CLOUD_ENV_VAR: &str = "TORII_API_KEY";
const FILE_NAME: &str = "auth.toml";

// -- Public types -----------------------------------------------------------

#[derive(Debug, Clone, Default)]
pub struct ApiKey {
    pub key: String,
    pub endpoint: String,
}

/// Every credential torii knows about, in one struct. `tokens` is a
/// map rather than fixed fields so `auth.toml` can keep older or
/// newer entries without parser breakage when we add providers.
///
/// 0.7.25 added `expirations`: optional ISO-8601 timestamps recorded
/// when a token was minted with a TTL. The expirations table is
/// purely advisory — torii doesn't auto-rotate; `auth doctor` reads
/// the timestamps to warn the user when a token is close to expiring
/// and they should run `torii auth rotate <provider>`.
#[derive(Debug, Clone, Default)]
pub struct AuthStore {
    pub cloud: Option<ApiKey>,
    pub tokens: BTreeMap<String, String>,
    pub expirations: BTreeMap<String, String>,
    /// 0.7.39 — refresh tokens issued by OAuth device flow. Lets
    /// `resolve_token` quietly mint a fresh `access_token` when one
    /// is close to expiry, instead of forcing the user to re-run
    /// `auth oauth <provider>`. Persisted under a `[token_refresh]`
    /// table in `auth.toml`. Empty for providers that don't issue
    /// refresh tokens (GitHub OAuth Apps).
    pub refresh_tokens: BTreeMap<String, String>,
}

/// Recognised provider names. The CLI accepts these; readers ask by
/// the same string. Add new entries here only — every other module
/// looks them up by name.
pub const PROVIDERS: &[&str] = &[
    "github",
    "gitlab",
    "gitea",
    "forgejo",
    "codeberg",
    "bitbucket",
    "sourcehut",
    "azure",      // 0.7.18 — Azure DevOps Repos / Pipelines / Releases / Artifacts
    "cargo",
];

// -- Default endpoint for cloud --------------------------------------------

pub fn default_endpoint() -> String {
    std::env::var("TORII_API_ENDPOINT")
        .unwrap_or_else(|_| "https://api.gitorii.com".to_string())
}

// -- Paths -----------------------------------------------------------------

fn global_path() -> Option<PathBuf> {
    dirs::config_dir().map(|d| d.join("torii").join(FILE_NAME))
}

fn local_path<P: AsRef<Path>>(repo_path: P) -> PathBuf {
    repo_path.as_ref().join(".torii").join(FILE_NAME)
}

// -- Load -------------------------------------------------------------------

/// Read the cloud API key (env wins).
pub fn load() -> Option<ApiKey> {
    if let Ok(env_key) = std::env::var(CLOUD_ENV_VAR) {
        if !env_key.is_empty() {
            return Some(ApiKey {
                key: env_key,
                endpoint: default_endpoint(),
            });
        }
    }
    load_global().cloud
}

/// Read the whole global store from disk (no env override applied —
/// that's [`load`] / [`resolve_token`]'s job).
pub fn load_global() -> AuthStore {
    let Some(path) = global_path() else {
        return AuthStore::default();
    };
    if !path.exists() {
        // Fallback: try migrating the legacy `[auth]` block from
        // `config.toml` so the user doesn't lose tokens after upgrade.
        return migrate_from_config_toml().unwrap_or_default();
    }
    let text = match fs::read_to_string(&path) {
        Ok(t) => t,
        Err(_) => return AuthStore::default(),
    };
    parse(&text)
}

/// Read a local (per-repo) store. Returns empty if the repo has no
/// `.torii/auth.toml`. **Never** falls back to global — that's the
/// merge step's job ([`resolve_token`]).
pub fn load_local_raw<P: AsRef<Path>>(repo_path: P) -> AuthStore {
    let path = local_path(repo_path);
    if !path.exists() {
        return AuthStore::default();
    }
    let text = match fs::read_to_string(&path) {
        Ok(t) => t,
        Err(_) => return AuthStore::default(),
    };
    parse(&text)
}

// -- Save -------------------------------------------------------------------

/// Persist a store to disk with chmod 600 on Unix.
fn save_to(path: &Path, store: &AuthStore) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| ToriiError::Fs(format!("create dir: {}", e)))?;
    }
    let mut out = String::new();
    out.push_str("# torii credentials — managed by 'torii auth …'. Do not share.\n\n");
    if let Some(cloud) = &store.cloud {
        out.push_str("[cloud]\n");
        out.push_str(&format!("key = \"{}\"\n", cloud.key));
        out.push_str(&format!("endpoint = \"{}\"\n\n", cloud.endpoint));
    }
    if !store.tokens.is_empty() {
        out.push_str("[tokens]\n");
        for (k, v) in &store.tokens {
            out.push_str(&format!("{} = \"{}\"\n", k, v));
        }
        out.push('\n');
    }
    if !store.expirations.is_empty() {
        out.push_str("[token_expires]\n");
        for (k, v) in &store.expirations {
            out.push_str(&format!("{} = \"{}\"\n", k, v));
        }
        out.push('\n');
    }
    if !store.refresh_tokens.is_empty() {
        out.push_str("[token_refresh]\n");
        for (k, v) in &store.refresh_tokens {
            out.push_str(&format!("{} = \"{}\"\n", k, v));
        }
    }
    fs::write(path, out)
        .map_err(|e| ToriiError::Fs(format!("write {}: {}", path.display(), e)))?;
    restrict_permissions(path);
    Ok(())
}

pub fn save_global(store: &AuthStore) -> Result<()> {
    let path = global_path()
        .ok_or_else(|| ToriiError::InvalidConfig("could not resolve config dir".to_string()))?;
    save_to(&path, store)
}

pub fn save_local<P: AsRef<Path>>(repo_path: P, store: &AuthStore) -> Result<()> {
    let path = local_path(repo_path);
    save_to(&path, store)
}

/// Persist a cloud key — kept as a back-compat shim for `torii auth login`
/// callers that don't know about the wider store yet.
pub fn save_cloud(key: &str, endpoint: &str) -> Result<()> {
    let mut store = load_global();
    store.cloud = Some(ApiKey {
        key: key.to_string(),
        endpoint: endpoint.to_string(),
    });
    save_global(&store)
}

/// Delete just the cloud entry (preserves platform tokens).
pub fn delete() -> Result<()> {
    let mut store = load_global();
    store.cloud = None;
    if store.tokens.is_empty() {
        // Whole file was just the cloud key — remove it entirely.
        if let Some(path) = global_path() {
            if path.exists() {
                fs::remove_file(&path).map_err(|e| {
                    ToriiError::Fs(format!("remove {}: {}", path.display(), e))
                })?;
            }
        }
        return Ok(());
    }
    save_global(&store)
}

// -- Token mutation ---------------------------------------------------------

/// Validate the provider name against the known list. Case-insensitive
/// match; returns the canonical lowercase form.
pub fn normalise_provider(name: &str) -> Result<String> {
    let lc = name.to_lowercase();
    if PROVIDERS.iter().any(|p| **p == lc) {
        Ok(lc)
    } else {
        Err(ToriiError::Usage(format!(
            "unknown provider '{}'. Known: {}",
            name,
            PROVIDERS.join(", ")
        )))
    }
}

pub fn set_token(provider: &str, token: &str, local: Option<&Path>) -> Result<()> {
    set_token_with_expiry(provider, token, None, local)
}

/// Same as [`set_token`], plus an optional ISO-8601 expiration
/// timestamp. Stored under `[token_expires]` and surfaced by
/// `torii auth doctor` as a "rotate before X" warning. Passing
/// `None` clears any existing expiration entry for the provider
/// (e.g. switching from a TTL-managed PAT to a stable bot token).
pub fn set_token_with_expiry(
    provider: &str,
    token: &str,
    expires_at: Option<&str>,
    local: Option<&Path>,
) -> Result<()> {
    let provider = normalise_provider(provider)?;
    let result = if let Some(repo) = local {
        let mut store = load_local_raw(repo);
        store.tokens.insert(provider.clone(), token.to_string());
        apply_expiry(&mut store.expirations, &provider, expires_at);
        save_local(repo, &store)
    } else {
        let mut store = load_global();
        store.tokens.insert(provider.clone(), token.to_string());
        apply_expiry(&mut store.expirations, &provider, expires_at);
        save_global(&store)
    };
    invalidate_token_cache();
    result
}

/// 0.7.39 — store `access_token` + `refresh_token` + an `expires_at`
/// derived from `expires_in`. Called by the OAuth worker so the next
/// `resolve_token` can auto-refresh transparently. `local` is always
/// `None` here because refresh tokens are user-scoped, not repo-
/// scoped.
pub fn set_token_with_refresh(
    provider: &str,
    access_token: &str,
    refresh_token: Option<&str>,
    expires_in_seconds: Option<u64>,
) -> Result<()> {
    let provider = normalise_provider(provider)?;
    let expires_at = expires_in_seconds.map(|s| {
        let when = chrono::Utc::now() + chrono::Duration::seconds(s as i64);
        when.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
    });
    let mut store = load_global();
    store.tokens.insert(provider.clone(), access_token.to_string());
    apply_expiry(&mut store.expirations, &provider, expires_at.as_deref());
    if let Some(r) = refresh_token {
        store.refresh_tokens.insert(provider.clone(), r.to_string());
    }
    save_global(&store)?;
    invalidate_token_cache();
    Ok(())
}

/// 0.7.39 — best-effort auto-refresh. Returns Ok(true) if a refresh
/// actually happened (new access token persisted, cache cleared),
/// Ok(false) if nothing was due, Err on real errors. Safe to call
/// from any path; failures are non-fatal (the caller still sees the
/// stale token and the platform will return 401 if it's expired,
/// at which point a manual re-auth is the answer).
pub fn refresh_if_needed(provider: &str) -> Result<bool> {
    let provider_lc = provider.to_lowercase();
    let store = load_global();
    let Some(refresh) = store.refresh_tokens.get(&provider_lc).cloned() else {
        return Ok(false);
    };
    // Only refresh when within 5 minutes of expiry. Earlier than
    // that and we waste round-trips; later than that and the platform
    // may already be rejecting.
    let due = store.expirations.get(&provider_lc)
        .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
        .map(|when| {
            let now = chrono::Utc::now();
            when.with_timezone(&chrono::Utc) - now < chrono::Duration::minutes(5)
        })
        .unwrap_or(false);
    if !due { return Ok(false); }

    let (new_access, new_refresh, expires_in) =
        crate::oauth::refresh_access_token(&provider_lc, &refresh)?;
    set_token_with_refresh(
        &provider_lc,
        &new_access,
        new_refresh.as_deref().or(Some(&refresh)),
        expires_in,
    )?;
    Ok(true)
}

fn apply_expiry(map: &mut BTreeMap<String, String>, provider: &str, expires_at: Option<&str>) {
    match expires_at {
        Some(s) if !s.is_empty() => { map.insert(provider.to_string(), s.to_string()); }
        _ => { map.remove(provider); }
    }
}

/// Return the recorded expiration timestamp for `provider`, if any.
/// Reads global only — the same precedence as `resolve_token` would
/// be misleading for expirations (a local override of the token
/// usually means the local one has its own TTL semantics).
pub fn token_expires_at(provider: &str) -> Option<String> {
    let store = load_global();
    store.expirations.get(&provider.to_lowercase()).cloned()
}

pub fn remove_token(provider: &str, local: Option<&Path>) -> Result<bool> {
    let provider = normalise_provider(provider)?;
    let removed = if let Some(repo) = local {
        let mut store = load_local_raw(repo);
        let r = store.tokens.remove(&provider).is_some();
        store.expirations.remove(&provider);
        save_local(repo, &store)?;
        r
    } else {
        let mut store = load_global();
        let r = store.tokens.remove(&provider).is_some();
        store.expirations.remove(&provider);
        save_global(&store)?;
        r
    };
    invalidate_token_cache();
    Ok(removed)
}

// -- The big one: token resolution -----------------------------------------

/// Where a token came from, surfaced by `torii auth doctor`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenSource {
    EnvVar(&'static str),
    EnvGeneric,
    Local,
    Global,
    Missing,
}

#[derive(Debug, Clone)]
pub struct ResolvedToken {
    /// Provider this token resolves for. Currently informational only —
    /// kept on the public type so consumers (CLI doctor output, future
    /// audit logs) can use it without forcing a recompile.
    #[allow(dead_code)]
    pub provider: String,
    pub value: Option<String>,
    pub source: TokenSource,
}

/// Look up a token using the documented precedence:
/// env-per-host > env generic > local config > global config > none.
///
// In-process cache for resolve_token results. Many CLI flows resolve
// the same token N times (workspace status across M repos × P
// platforms = N*M*P file reads). Caching is safe because a single
// `torii ...` invocation is short-lived and config rarely changes
// mid-run; the few mutating commands (`set_token`, `remove_token`)
// invalidate the cache below.
fn token_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, ResolvedToken>> {
    static CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, ResolvedToken>>> = std::sync::OnceLock::new();
    CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}

fn invalidate_token_cache() {
    if let Ok(mut g) = token_cache().lock() {
        g.clear();
    }
}

/// Public variant used by callers that mutated `auth.toml` out-of-band
/// (e.g. the TUI's auth ops spawn a child process via `torii auth
/// oauth …` — the child invalidates its own cache when it calls
/// `set_token`, but the parent TUI has no way of knowing that
/// without an explicit cue). Call this after any operation that
/// could have changed a token outside this process.
pub fn drop_token_cache() {
    invalidate_token_cache();
}

/// `repo_path` is the path to the repo (`.` is usually fine); pass it
/// even when you don't expect a local override, the local lookup is
/// cheap when the file doesn't exist.
///
/// Results are cached in-process per `(provider, repo_path)` to avoid
/// re-reading the global / local TOML on every platform-client
/// construction. `set_token` and `remove_token` invalidate the cache.
pub fn resolve_token<P: AsRef<Path>>(provider: &str, repo_path: P) -> ResolvedToken {
    // 0.7.39 — best-effort proactive refresh BEFORE we serve any
    // cached value. `refresh_if_needed` is a no-op when the provider
    // has no refresh token or when the access token isn't close to
    // expiry; it logs nothing. If a refresh happened it also
    // clears the cache, so the lookup below picks up the fresh
    // value transparently. Network errors here are swallowed: the
    // resolver still returns the stale token and the API call's
    // own error path decides what to do with the 401 that follows.
    let _ = refresh_if_needed(provider);

    let key = format!("{}|{}", provider.to_lowercase(), repo_path.as_ref().display());
    if let Ok(g) = token_cache().lock() {
        if let Some(hit) = g.get(&key) {
            return hit.clone();
        }
    }
    let result = resolve_token_uncached(provider, repo_path);
    if let Ok(mut g) = token_cache().lock() {
        g.insert(key, result.clone());
    }
    result
}

fn resolve_token_uncached<P: AsRef<Path>>(provider: &str, repo_path: P) -> ResolvedToken {
    let provider_lc = provider.to_lowercase();

    // 1. Per-provider env vars.
    for env_name in env_vars_for(&provider_lc) {
        if let Ok(v) = std::env::var(env_name) {
            if !v.is_empty() {
                return ResolvedToken {
                    provider: provider_lc,
                    value: Some(v),
                    source: TokenSource::EnvVar(env_name),
                };
            }
        }
    }

    // 2. Generic env var (TORII_HTTPS_TOKEN) — matches existing transport.
    if let Ok(v) = std::env::var("TORII_HTTPS_TOKEN") {
        if !v.is_empty() {
            return ResolvedToken {
                provider: provider_lc,
                value: Some(v),
                source: TokenSource::EnvGeneric,
            };
        }
    }

    // 3. Local (per-repo) store.
    let local = load_local_raw(repo_path);
    if let Some(v) = local.tokens.get(&provider_lc) {
        if !v.is_empty() {
            return ResolvedToken {
                provider: provider_lc,
                value: Some(v.clone()),
                source: TokenSource::Local,
            };
        }
    }

    // 4. Global store.
    let global = load_global();
    if let Some(v) = global.tokens.get(&provider_lc) {
        if !v.is_empty() {
            return ResolvedToken {
                provider: provider_lc,
                value: Some(v.clone()),
                source: TokenSource::Global,
            };
        }
    }

    ResolvedToken {
        provider: provider_lc,
        value: None,
        source: TokenSource::Missing,
    }
}

/// Env var names checked for each provider, in order. Order matters
/// because `gh` and GitHub's own CI use `GH_TOKEN` interchangeably with
/// `GITHUB_TOKEN`; we accept both.
fn env_vars_for(provider: &str) -> &'static [&'static str] {
    match provider {
        "github" => &["GITHUB_TOKEN", "GH_TOKEN"],
        "gitlab" => &["GITLAB_TOKEN", "GL_TOKEN"],
        "gitea" => &["GITEA_TOKEN"],
        "forgejo" => &["FORGEJO_TOKEN"],
        "codeberg" => &["CODEBERG_TOKEN"],
        "bitbucket" => &["BITBUCKET_TOKEN"],
        "azure"     => &["AZURE_DEVOPS_TOKEN", "AZURE_DEVOPS_EXT_PAT", "AZDO_TOKEN"],
        "sourcehut" => &["SOURCEHUT_TOKEN", "SRHT_TOKEN"],
        "cargo" => &["CARGO_REGISTRY_TOKEN"],
        _ => &[],
    }
}

// -- Parser -----------------------------------------------------------------

/// Parse the on-disk format. Accepts both the new sectioned form and
/// the pre-0.7.1 cloud-only form (bare `key = …`/`endpoint = …`).
fn parse(text: &str) -> AuthStore {
    enum Section {
        TopLevel,
        Cloud,
        Tokens,
        TokenExpires,
        TokenRefresh,
    }
    let mut section = Section::TopLevel;
    let mut cloud_key = String::new();
    let mut cloud_endpoint = default_endpoint();
    let mut have_cloud = false;
    let mut tokens = BTreeMap::new();
    let mut expirations = BTreeMap::new();
    let mut refresh_tokens = BTreeMap::new();

    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with('[') && line.ends_with(']') {
            let name = &line[1..line.len() - 1];
            section = match name.trim() {
                "cloud" => Section::Cloud,
                "tokens" => Section::Tokens,
                "token_expires" => Section::TokenExpires,
                "token_refresh" => Section::TokenRefresh,
                _ => Section::TopLevel, // unknown section: tolerate, ignore lines
            };
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        let k = k.trim();
        let v = v.trim().trim_matches('"').to_string();
        match section {
            Section::Cloud | Section::TopLevel => match k {
                "key" => {
                    cloud_key = v;
                    have_cloud = true;
                }
                "endpoint" => {
                    cloud_endpoint = v;
                }
                _ => {}
            },
            Section::Tokens => {
                if !v.is_empty() {
                    tokens.insert(k.to_string(), v);
                }
            }
            Section::TokenExpires => {
                if !v.is_empty() {
                    expirations.insert(k.to_string(), v);
                }
            }
            Section::TokenRefresh => {
                if !v.is_empty() {
                    refresh_tokens.insert(k.to_string(), v);
                }
            }
        }
    }

    AuthStore {
        cloud: if have_cloud && !cloud_key.is_empty() {
            Some(ApiKey {
                key: cloud_key,
                endpoint: cloud_endpoint,
            })
        } else {
            None
        },
        tokens,
        expirations,
        refresh_tokens,
    }
}

// -- Migration --------------------------------------------------------------

/// Back-compat: read `~/.config/torii/config.toml`, pull `[auth]` out of
/// it into an `AuthStore`, and on success write it into `auth.toml` (so
/// next time we use the canonical location). Idempotent — silently
/// returns None when there's nothing to migrate.
fn migrate_from_config_toml() -> Option<AuthStore> {
    let config_path = dirs::config_dir()?.join("torii").join("config.toml");
    if !config_path.exists() {
        return None;
    }
    let text = fs::read_to_string(&config_path).ok()?;

    let mut tokens = BTreeMap::new();
    let mut in_auth = false;
    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with('[') && line.ends_with(']') {
            in_auth = line.trim_start_matches('[').trim_end_matches(']').trim() == "auth";
            continue;
        }
        if !in_auth {
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        let key = k.trim();
        let value = v.trim().trim_matches('"').to_string();
        if value.is_empty() {
            continue;
        }
        // Field name in config.toml was `<provider>_token`; in auth.toml
        // we drop the `_token` suffix to match the CLI argument.
        if let Some(provider) = key.strip_suffix("_token") {
            tokens.insert(provider.to_string(), value);
        }
    }
    if tokens.is_empty() {
        return None;
    }
    let store = AuthStore {
        cloud: None,
        tokens,
        expirations: BTreeMap::new(),
        refresh_tokens: BTreeMap::new(),
    };
    let _ = save_global(&store);
    Some(store)
}

// -- Unix permissions -------------------------------------------------------

#[cfg(unix)]
fn restrict_permissions(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
}

#[cfg(not(unix))]
fn restrict_permissions(_: &std::path::Path) {}

// -- Tests ------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_legacy_top_level_cloud() {
        let s = parse("key = \"gitorii_sk_abc\"");
        assert_eq!(s.cloud.as_ref().unwrap().key, "gitorii_sk_abc");
        assert!(s.tokens.is_empty());
    }

    #[test]
    fn parse_new_sectioned_cloud_only() {
        let s = parse("[cloud]\nkey = \"x\"\nendpoint = \"http://h\"\n");
        let c = s.cloud.unwrap();
        assert_eq!(c.key, "x");
        assert_eq!(c.endpoint, "http://h");
    }

    #[test]
    fn parse_tokens_only() {
        let s = parse("[tokens]\ngithub = \"ghp_x\"\ngitlab = \"glp_y\"\n");
        assert_eq!(s.tokens["github"], "ghp_x");
        assert_eq!(s.tokens["gitlab"], "glp_y");
        assert!(s.cloud.is_none());
    }

    #[test]
    fn parse_both_sections() {
        let s = parse("[cloud]\nkey = \"k\"\n[tokens]\ncargo = \"cio\"\n");
        assert_eq!(s.cloud.unwrap().key, "k");
        assert_eq!(s.tokens["cargo"], "cio");
    }

    #[test]
    fn parse_empty_tokens_are_dropped() {
        let s = parse("[tokens]\ngithub = \"\"\ngitlab = \"x\"\n");
        assert!(!s.tokens.contains_key("github"));
        assert!(s.tokens.contains_key("gitlab"));
    }

    #[test]
    fn normalise_provider_accepts_known() {
        assert_eq!(normalise_provider("GitHub").unwrap(), "github");
        assert_eq!(normalise_provider("cargo").unwrap(), "cargo");
    }

    #[test]
    fn normalise_provider_rejects_unknown() {
        assert!(normalise_provider("hackernews").is_err());
    }
}