Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

38.0 KB
Raw Blame
//! Local account catalog containing Qoder's opaque, already encrypted credentials.
//! Native CLI owns encryption and refresh; snapshots never leave the backend.
use crate::{
    config::atomic_write_private,
    qoder_config::{self, QoderEdition},
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
};

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AccountProfile {
    pub username: Option<String>,
    pub email: Option<String>,
    pub plan: Option<String>,
    pub organization_id: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QoderAccount {
    pub id: String,
    #[serde(flatten)]
    pub(crate) profile: AccountProfile,
    pub is_current: bool,
}

#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Credential {
    machine_id: String,
    encrypted_user: String,
}

#[derive(Clone, Deserialize, Serialize)]
struct SavedAccount {
    id: String,
    profile: AccountProfile,
    credential: Credential,
}

#[derive(Default, Deserialize, Serialize)]
pub(crate) struct AccountStore {
    scopes: BTreeMap<String, Vec<SavedAccount>>,
    /// 每个范围里最近一次确认是 Qoder 当前登录的号(切号、收录、查看状态认出它时记下)。
    /// Qoder 第一次用新凭据或续期时会重写登录文件,国内版资料常常只有用户名,
    /// 凭据和「邮箱 / 用户名+组织」都对不上时,靠它把同一个号认回来。
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    active: BTreeMap<String, String>,
}

pub(crate) fn absolute_root(edition: QoderEdition) -> Result<PathBuf, String> {
    let root = qoder_config::data_dir(edition);
    if root.is_absolute() {
        Ok(root)
    } else {
        Ok(std::env::current_dir()
            .map_err(|e| e.to_string())?
            .join(root))
    }
}

/// 账号范围里的版本标识(沿用两个版本各自的旧应用 ID,已有账号的范围不变)
fn edition_scope_id(edition: QoderEdition) -> &'static str {
    match edition {
        QoderEdition::Global => "qoder",
        QoderEdition::Cn => "qoder-cn",
    }
}

fn environment(edition: QoderEdition) -> String {
    let variable = if edition == QoderEdition::Cn {
        "QODERCN_ENV"
    } else {
        "QODER_ENV"
    };
    std::env::var(variable)
        .ok()
        .filter(|v| !v.is_empty())
        .or_else(|| std::env::var("QODER_ENV").ok())
        .unwrap_or_else(|| "prod".into())
}

fn credential_path(root: &Path, edition: QoderEdition) -> PathBuf {
    let environment = environment(edition);
    root.join(".auth").join(match environment.as_str() {
        "daily" => "user.daily",
        "test" => "user.test",
        _ => "user",
    })
}

pub(crate) fn scope(edition: QoderEdition, root: &Path) -> String {
    let root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let identity = format!(
        "{}\0{}\0{}",
        edition_scope_id(edition),
        root.display(),
        environment(edition)
    );
    format!("{:x}", Sha256::digest(identity.as_bytes()))
}

fn store_path() -> PathBuf {
    crate::config::get_app_config_dir().join("qoder_accounts.json")
}

