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

43.1 KB
Raw Blame
//! Transport-agnostic sync protocol layer.
//!
//! Shared by WebDAV, S3, and future transports. Artifact set: `db.sql` + `skills.zip`.

use std::collections::BTreeMap;
use std::fs;
use std::future::Future;
use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;

use chrono::Utc;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tempfile::tempdir;

use crate::error::AppError;
use crate::services::skill::{skill_state_read_guard, skill_state_write_guard};
use crate::services::sync_crypto;

// Re-export archive functions for use by transport layers.
pub(crate) use super::webdav_sync::archive::{
    backup_current_skills, restore_skills_zip, zip_skills_ssot,
};

// ─── Protocol constants ──────────────────────────────────────

/// Wire-format identifier stored in remote manifests.
/// Retains historic "webdav" naming for backward compatibility with existing remotes.
pub(crate) const PROTOCOL_FORMAT: &str = "cc-switch-webdav-sync";
pub(crate) const PROTOCOL_VERSION: u32 = 2;
pub(crate) const DB_COMPAT_VERSION: u32 = 6;
pub(crate) const LEGACY_DB_COMPAT_VERSION: u32 = 5;
pub(crate) const REMOTE_DB_SQL: &str = "db.sql";
pub(crate) const REMOTE_SKILLS_ZIP: &str = "skills.zip";
pub(crate) const REMOTE_MANIFEST: &str = "manifest.json";
pub(crate) const MAX_DEVICE_NAME_LEN: usize = 64;
pub(crate) const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
pub(crate) const MAX_SYNC_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024;
/// Download size cap allowing for encryption framing overhead on top of [`MAX_SYNC_ARTIFACT_BYTES`].
pub(crate) const MAX_SYNC_DOWNLOAD_BYTES: usize =
    MAX_SYNC_ARTIFACT_BYTES as usize + sync_crypto::ENCRYPTION_OVERHEAD;

// ─── Transfer timeouts ──────────────────────────────────────

/// Floor of the overall timeout for large transfers (db.sql, skills.zip).
const TRANSFER_BASE_TIMEOUT_SECS: u64 = 300;
/// Slowest throughput the overall timeout still accommodates (16 KiB/s).
const TRANSFER_MIN_BYTES_PER_SEC: u64 = 16 * 1024;
/// A transfer that makes no progress for this long (waiting for response
/// headers, or between two body chunks) is treated as stalled.
pub(crate) const TRANSFER_IDLE_TIMEOUT: Duration = Duration::from_secs(120);

/// Overall timeout for transferring up to `len` bytes.
///
/// reqwest's request timeout covers the whole body, so a fixed 300 s cut off
/// healthy-but-slow downloads of large skills.zip archives mid-stream (#8428).
/// The budget now grows with the payload size; stalls are caught separately by
/// [`TRANSFER_IDLE_TIMEOUT`] where the transport can observe progress.
pub(crate) fn transfer_timeout(len: u64) -> Duration {
    Duration::from_secs(TRANSFER_BASE_TIMEOUT_SECS.saturating_add(len / TRANSFER_MIN_BYTES_PER_SEC))
}

/// Describe a WebDAV/S3 transport failure as `(zh, en)`: a short category plus
/// the reqwest cause chain (URL stripped).
///
/// `is_request()` means the request was built but failed while being sent
/// (connection reset or closed mid-body, TLS / HTTP-2 errors…); only
/// `is_builder()` is a request build failure. Labelling the former "request
/// build failed" and dropping the cause left users with nothing to act on (#9559).
pub(crate) fn transport_failure_reason(err: reqwest::Error) -> (String, String) {
    let (zh, en) = if err.is_timeout() {
        ("请求超时", "request timed out")
    } else if err.is_connect() {
        ("连接失败", "connection failed")
    } else if err.is_builder() {
        ("请求构造失败", "request build failed")
    } else if err.is_request() {
        ("发送失败", "failed to send")
    } else {
        ("网络请求失败", "network request failed")
    };
    let detail = crate::proxy::error::describe_reqwest_error(err);
    (format!("{zh}: {detail}"), format!("{en}: {detail}"))
}

// ─── Sync operation lock ────────────────────────────────────

/// Serialize every snapshot upload/download across all transports.
///
/// WebDAV and S3 used to own separate mutexes, which allowed two transports to
/// restore the database and Skills SSOT concurrently. Keep the lock in this
/// transport-agnostic layer so future transports automatically share it too.
pub(crate) fn sync_mutex() -> &'static tokio::sync::Mutex<()> {
    static LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}

pub(crate) async fn run_with_sync_lock<T, Fut>(operation: Fut) -> Result<T, AppError>
where
    Fut: Future<Output = Result<T, AppError>>,
{
    let _guard = sync_mutex().lock().await;
    operation.await
}

/// Tables whose changes make the remote configuration snapshot stale.
///
/// Keep this transport-agnostic so WebDAV and S3 cannot silently drift apart.
/// `model_pricing` is intentionally excluded while its local JSON sidecar is
/// the user-owned SSOT.
pub(crate) fn should_trigger_auto_sync_for_table(table: &str) -> bool {
    let normalized = table.trim().to_ascii_lowercase();
    matches!(
        normalized.as_str(),
        "providers"
            | "provider_endpoints"
            | "mcp_servers"
            | "prompts"
            | "skills"
            | "skill_repos"
            | "profiles"
            | "settings"
            | "proxy_config"
    )
}

