Skip to main content

ipatool_kit/
session.rs

1//! Account session under `~/.ipatool/`.
2
3use std::fs;
4use std::io::Write;
5use std::path::PathBuf;
6
7use ipatool_core::model::Account;
8use serde::{Deserialize, Serialize};
9
10use crate::error::{IpatoolError, Result};
11
12#[derive(Clone, Serialize, Deserialize)]
13struct AccountFile {
14    email: String,
15    #[serde(rename = "passwordToken")]
16    password_token: String,
17    #[serde(rename = "directoryServicesIdentifier", alias = "directoryServicesID")]
18    directory_services_id: String,
19    #[serde(default)]
20    name: String,
21    #[serde(rename = "storeFront", alias = "storefront")]
22    store_front: String,
23    #[serde(default)]
24    pod: Option<String>,
25    /// Never written to disk (always None in AccountFile::from). Kept for
26    /// reading legacy account.json that still contained a password.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    password: Option<String>,
29}
30
31impl std::fmt::Debug for AccountFile {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("AccountFile")
34            .field("email", &self.email)
35            .field("password_token", &"***")
36            .field("directory_services_id", &self.directory_services_id)
37            .field("name", &self.name)
38            .field("store_front", &self.store_front)
39            .field("pod", &self.pod)
40            .field("password", &self.password.as_ref().map(|_| "***"))
41            .finish()
42    }
43}
44
45impl From<&Account> for AccountFile {
46    fn from(a: &Account) -> Self {
47        Self {
48            email: a.email.clone(),
49            password_token: a.password_token.clone(),
50            directory_services_id: a.directory_services_id.clone(),
51            name: a.name.clone(),
52            store_front: a.store_front.clone(),
53            pod: a.pod.clone(),
54            // Never persist Apple ID password in account.json.
55            password: None,
56        }
57    }
58}
59
60impl From<AccountFile> for Account {
61    fn from(a: AccountFile) -> Self {
62        Account {
63            email: a.email,
64            password_token: a.password_token,
65            directory_services_id: a.directory_services_id,
66            name: a.name,
67            store_front: a.store_front,
68            pod: a.pod,
69            password: None,
70        }
71    }
72}
73
74pub fn home_dir() -> Option<PathBuf> {
75    std::env::var_os("HOME")
76        .or_else(|| std::env::var_os("USERPROFILE"))
77        .map(PathBuf::from)
78}
79
80pub fn ipatool_dir() -> Option<PathBuf> {
81    home_dir().map(|h| h.join(".ipatool"))
82}
83
84pub fn account_path() -> Option<PathBuf> {
85    ipatool_dir().map(|d| d.join("account.json"))
86}
87
88pub fn cookies_path() -> Option<PathBuf> {
89    ipatool_dir().map(|d| d.join("cookies.json"))
90}
91
92pub fn cache_dir() -> Option<PathBuf> {
93    ipatool_dir().map(|d| d.join("cache"))
94}
95
96fn chmod_private(path: &std::path::Path) {
97    #[cfg(unix)]
98    {
99        use std::os::unix::fs::PermissionsExt;
100        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
101    }
102}
103
104/// Harden a secret file after an external writer (e.g. cookie jar) created it.
105pub fn chmod_secret_file(path: &std::path::Path) {
106    chmod_private(path);
107}
108
109fn chmod_private_dir(path: &std::path::Path) {
110    #[cfg(unix)]
111    {
112        use std::os::unix::fs::PermissionsExt;
113        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o700));
114    }
115}
116
117pub fn ensure_dirs() -> Result<()> {
118    let Some(root) = ipatool_dir() else {
119        return Err(IpatoolError::msg("HOME not set"));
120    };
121    fs::create_dir_all(&root)?;
122    chmod_private_dir(&root);
123    if let Some(c) = cache_dir() {
124        fs::create_dir_all(&c)?;
125        chmod_private_dir(&c);
126    }
127    Ok(())
128}
129
130fn write_private(path: &std::path::Path, data: &[u8]) -> Result<()> {
131    let mut f = fs::File::create(path)?;
132    f.write_all(data)?;
133    f.sync_all()?;
134    chmod_private(path);
135    Ok(())
136}
137
138pub fn save_account(account: &Account) -> Result<()> {
139    ensure_dirs()?;
140    let path = account_path().ok_or_else(|| IpatoolError::msg("HOME not set"))?;
141    let file = AccountFile::from(account);
142    let json = serde_json::to_string_pretty(&file)?;
143    write_private(&path, json.as_bytes())?;
144    // Keyring keeps full Account including password for silent reauth.
145    let _ = ipatool_core::credential::store_account(account);
146    Ok(())
147}
148
149pub fn load_account() -> Result<Option<Account>> {
150    if let Some(path) = account_path() {
151        if path.is_file() {
152            let raw = fs::read_to_string(&path)?;
153            if let Ok(file) = serde_json::from_str::<AccountFile>(&raw) {
154                let mut acc: Account = file.into();
155                // Overlay password from keyring (never from JSON).
156                if let Ok(Some(kr)) = ipatool_core::credential::load_account() {
157                    if kr.email == acc.email {
158                        acc.password = kr.password;
159                    }
160                }
161                // Scrub legacy plaintext password from disk on next opportunity.
162                return Ok(Some(acc));
163            }
164        }
165    }
166    match ipatool_core::credential::load_account() {
167        Ok(acc) => Ok(acc),
168        Err(_) => Ok(None),
169    }
170}
171
172pub fn delete_account() -> Result<()> {
173    if let Some(path) = account_path() {
174        let _ = fs::remove_file(path);
175    }
176    let _ = ipatool_core::credential::delete_account();
177    Ok(())
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn account_file_never_serializes_password() {
186        let acc = Account {
187            email: "a@b.c".into(),
188            password_token: "tok".into(),
189            directory_services_id: "1".into(),
190            name: "N".into(),
191            store_front: "143441".into(),
192            pod: None,
193            password: Some("secret".into()),
194        };
195        let file = AccountFile::from(&acc);
196        let json = serde_json::to_string(&file).unwrap();
197        assert!(!json.contains("secret"));
198        assert!(!json.contains("\"password\""));
199    }
200}
201
202
203#[cfg(all(test, unix))]
204mod unix_tests {
205    use super::*;
206    use std::os::unix::fs::PermissionsExt;
207
208    #[test]
209    fn write_private_sets_mode_600() {
210        let dir = std::env::temp_dir().join(format!("ipatool-session-test-{}", std::process::id()));
211        let _ = fs::remove_dir_all(&dir);
212        fs::create_dir_all(&dir).unwrap();
213        let path = dir.join("secret.json");
214        write_private(&path, b"{}").unwrap();
215        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
216        assert_eq!(mode, 0o600);
217        let _ = fs::remove_dir_all(&dir);
218    }
219}