use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::traits::{NativeObserver, SyncTransport};
use crate::helper::{CloudKitHelper, HelperConfig};
use crate::transcripts::{self as sync_core, CloudKitEnvironment, TranscriptSyncProfile};
use crate::{AuthProvider, Backend, SyncObserver};
pub struct CloudKitConfig {
pub profile: TranscriptSyncProfile,
pub container: String,
pub zone: String,
pub subscription: String,
pub team_id: String,
pub request_timeout_secs: u64,
pub native: Option<Arc<dyn NativeObserver>>,
pub event_sink: fn(&str, &str),
}
fn check_ident(what: &str, value: &str) -> Result<(), String> {
let ok = !value.is_empty()
&& value.len() <= 255
&& !value.starts_with('-')
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
if ok {
Ok(())
} else {
Err(format!(
"cloudkit config: {what} must be 1..=255 ASCII letters, digits, '.', '_' or '-', not starting with '-'"
))
}
}
fn environment() -> Result<CloudKitEnvironment, String> {
sync_core::requested_environment()
}
fn env_or_production() -> CloudKitEnvironment {
environment().unwrap_or(CloudKitEnvironment::Production)
}
struct TelemetryObserver {
sink: fn(&str, &str),
native: Option<Arc<dyn NativeObserver>>,
}
impl SyncObserver for TelemetryObserver {
fn event(&self, name: &'static str, detail: &str) {
if name == "zone_recreated" {
if let Some(native) = &self.native {
native.invalidate_subscription();
}
}
(self.sink)(&format!("cloud_sync_{name}"), &super::safe_detail(detail));
}
}
fn verify_signed_environment(env: CloudKitEnvironment, path: &Path) -> Result<(), String> {
let mut command = rightkit_child_process::OwnedCommand::new("/usr/bin/codesign");
command
.command_mut()
.args(["-d", "--entitlements", ":-"])
.arg(path);
let options =
rightkit_child_process::CaptureOptions::default().timeout(Duration::from_secs(15));
let signed = rightkit_child_process::run_command_capture(command, None, &options)
.ok()
.filter(|output| !output.timed_out && !output.stdout.truncated)
.and_then(|output| {
sync_core::parse_entitlement_environment(&String::from_utf8_lossy(&output.stdout.bytes))
});
sync_core::check_helper_environment(env, signed)
}
pub struct CloudKitTransport {
profile: TranscriptSyncProfile,
container: String,
zone: String,
subscription: String,
team_id: String,
request_timeout: Duration,
sink: fn(&str, &str),
native: Option<Arc<dyn NativeObserver>>,
helper: Mutex<Option<CloudKitHelper>>,
}
impl CloudKitTransport {
pub fn new(config: CloudKitConfig) -> Result<Self, String> {
check_ident("container", &config.container)?;
check_ident("zone", &config.zone)?;
check_ident("subscription", &config.subscription)?;
if !rightkit_child_process::is_team_id(&config.team_id) {
return Err("cloudkit config: team_id is not an Apple team identifier".to_string());
}
let native = config
.native
.filter(|_| sync_core::native_observer_allowed(env_or_production()));
Ok(Self {
profile: config.profile,
container: config.container,
zone: config.zone,
subscription: config.subscription,
team_id: config.team_id,
request_timeout: Duration::from_secs(config.request_timeout_secs.clamp(5, 600)),
sink: config.event_sink,
native,
helper: Mutex::new(None),
})
}
fn emit(&self, name: &str, detail: &str) {
(self.sink)(name, &super::safe_detail(detail));
}
fn existing_helper(&self) -> Result<Option<CloudKitHelper>, String> {
Ok(self
.helper
.lock()
.map_err(|_| "cloud sync helper lock poisoned".to_string())?
.clone())
}
fn helper(&self) -> Result<CloudKitHelper, String> {
if let Some(helper) = self.existing_helper()? {
return Ok(helper);
}
let env = environment()?;
let name = self.profile.helper_bundle_name(env);
let placed =
rightkit_child_process::resolve_bundled_login_item(name).map_err(|reason| {
self.emit(
"helper_path_rejected",
&format!("helper={name} reason={reason}"),
);
"CloudKit helper not bundled — CloudKit sync unavailable".to_string()
})?;
let path = rightkit_child_process::verify_team_signature(&placed, &self.team_id).map_err(
|reason| {
self.emit(
"helper_untrusted",
&format!("helper={name} reason={reason}"),
);
"CloudKit helper is not signed by the expected team".to_string()
},
)?;
verify_signed_environment(env, &path)?;
let config = HelperConfig::new(path)
.cloudkit(&self.container, &self.zone, &self.subscription)
.timeout(self.request_timeout);
let helper = CloudKitHelper::new(
config,
Arc::new(TelemetryObserver {
sink: self.sink,
native: self.native.clone(),
}),
);
helper.auth().set_enabled(false);
let mut guard = self
.helper
.lock()
.map_err(|_| "cloud sync helper lock poisoned".to_string())?;
if let Some(winner) = guard.as_ref() {
return Ok(winner.clone());
}
*guard = Some(helper.clone());
Ok(helper)
}
}
impl SyncTransport for CloudKitTransport {
fn state_file_name(&self, base: &str) -> String {
sync_core::env_file_name(base, env_or_production())
}
fn legacy_import(&self) -> bool {
env_or_production() == CloudKitEnvironment::Production
}
fn prepare(&self) -> Result<(), String> {
self.helper().map(|_| ())
}
fn backend(&self) -> Result<Arc<dyn Backend>, String> {
Ok(Arc::new(self.helper()?.backend()))
}
fn auth(&self) -> Result<Arc<dyn AuthProvider>, String> {
Ok(Arc::new(self.helper()?.auth()))
}
fn observer(&self) -> Arc<dyn SyncObserver> {
Arc::new(TelemetryObserver {
sink: self.sink,
native: self.native.clone(),
})
}
fn set_enabled(&self, enabled: bool) -> Result<(), String> {
if !enabled {
if let Some(helper) = self.existing_helper()? {
helper.auth().set_enabled(false);
}
return Ok(());
}
self.helper()?.auth().set_enabled(true);
Ok(())
}
fn confirmed_stopped(&self) -> Option<bool> {
match self.existing_helper() {
Ok(Some(helper)) => Some(!helper.auth().enabled()),
_ => None,
}
}
fn native_observer(&self) -> Option<Arc<dyn NativeObserver>> {
self.native.clone()
}
}