// ─── Error helpers ───────────────────────────────────────────

pub(crate) fn localized(
    key: &'static str,
    zh: impl Into<String>,
    en: impl Into<String>,
) -> AppError {
    AppError::localized(key, zh, en)
}

pub(crate) fn io_context_localized(
    _key: &'static str,
    zh: impl Into<String>,
    en: impl Into<String>,
    source: std::io::Error,
) -> AppError {
    let zh_msg = zh.into();
    let en_msg = en.into();
    AppError::IoContext {
        context: format!("{zh_msg} ({en_msg})"),
        source,
    }
}

// ─── Cloud-data encryption helpers ───────────────────────────

/// Seal an artifact before upload when an encryption key is configured.
///
/// Returns `(bytes, content_type)`. Encrypted payloads are opaque binary
/// (`application/octet-stream`) because the ciphertext no longer matches the
/// artifact's natural format; when no key is set the plaintext and its
/// original content type pass through unchanged. Call this in every transport
/// upload path (WebDAV, S3, ...) so remote copies are encrypted uniformly.
pub(crate) fn encrypt_artifact_for_upload(
    plaintext: Vec<u8>,
    plaintext_content_type: &'static str,
    key: &str,
) -> Result<(Vec<u8>, &'static str), AppError> {
    let key = key.trim();
    if key.is_empty() {
        return Ok((plaintext, plaintext_content_type));
    }
    let sealed = sync_crypto::encrypt(&plaintext, key)
        .map_err(|e| AppError::Config(format!("Encryption failed: {e}")))?;
    Ok((sealed, "application/octet-stream"))
}

/// Open a downloaded artifact when it is encrypted.
///
/// Encrypted artifacts are detected by their header, so plaintext artifacts
/// from older/other clients are returned unchanged. An encrypted artifact
/// without a configured key is a hard error rather than a silent mismatch,
/// since the caller could not verify or apply it anyway.
pub(crate) fn decrypt_artifact_from_download(
    bytes: Vec<u8>,
    key: &str,
    artifact_name: &str,
) -> Result<Vec<u8>, AppError> {
    if !sync_crypto::is_encrypted(&bytes) {
        return Ok(bytes);
    }
    let key = key.trim();
    if key.is_empty() {
        return Err(localized(
            "sync.encryption.missing_key",
            format!(
                "远端 artifact {artifact_name} 已加密,但未配置加密密钥。请在同步设置中填写云数据加密密钥。"
            ),
            format!(
                "Remote artifact {artifact_name} is encrypted but no encryption key is configured. Set the cloud data encryption key in sync settings."
            ),
        ));
    }
    sync_crypto::decrypt(&bytes, key)
        .map_err(|e| AppError::Config(format!("Decryption of {artifact_name} failed: {e}")))
}

/// Result of inspecting a remote manifest's encryption metadata against this device's key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RemoteEncryptionStatus {
    Unencrypted,
    Matched,
    MissingKey,
    KeyMismatch,
    UnsupportedVersion(u32),
    Malformed,
}

impl RemoteEncryptionStatus {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Unencrypted => "none",
            Self::Matched => "matched",
            Self::MissingKey => "missing_key",
            Self::KeyMismatch => "key_mismatch",
            Self::UnsupportedVersion(_) => "unsupported_version",
            Self::Malformed => "malformed",
        }
    }
}

/// Inspect whether the remote manifest is encrypted and whether `local_key` matches it.
pub(crate) fn inspect_remote_encryption(
    remote_manifest: Option<&SyncManifest>,
    local_key: &str,
) -> RemoteEncryptionStatus {
    let Some(enc) = remote_manifest.and_then(|m| m.encryption.as_ref()) else {
        return RemoteEncryptionStatus::Unencrypted;
    };

    if enc.version != sync_crypto::FORMAT_VERSION {
        return RemoteEncryptionStatus::UnsupportedVersion(enc.version);
    }

    let key = local_key.trim();
    if key.is_empty() {
        return RemoteEncryptionStatus::MissingKey;
    }

    match sync_crypto::verify_key_check(key, enc.version, &enc.salt, &enc.key_check) {
        sync_crypto::KeyCheckResult::Matched => RemoteEncryptionStatus::Matched,
        sync_crypto::KeyCheckResult::Mismatched => RemoteEncryptionStatus::KeyMismatch,
        sync_crypto::KeyCheckResult::UnsupportedVersion => {
            RemoteEncryptionStatus::UnsupportedVersion(enc.version)
        }
        sync_crypto::KeyCheckResult::MalformedMetadata => RemoteEncryptionStatus::Malformed,
    }
}