fn optional_text(path: &Path) -> Result<Option<String>, String> {
    match fs::read_to_string(path) {
        Ok(value) => Ok(Some(value)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(_) => {
            Err("Cannot read Qoder credentials; check the config directory permissions".into())
        }
    }
}

/// Cooperate with proper-lockfile's native transaction directory. Never remove
/// or reclaim another process's lock, and keep the critical section synchronous.
struct NativeLock(PathBuf);
impl NativeLock {
    fn acquire(root: &Path) -> Result<Self, String> {
        let auth = root.join(".auth");
        fs::create_dir_all(&auth).map_err(|e| e.to_string())?;
        let path = auth.join(".credential-transaction.lock");
        fs::create_dir(&path).map_err(|_| {
            "Another Qoder process is updating this login. Refresh and retry".to_string()
        })?;
        Ok(Self(path))
    }
}
impl Drop for NativeLock {
    fn drop(&mut self) {
        let _ = fs::remove_dir(&self.0);
    }
}

fn read_unlocked(root: &Path, edition: QoderEdition) -> Result<Option<Credential>, String> {
    let Some(encrypted_user) = optional_text(&credential_path(root, edition))? else {
        return Ok(None);
    };
    let machine_id = optional_text(&root.join(".auth/machine_id"))?
        .filter(|v| !v.trim().is_empty())
        .ok_or("Qoder's machine identity is missing. Sign in again")?;
    Ok(Some(Credential {
        machine_id,
        encrypted_user,
    }))
}

pub(crate) fn capture(root: &Path, edition: QoderEdition) -> Result<Option<Credential>, String> {
    if !root.join(".auth").exists() {
        return Ok(None);
    }
    let _guard = NativeLock::acquire(root)?;
    read_unlocked(root, edition)
}

fn ensure_machine_identity_unlocked(root: &Path, next: &Credential) -> Result<bool, String> {
    let path = root.join(".auth/machine_id");
    if let Some(existing) = optional_text(&path)? {
        if existing.trim() != next.machine_id.trim() {
            return Err(
                "This account belongs to a different Qoder machine identity. Add the account again"
                    .into(),
            );
        }
        return Ok(false);
    }
    atomic_write_private(&path, next.machine_id.as_bytes()).map_err(|e| e.to_string())?;
    Ok(true)
}

/// Keep the first staged login's machine identity for later logins, even when
/// no account has been selected yet. Never activate the staged credentials.
pub(crate) fn preserve_machine_identity(root: &Path, next: &Credential) -> Result<(), String> {
    let _guard = NativeLock::acquire(root)?;
    ensure_machine_identity_unlocked(root, next)?;
    Ok(())
}

/// Only replace the exact credential observed by the caller. Machine identity
/// stays stable so Qoder's other encrypted files and running sessions still work.
pub(crate) fn replace(
    root: &Path,
    edition: QoderEdition,
    expected: Option<&Credential>,
    next: Option<&Credential>,
) -> Result<(), String> {
    let _guard = NativeLock::acquire(root)?;
    if read_unlocked(root, edition)?.as_ref() != expected {
        return Err("Qoder login changed outside CC Switch. Refresh and retry".into());
    }
    let path = credential_path(root, edition);
    if let Some(next) = next {
        let machine_path = root.join(".auth/machine_id");
        let created_machine = ensure_machine_identity_unlocked(root, next)?;
        if let Err(error) = atomic_write_private(&path, next.encrypted_user.as_bytes()) {
            if created_machine {
                let _ = fs::remove_file(machine_path);
            }
            return Err(error.to_string());
        }
    } else if expected.is_some() {
        fs::remove_file(path).map_err(|e| e.to_string())?;
    }
    Ok(())
}

pub(crate) fn prepare_login(root: &Path) -> Result<tempfile::TempDir, String> {
    let staging = tempfile::Builder::new()
        .prefix("cc-switch-qoder-account-")
        .tempdir()
        .map_err(|e| e.to_string())?;
    if let Some(settings) = optional_text(&root.join("settings.json"))? {
        atomic_write_private(&staging.path().join("settings.json"), settings.as_bytes())
            .map_err(|e| e.to_string())?;
    } else {
        atomic_write_private(
            &staging.path().join("settings.json"),
            br#"{"privacy":{"usageStatisticsEnabled":false}}"#,
        )
        .map_err(|e| e.to_string())?;
    }
    if let Some(machine_id) = optional_text(&root.join(".auth/machine_id"))? {
        atomic_write_private(
            &staging.path().join(".auth/machine_id"),
            machine_id.as_bytes(),
        )
        .map_err(|e| e.to_string())?;
    }
    Ok(staging)
}

impl AccountStore {
    pub(crate) fn load() -> Result<Self, String> {
        Self::load_from(&store_path())
    }
    fn load_from(path: &Path) -> Result<Self, String> {
        let Some(source) = optional_text(path)? else {
            return Ok(Self::default());
        };
        serde_json::from_str(&source)
            .map_err(|_| "Qoder account catalog is invalid; the existing file was preserved".into())
    }
    pub(crate) fn save(&self) -> Result<(), String> {
        self.save_to(&store_path())
    }
    fn save_to(&self, path: &Path) -> Result<(), String> {
        let bytes = serde_json::to_vec_pretty(self).map_err(|e| e.to_string())?;
        atomic_write_private(path, &bytes).map_err(|e| e.to_string())
    }
    pub(crate) fn save_reauthentication(
        &self,
        root: &Path,
        edition: QoderEdition,
        expected: &Credential,
        next: &Credential,
        was_current: bool,
    ) -> Result<(), String> {
        self.save_reauthentication_to(root, edition, expected, next, was_current, &store_path())
    }
    fn save_reauthentication_to(
        &self,
        root: &Path,
        edition: QoderEdition,
        expected: &Credential,
        next: &Credential,
        was_current: bool,
        path: &Path,
    ) -> Result<(), String> {
        // Renew the native login only when it still uses this exact account.
        // Leave the selected model and every other native setting untouched.
        let current = capture(root, edition)?;
        let active = current.as_ref() == Some(expected);
        if was_current && !active {
            return Err("Qoder login changed outside CC Switch. Refresh and retry".into());
        }
        if active {
            replace(root, edition, current.as_ref(), Some(next))?;
        }
        if let Err(error) = self.save_to(path) {
            if active {
                replace(root, edition, Some(next), current.as_ref())?;
            }
            return Err(error);
        }
        Ok(())
    }
    /// 收录(或更新)一个账号:用户点了「收录」、或自己发起的登录 / 切换才调用。
    pub(crate) fn import(
        &mut self,
        scope: &str,
        credential: Credential,
        profile: AccountProfile,
        before: Option<&Credential>,
    ) -> String {
        if let Some(id) = self.refresh_known(scope, &credential, &profile, before) {
            return id;
        }
        let id = uuid::Uuid::new_v4().to_string();
        self.scopes
            .entry(scope.into())
            .or_default()
            .push(SavedAccount {
                id: id.clone(),
                profile,
                credential,
            });
        id
    }

    /// 只更新已收录的号(Qoder 续期后换了凭据也认得出来),认不出就返回 `None`。
    /// 查看状态只走这条:没收录过的登录不会自己冒出来,等用户点「收录」。
    pub(crate) fn refresh_known(
        &mut self,
        scope: &str,
        credential: &Credential,
        profile: &AccountProfile,
        before: Option<&Credential>,
    ) -> Option<String> {
        let accounts = self.scopes.get_mut(scope)?;
        let credential = credential.clone();
        let profile = profile.clone();
        // Exact matches also handle importing a login already managed here.
        // A refresh during status lookup can be linked to the known credential
        // observed before the command, even when only a display name is known.
        let existing = accounts
            .iter_mut()
            .find(|account| account.credential == credential);
        if let Some(account) = existing {
            account.profile = profile;
            return Some(account.id.clone());
        }
        if let Some(account) = accounts.iter_mut().find(|account| {
            before == Some(&account.credential)
                && account.profile.username == profile.username
                && account.profile.email == profile.email
                && account.profile.organization_id == profile.organization_id
        }) {
            account.credential = credential;
            account.profile = profile;
            return Some(account.id.clone());
        }
        let nonempty = |value: &Option<String>| {
            value
                .as_deref()
                .is_some_and(|value| !value.trim().is_empty())
        };
        // Qoder renewed the login outside CC Switch (e.g. a CLI run). The account
        // CC Switch last confirmed as Qoder's login still reports the same identity,
        // so it is the same account with a new credential. A display name alone is
        // not trusted for any other saved account.
        if nonempty(&profile.username) || nonempty(&profile.email) {
            if let Some(active) = self.active.get(scope) {
                if let Some(account) = accounts.iter_mut().find(|account| {
                    &account.id == active
                        && account.profile.username == profile.username
                        && account.profile.email == profile.email
                        && account.profile.organization_id == profile.organization_id
                }) {
                    account.credential = credential;
                    account.profile = profile;
                    return Some(account.id.clone());
                }
            }
        }
        // The CLI may already have rotated credentials before status lookup.
        // Require a unique identity within this scope: email, or username plus
        // organization. A display name or organization alone cannot identify a user.
        if nonempty(&profile.email)
            || (nonempty(&profile.username) && nonempty(&profile.organization_id))
        {
            let mut matches = accounts.iter_mut().filter(|account| {
                account.profile.username == profile.username
                    && account.profile.email == profile.email
                    && account.profile.organization_id == profile.organization_id
            });
            if let Some(account) = matches.next() {
                if matches.next().is_none() {
                    account.credential = credential;
                    account.profile = profile;
                    return Some(account.id.clone());
                }
            }
        }
        None
    }
    pub(crate) fn accounts(&self, scope: &str, current: Option<&Credential>) -> Vec<QoderAccount> {
        self.scopes
            .get(scope)
            .into_iter()
            .flatten()
            .map(|account| QoderAccount {
                id: account.id.clone(),
                profile: account.profile.clone(),
                is_current: current == Some(&account.credential),
            })
            .collect()
    }
    pub(crate) fn reauthenticate(
        &mut self,
        scope: &str,
        id: &str,
        expected: &Credential,
        credential: Credential,
        profile: AccountProfile,
    ) -> Result<(), String> {
        if &self.credential(scope, id)? != expected {
            return Err(
                "This Qoder account changed during sign-in. Refresh the account list and retry"
                    .into(),
            );
        }
        let accounts = self.scopes.get_mut(scope).unwrap();
        let has_identity = profile
            .email
            .as_deref()
            .is_some_and(|value| !value.trim().is_empty())
            || (profile
                .username
                .as_deref()
                .is_some_and(|value| !value.trim().is_empty())
                && profile
                    .organization_id
                    .as_deref()
                    .is_some_and(|value| !value.trim().is_empty()));
        if accounts.iter().any(|account| {
            account.id != id
                && (account.credential == credential
                    || (has_identity
                        && account.profile.username == profile.username
                        && account.profile.email == profile.email
                        && account.profile.organization_id == profile.organization_id))
        }) {
            return Err(
                "This Qoder account is already saved. Use the existing account instead".into(),
            );
        }
        let account = accounts
            .iter_mut()
            .find(|account| account.id == id)
            .unwrap();
        account.credential = credential;
        account.profile = profile;
        Ok(())
    }
    pub(crate) fn credential(&self, scope: &str, id: &str) -> Result<Credential, String> {
        self.scopes
            .get(scope)
            .into_iter()
            .flatten()
            .find(|a| a.id == id)
            .map(|a| a.credential.clone())
            .ok_or_else(|| "Qoder account no longer exists. Refresh the account list".into())
    }
    pub(crate) fn remove(&mut self, scope: &str, id: &str) -> Result<(), String> {
        self.credential(scope, id)?;
        self.scopes
            .get_mut(scope)
            .unwrap()
            .retain(|account| account.id != id);
        if self.active.get(scope).is_some_and(|active| active == id) {
            self.active.remove(scope);
        }
        Ok(())
    }
    /// 记下 Qoder 当前登录对应的已存账号(只在确认它就是当前登录时调用)
    pub(crate) fn mark_active(&mut self, scope: &str, id: &str) {
        self.active.insert(scope.into(), id.into());
    }
    /// 最近一次确认是 Qoder 当前登录的号(没确认过、或已删除时为空)
    pub(crate) fn active(&self, scope: &str) -> Option<&str> {
        let id = self.active.get(scope)?;
        self.scopes
            .get(scope)?
            .iter()
            .any(|account| &account.id == id)
            .then_some(id.as_str())
    }
}

/// 所选版本收录的账号和最近确认在用的那个号,供应商列表据此生成官方账号卡。
/// 只读本机账号文件,不调用 Qoder CLI。
pub(crate) fn saved_accounts(
    edition: QoderEdition,
) -> Result<(Vec<QoderAccount>, Option<String>), String> {
    let root = absolute_root(edition)?;
    let scope = scope(edition, &root);
    let store = AccountStore::load()?;
    let active = store.active(&scope).map(str::to_string);
    Ok((store.accounts(&scope, None), active))
}

impl QoderAccount {
    /// 卡片上显示的账号名:邮箱优先,其次用户名
    pub(crate) fn display_name(&self) -> Option<&str> {
        [&self.profile.email, &self.profile.username]
            .into_iter()
            .flatten()
            .map(|value| value.trim())
            .find(|value| !value.is_empty())
    }
    pub(crate) fn plan(&self) -> Option<&str> {
        self.profile
            .plan
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    fn credential(value: &str) -> Credential {
        Credential {
            machine_id: "fixture-machine".into(),
            encrypted_user: value.into(),
        }
    }

    #[test]
    fn qoder_staged_accounts_share_machine_identity_before_any_account_is_selected() {
        for edition in QoderEdition::ALL {
            let temp = tempfile::tempdir().unwrap();
            let root = temp.path();
            let first = credential("first-account");
            preserve_machine_identity(root, &first).unwrap();
            assert!(capture(root, edition).unwrap().is_none());
            let next_login = prepare_login(root).unwrap();
            assert_eq!(
                fs::read_to_string(next_login.path().join(".auth/machine_id")).unwrap(),
                first.machine_id,
            );
            assert!(capture(next_login.path(), edition).unwrap().is_none());
            let second = credential("second-account");
            preserve_machine_identity(root, &second).unwrap();
            replace(root, edition, None, Some(&first)).unwrap();
            replace(root, edition, Some(&first), Some(&second)).unwrap();
            assert!(capture(root, edition).unwrap() == Some(second));
            let foreign = Credential {
                machine_id: "another-machine".into(),
                encrypted_user: "another-account".into(),
            };
            assert!(preserve_machine_identity(root, &foreign).is_err());
            assert_eq!(
                fs::read_to_string(root.join(".auth/machine_id")).unwrap(),
                first.machine_id
            );
        }
    }

    #[test]
    fn qoder_renewed_login_with_only_a_username_maps_back_to_the_active_account() {
        // Qoder CN profiles often carry a username only. When Qoder rewrites the
        // credential outside CC Switch, the account CC Switch last confirmed as the
        // login is refreshed instead of being reported (and collected) again.
        let profile = AccountProfile {
            username: Some("farion".into()),
            ..Default::default()
        };
        let mut store = AccountStore::default();
        let id = store.import("cn", credential("issued"), profile.clone(), None);
        assert!(store
            .refresh_known("cn", &credential("renewed"), &profile, None)
            .is_none());

        store.mark_active("cn", &id);
        assert_eq!(
            store.refresh_known("cn", &credential("renewed"), &profile, None),
            Some(id.clone())
        );
        assert!(store.credential("cn", &id).unwrap() == credential("renewed"));
        assert_eq!(
            store.import("cn", credential("renewed-again"), profile.clone(), None),
            id
        );
        assert_eq!(store.accounts("cn", None).len(), 1);

        // A different identity, another scope, or an anonymous profile never matches.
        let other = AccountProfile {
            username: Some("someone else".into()),
            ..Default::default()
        };
        for (scope, profile) in [
            ("cn", other),
            ("global", profile.clone()),
            ("cn", AccountProfile::default()),
        ] {
            assert!(store
                .refresh_known(scope, &credential("foreign"), &profile, None)
                .is_none());
        }
        assert!(store.credential("cn", &id).unwrap() == credential("renewed-again"));

        // The pointer survives a save/load round trip and is cleared with its account.
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("qoder_accounts.json");
        store.save_to(&path).unwrap();
        let mut loaded = AccountStore::load_from(&path).unwrap();
        assert_eq!(
            loaded.refresh_known("cn", &credential("third"), &profile, None),
            Some(id.clone())
        );
        loaded.remove("cn", &id).unwrap();
        loaded.import("cn", credential("fourth"), profile.clone(), None);
        assert!(loaded
            .refresh_known("cn", &credential("fifth"), &profile, None)
            .is_none());
    }

    #[test]
    fn qoder_reauthentication_keeps_ids_and_rejects_changed_or_duplicate_accounts() {
        let mut store = AccountStore::default();
        let profile = AccountProfile {
            username: Some("same display name".into()),
            ..Default::default()
        };
        let first = store.import("global", credential("first"), profile.clone(), None);
        let second = store.import("global", credential("second"), profile.clone(), None);
        store.import("cn", credential("cn"), profile.clone(), None);
        store
            .reauthenticate(
                "global",
                &first,
                &credential("first"),
                credential("renewed"),
                AccountProfile {
                    plan: Some("Pro".into()),
                    ..profile.clone()
                },
            )
            .unwrap();
        assert_eq!(store.accounts("global", None).len(), 2);
        assert!(store.credential("global", &first).unwrap() == credential("renewed"));
        assert!(store.credential("global", &second).unwrap() == credential("second"));
        assert_eq!(
            store.accounts("global", None)[0].profile.plan.as_deref(),
            Some("Pro")
        );
        // A stale flow cannot overwrite credentials rotated or removed in the meantime.
        for (scope, id, expected, next) in [
            ("global", first.as_str(), "first", "stale"),
            ("cn", first.as_str(), "renewed", "wrong-edition"),
            ("global", "removed", "renewed", "deleted"),
            ("global", first.as_str(), "renewed", "second"),
        ] {
            assert!(store
                .reauthenticate(
                    scope,
                    id,
                    &credential(expected),
                    credential(next),
                    profile.clone()
                )
                .is_err());
        }
        assert!(store.credential("global", &first).unwrap() == credential("renewed"));
        assert_eq!(store.accounts("cn", None).len(), 1);
        let identity = AccountProfile {
            email: Some("[email protected]".into()),
            ..Default::default()
        };
        store.import("global", credential("third"), identity.clone(), None);
        assert!(store
            .reauthenticate(
                "global",
                &first,
                &credential("renewed"),
                credential("third-renewed"),
                identity
            )
            .is_err());
        assert!(store.credential("global", &first).unwrap() == credential("renewed"));
    }

    #[test]
    fn qoder_reauthentication_preserves_model_and_other_native_login() {
        for edition in QoderEdition::ALL {
            for active in [true, false] {
                let temp = tempfile::tempdir().unwrap();
                let root = temp.path();
                let settings = "{\"model\":{\"name\":\"custom/model\"},\"native\":true}";
                fs::write(root.join("settings.json"), settings).unwrap();
                let previous = credential(if active { "original" } else { "other" });
                replace(root, edition, None, Some(&previous)).unwrap();
                let mut store = AccountStore::default();
                let id = store.import(
                    "scope",
                    credential("original"),
                    AccountProfile::default(),
                    None,
                );
                store
                    .reauthenticate(
                        "scope",
                        &id,
                        &credential("original"),
                        credential("renewed"),
                        AccountProfile::default(),
                    )
                    .unwrap();
                let path = root.join("catalog.json");
                store
                    .save_reauthentication_to(
                        root,
                        edition,
                        &credential("original"),
                        &credential("renewed"),
                        active,
                        &path,
                    )
                    .unwrap();
                let saved = AccountStore::load_from(&path).unwrap();
                assert!(saved.credential("scope", &id).unwrap() == credential("renewed"));
                let expected_native = if active {
                    credential("renewed")
                } else {
                    previous
                };
                assert!(capture(root, edition).unwrap() == Some(expected_native));
                assert_eq!(
                    fs::read_to_string(root.join("settings.json")).unwrap(),
                    settings
                );
            }
        }
    }

    #[test]
    fn qoder_reauthentication_rolls_back_native_login_when_catalog_save_fails() {
        for edition in QoderEdition::ALL {
            let temp = tempfile::tempdir().unwrap();
            let root = temp.path();
            replace(root, edition, None, Some(&credential("original"))).unwrap();
            let blocker = root.join("blocker");
            fs::write(&blocker, "keep").unwrap();
            let store = AccountStore::default();
            assert!(store
                .save_reauthentication_to(
                    root,
                    edition,
                    &credential("original"),
                    &credential("renewed"),
                    true,
                    &blocker.join("catalog.json")
                )
                .is_err());
            assert!(capture(root, edition).unwrap() == Some(credential("original")));
            assert_eq!(fs::read_to_string(&blocker).unwrap(), "keep");
        }
    }

    #[test]
    fn qoder_reauthentication_refuses_a_native_login_changed_during_authorization() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        replace(
            root,
            QoderEdition::Global,
            None,
            Some(&credential("refreshed-outside")),
        )
        .unwrap();
        let path = root.join("catalog.json");
        let store = AccountStore::default();
        assert!(store
            .save_reauthentication_to(
                root,
                QoderEdition::Global,
                &credential("original"),
                &credential("new-login"),
                true,
                &path,
            )
            .is_err());
        assert!(
            capture(root, QoderEdition::Global).unwrap() == Some(credential("refreshed-outside"))
        );
        assert!(!path.exists());
    }

    #[test]
    fn qoder_accounts_keep_same_name_accounts_and_editions_separate() {
        let mut store = AccountStore::default();
        let profile = AccountProfile {
            username: Some("same name".into()),
            ..Default::default()
        };
        let a = store.import("global", credential("a"), profile.clone(), None);
        let b = store.import("global", credential("b"), profile.clone(), None);
        store.import("cn", credential("c"), profile.clone(), None);
        assert_ne!(a, b);
        let id = store.import(
            "global",
            credential("a-refreshed"),
            profile,
            Some(&credential("a")),
        );
        assert_eq!(id, a);
        assert_eq!(store.accounts("global", None).len(), 2);
        assert!(store.remove("cn", &a).is_err());
        store.remove("global", &a).unwrap();
        assert_eq!(store.accounts("cn", None).len(), 1);
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("accounts.json");
        store.save_to(&path).unwrap();
        let loaded = AccountStore::load_from(&path).unwrap();
        assert!(loaded.credential("global", &b).unwrap() == credential("b"));
        let public = serde_json::to_string(&loaded.accounts("global", None)).unwrap();
        assert!(!public.contains("encryptedUser") && !public.contains("machineId"));
    }

    #[test]
    fn qoder_accounts_reuse_unique_identities_after_external_token_rotation() {
        for profile in [
            AccountProfile {
                username: Some("fixture".into()),
                email: Some("[email protected]".into()),
                ..Default::default()
            },
            AccountProfile {
                username: Some("fixture".into()),
                organization_id: Some("org".into()),
                ..Default::default()
            },
            AccountProfile {
                email: Some("[email protected]".into()),
                ..Default::default()
            },
        ] {
            let mut store = AccountStore::default();
            let id = store.import("global", credential("old"), profile.clone(), None);
            let cn = store.import("cn", credential("cn"), profile.clone(), None);
            let updated = AccountProfile {
                plan: Some("Pro".into()),
                ..profile
            };
            let current = credential("refreshed-before-status");
            assert_eq!(
                store.import("global", current.clone(), updated.clone(), Some(&current)),
                id
            );
            assert!(store.credential("global", &id).unwrap() == current);
            let accounts = store.accounts("global", Some(&current));
            assert_eq!(accounts.len(), 1);
            assert!(accounts[0].is_current);
            assert_eq!(accounts[0].profile.plan.as_deref(), Some("Pro"));
            assert_eq!(
                store.import("global", credential("refreshed-again"), updated, None),
                id
            );
            assert!(store.credential("global", &id).unwrap() == credential("refreshed-again"));
            assert_eq!(store.accounts("global", None).len(), 1);
            assert!(store.credential("cn", &cn).unwrap() == credential("cn"));
        }
    }

    #[test]
    fn qoder_accounts_do_not_merge_missing_or_conflicting_identities() {
        for profile in [
            AccountProfile::default(),
            AccountProfile {
                username: Some("same name".into()),
                ..Default::default()
            },
            AccountProfile {
                username: Some("same name".into()),
                email: Some(" ".into()),
                organization_id: Some("".into()),
                ..Default::default()
            },
            AccountProfile {
                organization_id: Some("shared-org".into()),
                ..Default::default()
            },
        ] {
            let mut store = AccountStore::default();
            let first = store.import("global", credential("a"), profile.clone(), None);
            let next = credential("b");
            assert_ne!(
                store.import("global", next.clone(), profile, Some(&next)),
                first
            );
            assert!(store.credential("global", &first).unwrap() == credential("a"));
        }
        let profile = AccountProfile {
            username: Some("fixture".into()),
            email: Some("[email protected]".into()),
            organization_id: Some("org".into()),
            ..Default::default()
        };
        for other in [
            AccountProfile {
                username: Some("other".into()),
                ..profile.clone()
            },
            AccountProfile {
                email: Some("[email protected]".into()),
                ..profile.clone()
            },
            AccountProfile {
                organization_id: Some("other-org".into()),
                ..profile.clone()
            },
        ] {
            let mut store = AccountStore::default();
            let first = store.import("global", credential("a"), profile.clone(), None);
            assert_ne!(store.import("global", credential("b"), other, None), first);
        }
    }

    #[test]
    fn qoder_accounts_do_not_choose_between_ambiguous_saved_identities() {
        let mut store = AccountStore::default();
        let profile = AccountProfile {
            username: Some("fixture".into()),
            email: Some("[email protected]".into()),
            ..Default::default()
        };
        let first = store.import("global", credential("a"), profile.clone(), None);
        // Older catalogs may already contain duplicates from native refreshes.
        let accounts = store.scopes.get_mut("global").unwrap();
        let mut duplicate = accounts[0].clone();
        duplicate.id = "duplicate".into();
        duplicate.credential = credential("b");
        accounts.push(duplicate);
        let next = store.import("global", credential("c"), profile, None);
        assert_ne!(next, first);
        assert_ne!(next, "duplicate");
        assert!(store.credential("global", &first).unwrap() == credential("a"));
        assert!(store.credential("global", "duplicate").unwrap() == credential("b"));
    }

    #[test]
    fn qoder_account_switch_and_delete_preserve_other_native_data() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        fs::write(root.join("settings.json"), "keep settings").unwrap();
        replace(root, QoderEdition::Cn, None, Some(&credential("a"))).unwrap();
        assert!(replace(root, QoderEdition::Cn, None, Some(&credential("b"))).is_err());
        replace(
            root,
            QoderEdition::Cn,
            Some(&credential("a")),
            Some(&credential("b")),
        )
        .unwrap();
        let staged = prepare_login(root).unwrap();
        assert!(!staged.path().join(".auth/user").exists());
        assert_eq!(
            fs::read_to_string(staged.path().join(".auth/machine_id")).unwrap(),
            "fixture-machine"
        );
        replace(root, QoderEdition::Cn, Some(&credential("b")), None).unwrap();
        assert!(capture(root, QoderEdition::Cn).unwrap().is_none());
        assert_eq!(
            fs::read_to_string(root.join("settings.json")).unwrap(),
            "keep settings"
        );
        assert!(root.join(".auth/machine_id").exists());
    }

    #[test]
    fn qoder_accounts_refuse_foreign_machine_or_concurrent_native_changes() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        replace(root, QoderEdition::Global, None, Some(&credential("a"))).unwrap();
        let foreign = Credential {
            machine_id: "foreign-machine".into(),
            encrypted_user: "foreign".into(),
        };
        assert!(replace(
            root,
            QoderEdition::Global,
            Some(&credential("a")),
            Some(&foreign)
        )
        .is_err());
        assert!(capture(root, QoderEdition::Global).unwrap().as_ref() == Some(&credential("a")));
        replace(
            root,
            QoderEdition::Global,
            Some(&credential("a")),
            Some(&credential("b")),
        )
        .unwrap();
        assert!(replace(root, QoderEdition::Global, Some(&credential("a")), None).is_err());
        assert!(capture(root, QoderEdition::Global).unwrap().as_ref() == Some(&credential("b")));
        let native_lock = root.join(".auth/.credential-transaction.lock");
        fs::create_dir(&native_lock).unwrap();
        assert!(replace(root, QoderEdition::Global, Some(&credential("b")), None).is_err());
        assert!(native_lock.exists());
    }

    #[test]
    fn qoder_accounts_preserve_invalid_catalogs() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("accounts.json");
        for original in ["broken JSON", "{}", "{\"scopes\":[]}"] {
            fs::write(&path, original).unwrap();
            assert!(AccountStore::load_from(&path).is_err());
            assert_eq!(fs::read_to_string(&path).unwrap(), original);
        }
    }
}