/// Guard uploads so a device without the encryption key (or with a mismatched key)
/// cannot silently overwrite an encrypted remote snapshot.
///
/// - Mismatched keys and unsupported/malformed encryption metadata are always refused.
/// - Downgrading an encrypted remote back to plaintext (`MissingKey`) is only allowed
///   when `allow_plaintext_overwrite` is explicitly `true` (never in auto-sync).
pub(crate) fn validate_upload_against_remote_encryption(
    remote_manifest: Option<&SyncManifest>,
    local_key: &str,
    allow_plaintext_overwrite: bool,
) -> Result<(), AppError> {
    match inspect_remote_encryption(remote_manifest, local_key) {
        RemoteEncryptionStatus::Unencrypted | RemoteEncryptionStatus::Matched => Ok(()),
        RemoteEncryptionStatus::MissingKey => {
            if allow_plaintext_overwrite {
                Ok(())
            } else {
                Err(localized(
                    "sync.encryption.remote_encrypted_missing_key",
                    "远端同步数据已加密,但当前设备未配置加密密钥,已阻止明文覆盖。请填写与其他设备一致的云数据加密密钥后再上传。",
                    "Remote sync data is encrypted, but this device has no encryption key configured. Enter the same Cloud Data Encryption Key used on your other devices before uploading.",
                ))
            }
        }
        RemoteEncryptionStatus::KeyMismatch => Err(localized(
            "sync.encryption.key_mismatch",
            "当前设备的云数据加密密钥与远端不匹配,已阻止上传。请填写与其他设备一致的云数据加密密钥。",
            "This device's Cloud Data Encryption Key does not match the encrypted remote snapshot. Enter the same key used on your other devices before uploading.",
        )),
        RemoteEncryptionStatus::UnsupportedVersion(version) => Err(localized(
            "sync.encryption.unsupported_version",
            format!("远端同步数据使用了不受支持的加密格式 (v{version}),请升级 CC Switch 后重试。"),
            format!("Remote sync data uses an unsupported encryption format (v{version}). Upgrade CC Switch and try again."),
        )),
        RemoteEncryptionStatus::Malformed => Err(localized(
            "sync.encryption.invalid_metadata",
            "远端 manifest 中的加密校验信息无效,已阻止上传。",
            "Remote manifest contains invalid encryption metadata; upload refused.",
        )),
    }
}

/// Fail-fast check on download before fetching potentially large artifacts.
pub(crate) fn validate_download_against_remote_encryption(
    remote_manifest: &SyncManifest,
    local_key: &str,
) -> Result<(), AppError> {
    match inspect_remote_encryption(Some(remote_manifest), local_key) {
        RemoteEncryptionStatus::Unencrypted | RemoteEncryptionStatus::Matched => Ok(()),
        RemoteEncryptionStatus::MissingKey => Err(localized(
            "sync.encryption.missing_key",
            "远端同步数据已加密,但当前设备未配置加密密钥。请在同步设置中填写云数据加密密钥。",
            "Remote sync data is encrypted, but no encryption key is configured. Set the Cloud Data Encryption Key in sync settings.",
        )),
        RemoteEncryptionStatus::KeyMismatch => Err(localized(
            "sync.encryption.download_key_mismatch",
            "当前设备的云数据加密密钥与远端不匹配,无法解密。请检查密钥是否与其他设备一致。",
            "This device's Cloud Data Encryption Key does not match the remote snapshot. Check that it matches your other devices.",
        )),
        RemoteEncryptionStatus::UnsupportedVersion(version) => Err(localized(
            "sync.encryption.unsupported_version",
            format!("远端同步数据使用了不受支持的加密格式 (v{version}),请升级 CC Switch 后重试。"),
            format!("Remote sync data uses an unsupported encryption format (v{version}). Upgrade CC Switch and try again."),
        )),
        RemoteEncryptionStatus::Malformed => Err(localized(
            "sync.encryption.invalid_metadata",
            "远端 manifest 中的加密校验信息无效,无法解密。",
            "Remote manifest contains invalid encryption metadata.",
        )),
    }
}

// ─── Types ───────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SyncEncryptionMeta {
    pub version: u32,
    pub salt: String,
    pub key_check: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SyncManifest {
    pub format: String,
    pub version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub db_compat_version: Option<u32>,
    pub device_name: String,
    pub created_at: String,
    pub artifacts: BTreeMap<String, ArtifactMeta>,
    pub snapshot_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encryption: Option<SyncEncryptionMeta>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ArtifactMeta {
    pub sha256: String,
    pub size: u64,
}

pub(crate) struct LocalSnapshot {
    pub db_sql: Vec<u8>,
    pub skills_zip: Vec<u8>,
    pub manifest_bytes: Vec<u8>,
    pub manifest_hash: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RemoteLayout {
    Current,
    Legacy,
}

impl RemoteLayout {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Current => "current",
            Self::Legacy => "legacy",
        }
    }
}

// ─── Snapshot building ───────────────────────────────────────

pub(crate) fn build_local_snapshot(
    db: &crate::database::Database,
    encryption_key: &str,
) -> Result<LocalSnapshot, AppError> {
    // Keep the DB's skill rows and the filesystem SSOT at one logical point in
    // time. Skill writers take the matching write guard around both mutations.
    let _skill_state_guard = skill_state_read_guard();

    // Export database to SQL string
    let sql_string = db.export_sql_string_for_sync()?;
    let db_sql = sql_string.into_bytes();

    // Pack skills into deterministic ZIP
    let tmp = tempdir().map_err(|e| {
        io_context_localized(
            "sync.snapshot_tmpdir_failed",
            "创建快照临时目录失败",
            "Failed to create temporary directory for snapshot",
            e,
        )
    })?;
    let skills_zip_path = tmp.path().join(REMOTE_SKILLS_ZIP);
    zip_skills_ssot(&skills_zip_path)?;
    let skills_zip = fs::read(&skills_zip_path).map_err(|e| AppError::io(&skills_zip_path, e))?;

    // Build artifact map and compute hashes
    let mut artifacts = BTreeMap::new();
    artifacts.insert(
        REMOTE_DB_SQL.to_string(),
        ArtifactMeta {
            sha256: sha256_hex(&db_sql),
            size: db_sql.len() as u64,
        },
    );
    artifacts.insert(
        REMOTE_SKILLS_ZIP.to_string(),
        ArtifactMeta {
            sha256: sha256_hex(&skills_zip),
            size: skills_zip.len() as u64,
        },
    );

    let encryption_key = encryption_key.trim();
    let encryption = if encryption_key.is_empty() {
        None
    } else {
        let (salt, key_check) = sync_crypto::compute_key_check(encryption_key).map_err(|e| {
            AppError::Config(format!("Failed to compute encryption key check: {e}"))
        })?;
        Some(SyncEncryptionMeta {
            version: sync_crypto::FORMAT_VERSION,
            salt,
            key_check,
        })
    };

    let snapshot_id = compute_snapshot_id(&artifacts);
    let manifest = SyncManifest {
        format: PROTOCOL_FORMAT.to_string(),
        version: PROTOCOL_VERSION,
        db_compat_version: Some(DB_COMPAT_VERSION),
        device_name: detect_system_device_name().unwrap_or_else(|| "Unknown Device".to_string()),
        created_at: Utc::now().to_rfc3339(),
        artifacts,
        snapshot_id,
        encryption,
    };
    let manifest_bytes =
        serde_json::to_vec_pretty(&manifest).map_err(|e| AppError::JsonSerialize { source: e })?;
    let manifest_hash = sha256_hex(&manifest_bytes);

    Ok(LocalSnapshot {
        db_sql,
        skills_zip,
        manifest_bytes,
        manifest_hash,
    })
}

// ─── Manifest handling ───────────────────────────────────────

/// Compute a deterministic snapshot identity from artifact hashes.
///
/// BTreeMap iteration order is sorted by key, ensuring stability.
pub(crate) fn compute_snapshot_id(artifacts: &BTreeMap<String, ArtifactMeta>) -> String {
    let parts: Vec<String> = artifacts
        .iter()
        .map(|(name, meta)| format!("{}:{}", name, meta.sha256))
        .collect();
    sha256_hex(parts.join("|").as_bytes())
}

pub(crate) fn effective_db_compat_version(
    manifest: &SyncManifest,
    layout: RemoteLayout,
) -> Option<u32> {
    manifest
        .db_compat_version
        .or_else(|| (layout == RemoteLayout::Legacy).then_some(LEGACY_DB_COMPAT_VERSION))
}

pub(crate) fn validate_manifest_compat(
    manifest: &SyncManifest,
    layout: RemoteLayout,
) -> Result<(), AppError> {
    if manifest.format != PROTOCOL_FORMAT {
        return Err(localized(
            "sync.manifest_format_incompatible",
            format!("远端 manifest 格式不兼容: {}", manifest.format),
            format!(
                "Remote manifest format is incompatible: {}",
                manifest.format
            ),
        ));
    }
    if manifest.version != PROTOCOL_VERSION {
        return Err(localized(
            "sync.manifest_version_incompatible",
            format!(
                "远端 manifest 协议版本不兼容: v{} (本地 v{PROTOCOL_VERSION})",
                manifest.version
            ),
            format!(
                "Remote manifest protocol version is incompatible: v{} (local v{PROTOCOL_VERSION})",
                manifest.version
            ),
        ));
    }
    let Some(db_compat_version) = effective_db_compat_version(manifest, layout) else {
        return Err(localized(
            "sync.manifest_db_version_missing",
            "远端 manifest 缺少数据库兼容版本",
            "Remote manifest is missing the database compatibility version.",
        ));
    };
    match layout {
        RemoteLayout::Current if db_compat_version != DB_COMPAT_VERSION => {
            return Err(localized(
                "sync.manifest_db_version_incompatible",
                format!(
                    "远端数据库快照版本不兼容: db-v{db_compat_version} (本地 db-v{DB_COMPAT_VERSION})"
                ),
                format!(
                    "Remote database snapshot version is incompatible: db-v{db_compat_version} (local db-v{DB_COMPAT_VERSION})"
                ),
            ));
        }
        RemoteLayout::Legacy if db_compat_version > DB_COMPAT_VERSION => {
            return Err(localized(
                "sync.manifest_db_version_incompatible",
                format!(
                    "远端数据库快照版本不兼容: db-v{db_compat_version} (本地最高支持 db-v{DB_COMPAT_VERSION})"
                ),
                format!(
                    "Remote database snapshot version is incompatible: db-v{db_compat_version} (local supports up to db-v{DB_COMPAT_VERSION})"
                ),
            ));
        }
        _ => {}
    }
    Ok(())
}

// ─── Artifact verification ───────────────────────────────────

pub(crate) fn validate_artifact_size_limit(artifact_name: &str, size: u64) -> Result<(), AppError> {
    if size > MAX_SYNC_ARTIFACT_BYTES {
        let max_mb = MAX_SYNC_ARTIFACT_BYTES / 1024 / 1024;
        return Err(localized(
            "sync.artifact_too_large",
            format!("artifact {artifact_name} 超过下载上限({} MB)", max_mb),
            format!(
                "Artifact {artifact_name} exceeds download limit ({} MB)",
                max_mb
            ),
        ));
    }
    Ok(())
}

/// Verify that downloaded artifact bytes match the expected size and SHA-256 hash.
pub(crate) fn verify_artifact(
    bytes: &[u8],
    artifact_name: &str,
    meta: &ArtifactMeta,
) -> Result<(), AppError> {
    // Quick size check before expensive hash
    if bytes.len() as u64 != meta.size {
        return Err(localized(
            "sync.artifact_size_mismatch",
            format!(
                "artifact {artifact_name} 大小不匹配 (expected: {}, got: {})",
                meta.size,
                bytes.len(),
            ),
            format!(
                "Artifact {artifact_name} size mismatch (expected: {}, got: {})",
                meta.size,
                bytes.len(),
            ),
        ));
    }

    let actual_hash = sha256_hex(bytes);
    if actual_hash != meta.sha256 {
        return Err(localized(
            "sync.artifact_hash_mismatch",
            format!(
                "artifact {artifact_name} SHA256 校验失败 (expected: {}..., got: {}...)",
                meta.sha256.get(..8).unwrap_or(&meta.sha256),
                actual_hash.get(..8).unwrap_or(&actual_hash),
            ),
            format!(
                "Artifact {artifact_name} SHA256 verification failed (expected: {}..., got: {}...)",
                meta.sha256.get(..8).unwrap_or(&meta.sha256),
                actual_hash.get(..8).unwrap_or(&actual_hash),
            ),
        ));
    }
    Ok(())
}

// ─── Snapshot application ────────────────────────────────────

pub(crate) fn apply_snapshot(
    db: &crate::database::Database,
    db_sql: &[u8],
    skills_zip: &[u8],
) -> Result<(), AppError> {
    let sql_str = std::str::from_utf8(db_sql).map_err(|e| {
        localized(
            "sync.sql_not_utf8",
            format!("SQL 非 UTF-8: {e}"),
            format!("SQL is not valid UTF-8: {e}"),
        )
    })?;
    // Exclude installs, uninstalls, updates, and local projection while Skills
    // are backed up/replaced and the corresponding database snapshot is applied.
    let _skill_state_guard = skill_state_write_guard();
    let skills_backup = backup_current_skills()?;

    // Replace skills first, then import database; roll back skills on DB failure.
    restore_skills_zip(skills_zip)?;

    if let Err(db_err) = db.import_sql_string_for_sync(sql_str) {
        return Err(skills_backup.rollback_after_import_error(db_err));
    }

    Ok(())
}

// ─── Utilities ───────────────────────────────────────────────

pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    format!("{:x}", hasher.finalize())
}

pub(crate) fn detect_system_device_name() -> Option<String> {
    let env_name = ["CC_SWITCH_DEVICE_NAME", "COMPUTERNAME", "HOSTNAME"]
        .iter()
        .filter_map(|key| std::env::var(key).ok())
        .find_map(|value| normalize_device_name(&value));

    if env_name.is_some() {
        return env_name;
    }

    let mut command = Command::new("hostname");
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        command.creation_flags(0x0800_0000);
    }
    let output = command.output().ok()?;
    if !output.status.success() {
        return None;
    }
    let hostname = String::from_utf8(output.stdout).ok()?;
    normalize_device_name(&hostname)
}

pub(crate) fn normalize_device_name(raw: &str) -> Option<String> {
    let compact = raw
        .chars()
        .fold(String::with_capacity(raw.len()), |mut acc, ch| {
            if ch.is_whitespace() {
                acc.push(' ');
            } else if !ch.is_control() {
                acc.push(ch);
            }
            acc
        });
    let normalized = compact.split_whitespace().collect::<Vec<_>>().join(" ");
    let trimmed = normalized.trim();
    if trimmed.is_empty() {
        return None;
    }

    let limited = trimmed
        .chars()
        .take(MAX_DEVICE_NAME_LEN)
        .collect::<String>();
    if limited.is_empty() {
        None
    } else {
        Some(limited)
    }
}

// ─── Sync status persistence ─────────────────────────────────

pub(crate) fn persist_sync_success_best_effort<S, F>(
    settings: &mut S,
    manifest_hash: String,
    etag: Option<String>,
    persist_fn: F,
) -> bool
where
    F: FnOnce(&mut S, String, Option<String>) -> Result<(), AppError>,
{
    match persist_fn(settings, manifest_hash, etag) {
        Ok(()) => true,
        Err(err) => {
            log::warn!("[Sync] Persist sync status failed, keep operation success: {err}");
            false
        }
    }
}

// ─── Tests ───────────────────────────────────────────────────

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

    #[tokio::test]
    async fn transport_failure_reason_reports_send_failure_with_cause() {
        // #9559: a server dropping the connection mid-PUT is a send failure, not a
        // request build failure, and the cause must survive into the message.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        tokio::spawn(async move {
            if let Ok((socket, _)) = listener.accept().await {
                drop(socket);
            }
        });

        let err = reqwest::Client::builder()
            .no_proxy()
            .build()
            .unwrap()
            .put(format!(
                "http://127.0.0.1:{port}/dav/db.sql?token=secret-token"
            ))
            .body(vec![0u8; 64 * 1024])
            .send()
            .await
            .expect_err("connection is dropped before a response");
        assert!(err.is_request() && !err.is_connect() && !err.is_builder());

        let (zh, en) = transport_failure_reason(err);
        assert!(zh.starts_with("发送失败: error sending request"), "{zh}");
        assert!(
            en.starts_with("failed to send: error sending request: "),
            "{en}"
        );
        assert!(!en.contains("secret-token"), "{en}");
    }

    #[test]
    fn transfer_timeout_grows_with_payload_size() {
        assert_eq!(transfer_timeout(0), Duration::from_secs(300));
        // #8428: a ~90 MiB skills.zip took ~927 s at ~99 KiB/s; the budget must
        // cover it with room to spare instead of cutting off at 300 s.
        let skills_zip = transfer_timeout(94_218_061);
        assert!(skills_zip > Duration::from_secs(927 * 2), "{skills_zip:?}");
        assert!(transfer_timeout(MAX_SYNC_ARTIFACT_BYTES) > transfer_timeout(94_218_061));
    }

    #[tokio::test]
    async fn webdav_and_s3_operations_share_one_sync_mutex() {
        let webdav_lock = crate::services::webdav_sync::sync_mutex();
        let s3_lock = crate::services::s3_sync::sync_mutex();
        assert!(
            std::ptr::eq(webdav_lock, s3_lock),
            "every transport must expose the same global sync lock"
        );

        let guard = webdav_lock.lock().await;
        assert!(s3_lock.try_lock().is_err());
        drop(guard);
        assert!(s3_lock.try_lock().is_ok());
    }

    fn artifact(sha256: &str, size: u64) -> ArtifactMeta {
        ArtifactMeta {
            sha256: sha256.to_string(),
            size,
        }
    }

    #[test]
    fn auto_sync_table_filter_covers_shared_configuration() {
        for table in [
            "providers",
            "provider_endpoints",
            "mcp_servers",
            "prompts",
            "skills",
            "skill_repos",
            "profiles",
            "settings",
            "proxy_config",
        ] {
            assert!(
                should_trigger_auto_sync_for_table(table),
                "{table} should trigger an automatic snapshot upload"
            );
        }

        assert!(should_trigger_auto_sync_for_table("  PROFILES  "));
        for table in [
            "proxy_request_logs",
            "provider_health",
            "session_log_sync",
            "model_pricing",
        ] {
            assert!(
                !should_trigger_auto_sync_for_table(table),
                "{table} should not trigger automatic snapshot upload"
            );
        }
    }

    #[test]
    fn snapshot_id_is_stable() {
        let mut artifacts = BTreeMap::new();
        artifacts.insert("db.sql".to_string(), artifact("abc123", 100));
        artifacts.insert("skills.zip".to_string(), artifact("def456", 200));

        let id1 = compute_snapshot_id(&artifacts);
        let id2 = compute_snapshot_id(&artifacts);
        assert_eq!(id1, id2);
    }

    #[test]
    fn snapshot_id_changes_with_artifacts() {
        let mut a1 = BTreeMap::new();
        a1.insert("db.sql".to_string(), artifact("hash-a", 1));

        let mut a2 = BTreeMap::new();
        a2.insert("db.sql".to_string(), artifact("hash-b", 1));

        assert_ne!(compute_snapshot_id(&a1), compute_snapshot_id(&a2));
    }

    #[test]
    fn sha256_hex_is_correct() {
        let hash = sha256_hex(b"hello");
        assert_eq!(
            hash,
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }

    #[test]
    fn persist_best_effort_returns_true_on_success() {
        let mut dummy = ();
        let ok = persist_sync_success_best_effort(
            &mut dummy,
            "hash".to_string(),
            Some("etag".to_string()),
            |_settings, _hash, _etag| Ok(()),
        );
        assert!(ok);
    }

    #[test]
    fn persist_best_effort_returns_false_on_error() {
        let mut dummy = ();
        let ok = persist_sync_success_best_effort(
            &mut dummy,
            "hash".to_string(),
            None,
            |_settings, _hash, _etag| Err(AppError::Config("boom".to_string())),
        );
        assert!(!ok);
    }

    fn manifest_with(format: &str, version: u32, db_compat_version: Option<u32>) -> SyncManifest {
        let mut artifacts = BTreeMap::new();
        artifacts.insert("db.sql".to_string(), artifact("abc", 1));
        artifacts.insert("skills.zip".to_string(), artifact("def", 2));
        SyncManifest {
            format: format.to_string(),
            version,
            db_compat_version,
            device_name: "My MacBook".to_string(),
            created_at: "2026-02-12T00:00:00Z".to_string(),
            artifacts,
            snapshot_id: "snap-1".to_string(),
            encryption: None,
        }
    }

    #[test]
    fn validate_manifest_compat_accepts_supported_manifest() {
        let manifest = manifest_with(PROTOCOL_FORMAT, PROTOCOL_VERSION, Some(DB_COMPAT_VERSION));
        assert!(validate_manifest_compat(&manifest, RemoteLayout::Current).is_ok());
    }

    #[test]
    fn validate_manifest_compat_rejects_wrong_format() {
        let manifest = manifest_with("other-format", PROTOCOL_VERSION, Some(DB_COMPAT_VERSION));
        assert!(validate_manifest_compat(&manifest, RemoteLayout::Current).is_err());
    }

    #[test]
    fn validate_manifest_compat_rejects_wrong_version() {
        let manifest = manifest_with(
            PROTOCOL_FORMAT,
            PROTOCOL_VERSION + 1,
            Some(DB_COMPAT_VERSION),
        );
        assert!(validate_manifest_compat(&manifest, RemoteLayout::Current).is_err());
    }

    #[test]
    fn validate_manifest_compat_accepts_legacy_manifest_without_db_compat() {
        let manifest = manifest_with(PROTOCOL_FORMAT, PROTOCOL_VERSION, None);
        assert!(validate_manifest_compat(&manifest, RemoteLayout::Legacy).is_ok());
    }

    #[test]
    fn validate_manifest_compat_rejects_current_manifest_with_wrong_db_compat() {
        let manifest = manifest_with(
            PROTOCOL_FORMAT,
            PROTOCOL_VERSION,
            Some(LEGACY_DB_COMPAT_VERSION),
        );
        assert!(validate_manifest_compat(&manifest, RemoteLayout::Current).is_err());
    }

    #[test]
    fn validate_manifest_compat_rejects_legacy_manifest_from_newer_db_generation() {
        let manifest = manifest_with(
            PROTOCOL_FORMAT,
            PROTOCOL_VERSION,
            Some(DB_COMPAT_VERSION + 1),
        );
        assert!(validate_manifest_compat(&manifest, RemoteLayout::Legacy).is_err());
    }

    #[test]
    fn effective_db_compat_version_defaults_legacy_layout_to_v5() {
        let manifest = manifest_with(PROTOCOL_FORMAT, PROTOCOL_VERSION, None);
        assert_eq!(
            effective_db_compat_version(&manifest, RemoteLayout::Legacy),
            Some(LEGACY_DB_COMPAT_VERSION)
        );
        assert_eq!(
            effective_db_compat_version(&manifest, RemoteLayout::Current),
            None
        );
    }

    #[test]
    fn normalize_device_name_returns_none_for_blank_input() {
        assert_eq!(normalize_device_name("   \n\t  "), None);
    }

    #[test]
    fn normalize_device_name_collapses_whitespace_and_drops_control_chars() {
        assert_eq!(
            normalize_device_name("  Mac\tBook \n Pro\u{0007} "),
            Some("Mac Book Pro".to_string())
        );
    }

    #[test]
    fn normalize_device_name_truncates_to_max_len() {
        let long = "a".repeat(80);
        assert_eq!(normalize_device_name(&long).map(|s| s.len()), Some(64));
    }

    #[test]
    fn manifest_serialization_uses_device_name_only() {
        let manifest = manifest_with(PROTOCOL_FORMAT, PROTOCOL_VERSION, Some(DB_COMPAT_VERSION));
        let value = serde_json::to_value(&manifest).expect("serialize manifest");
        assert!(
            value.get("deviceName").is_some(),
            "manifest should contain deviceName"
        );
        assert_eq!(
            value.get("dbCompatVersion").and_then(|v| v.as_u64()),
            Some(DB_COMPAT_VERSION as u64)
        );
        assert!(
            value.get("deviceId").is_none(),
            "manifest should not contain deviceId"
        );
    }

    #[test]
    fn validate_artifact_size_limit_rejects_oversized_artifacts() {
        let err = validate_artifact_size_limit("skills.zip", MAX_SYNC_ARTIFACT_BYTES + 1)
            .expect_err("artifact larger than limit should be rejected");
        assert!(
            err.to_string().contains("too large") || err.to_string().contains("超过"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn validate_artifact_size_limit_accepts_limit_boundary() {
        assert!(validate_artifact_size_limit("skills.zip", MAX_SYNC_ARTIFACT_BYTES).is_ok());
    }

    #[test]
    fn verify_artifact_rejects_size_mismatch() {
        let meta = artifact("abc123", 100);
        let bytes = vec![0u8; 50];
        let err = verify_artifact(&bytes, "test.bin", &meta)
            .expect_err("size mismatch should be rejected");
        assert!(
            err.to_string().contains("mismatch") || err.to_string().contains("不匹配"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn verify_artifact_rejects_hash_mismatch() {
        let meta = ArtifactMeta {
            sha256: "0000000000000000000000000000000000000000000000000000000000000000".to_string(),
            size: 5,
        };
        let bytes = b"hello";
        let err = verify_artifact(bytes, "test.bin", &meta)
            .expect_err("hash mismatch should be rejected");
        assert!(
            err.to_string().contains("verification failed") || err.to_string().contains("校验失败"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn verify_artifact_accepts_matching_data() {
        let data = b"hello";
        let meta = ArtifactMeta {
            sha256: sha256_hex(data),
            size: data.len() as u64,
        };
        assert!(verify_artifact(data, "test.bin", &meta).is_ok());
    }

    #[test]
    fn encrypt_artifact_passthrough_when_key_blank() {
        let (bytes, mime) =
            encrypt_artifact_for_upload(b"plain sql".to_vec(), "application/sql", "   ").unwrap();
        assert_eq!(bytes, b"plain sql");
        assert_eq!(mime, "application/sql");
        let opened = decrypt_artifact_from_download(bytes, "", "db.sql").unwrap();
        assert_eq!(opened, b"plain sql");
    }

    #[test]
    fn encrypt_and_decrypt_artifact_roundtrip() {
        let (bytes, mime) =
            encrypt_artifact_for_upload(b"secret sql".to_vec(), "application/sql", " my-key ")
                .unwrap();
        assert_eq!(mime, "application/octet-stream");
        assert!(sync_crypto::is_encrypted(&bytes));
        assert_ne!(bytes, b"secret sql");

        let opened = decrypt_artifact_from_download(bytes, "my-key", "db.sql").unwrap();
        assert_eq!(opened, b"secret sql");
    }

    #[test]
    fn decrypt_artifact_requires_key_when_encrypted() {
        let (bytes, _) =
            encrypt_artifact_for_upload(b"secret sql".to_vec(), "application/sql", "my-key")
                .unwrap();
        let err = decrypt_artifact_from_download(bytes, "", "db.sql").unwrap_err();
        assert!(
            err.to_string().contains("encryption key") || err.to_string().contains("加密密钥"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn decrypt_artifact_rejects_wrong_key() {
        let (bytes, _) =
            encrypt_artifact_for_upload(b"secret sql".to_vec(), "application/sql", "right-key")
                .unwrap();
        assert!(decrypt_artifact_from_download(bytes, "wrong-key", "db.sql").is_err());
    }

    fn encrypted_manifest(passphrase: &str) -> SyncManifest {
        let (salt, key_check) = sync_crypto::compute_key_check(passphrase).unwrap();
        let mut manifest =
            manifest_with(PROTOCOL_FORMAT, PROTOCOL_VERSION, Some(DB_COMPAT_VERSION));
        manifest.encryption = Some(SyncEncryptionMeta {
            version: sync_crypto::FORMAT_VERSION,
            salt,
            key_check,
        });
        manifest
    }

    #[test]
    fn manifest_omits_encryption_field_when_unencrypted() {
        let plain = manifest_with(PROTOCOL_FORMAT, PROTOCOL_VERSION, Some(DB_COMPAT_VERSION));
        let val = serde_json::to_value(&plain).unwrap();
        assert!(val.get("encryption").is_none());

        let enc = encrypted_manifest("my-key");
        let enc_val = serde_json::to_value(&enc).unwrap();
        assert_eq!(
            enc_val
                .pointer("/encryption/version")
                .and_then(|v| v.as_u64()),
            Some(sync_crypto::FORMAT_VERSION as u64)
        );
        assert!(enc_val.pointer("/encryption/salt").is_some());
        assert!(enc_val.pointer("/encryption/keyCheck").is_some());
    }

    #[test]
    fn upload_guard_allows_unencrypted_or_empty_remote() {
        assert!(validate_upload_against_remote_encryption(None, "", false).is_ok());
        assert!(validate_upload_against_remote_encryption(None, "new-key", false).is_ok());

        let plain = manifest_with(PROTOCOL_FORMAT, PROTOCOL_VERSION, Some(DB_COMPAT_VERSION));
        assert!(validate_upload_against_remote_encryption(Some(&plain), "", false).is_ok());
        assert!(validate_upload_against_remote_encryption(Some(&plain), "new-key", false).is_ok());
    }

    #[test]
    fn upload_guard_blocks_plaintext_overwrite_unless_explicitly_confirmed() {
        let remote = encrypted_manifest("shared-key");

        // Auto-sync / unconfirmed upload without key is refused
        assert!(validate_upload_against_remote_encryption(Some(&remote), "", false).is_err());
        assert!(validate_upload_against_remote_encryption(Some(&remote), "   ", false).is_err());

        // Explicit manual confirmation allows going back to plaintext
        assert!(validate_upload_against_remote_encryption(Some(&remote), "", true).is_ok());
    }

    #[test]
    fn upload_guard_always_refuses_mismatched_key_even_when_flag_set() {
        let remote = encrypted_manifest("device-a-key");

        // Matching key passes
        assert!(
            validate_upload_against_remote_encryption(Some(&remote), "device-a-key", false).is_ok()
        );
        // Mismatched key is ALWAYS refused
        assert!(
            validate_upload_against_remote_encryption(Some(&remote), "device-b-key", false)
                .is_err()
        );
        assert!(
            validate_upload_against_remote_encryption(Some(&remote), "device-b-key", true).is_err()
        );
    }

    #[test]
    fn upload_guard_refuses_unsupported_encryption_version() {
        let mut remote = encrypted_manifest("shared-key");
        remote.encryption.as_mut().unwrap().version = sync_crypto::FORMAT_VERSION + 1;

        assert!(
            validate_upload_against_remote_encryption(Some(&remote), "shared-key", false).is_err()
        );
        assert!(validate_upload_against_remote_encryption(Some(&remote), "", true).is_err());
    }

    #[test]
    fn download_guard_validates_key_before_fetching_artifacts() {
        let remote = encrypted_manifest("shared-key");
        assert!(validate_download_against_remote_encryption(&remote, "shared-key").is_ok());
        assert!(validate_download_against_remote_encryption(&remote, "").is_err());
        assert!(validate_download_against_remote_encryption(&remote, "wrong-key").is_err());
    }
}