Skip to main content

macfly_core/
plan.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3use std::time::{SystemTime, UNIX_EPOCH};
4
5use serde::{Deserialize, Serialize};
6
7use crate::config::{ProfileConfig, data_dir};
8use crate::error::MacflyError;
9use crate::model::compute_sha256_hex;
10
11/// Eingabeformat, mit dem ein Mensch oder KI-Agent einen Änderungsplan vorschlägt.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct PlanProposal {
14    #[serde(default = "default_schema_version")]
15    pub schema_version: String,
16    #[serde(default)]
17    pub summary: Option<String>,
18    pub operations: Vec<PlanOperation>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22#[serde(tag = "action", rename_all = "snake_case")]
23pub enum PlanOperation {
24    NotesCreate {
25        account: Option<String>,
26        folder: String,
27        title: String,
28        body: String,
29    },
30    NotesAppend {
31        note_id: String,
32        #[serde(default)]
33        expected_revision: Option<String>,
34        text: String,
35    },
36    NotesMove {
37        note_id: String,
38        #[serde(default)]
39        expected_revision: Option<String>,
40        destination_folder: String,
41        #[serde(default)]
42        destination_account: Option<String>,
43    },
44    NotesMoveFolderContents {
45        source_folder_id: String,
46        source_folder_path: String,
47        destination_folder_path: String,
48        #[serde(default)]
49        destination_account: Option<String>,
50    },
51    NotesCreateFolder {
52        account: Option<String>,
53        name: String,
54        #[serde(default)]
55        parent_folder: Option<String>,
56    },
57    NotesDeleteEmptyFolder {
58        folder_id: String,
59        folder_name: String,
60    },
61    MailCreateDraft {
62        #[serde(default)]
63        account: Option<String>,
64        to: Vec<String>,
65        #[serde(default)]
66        cc: Vec<String>,
67        subject: String,
68        body: String,
69        /// Optional: Name einer Signatur in Apple Mail (sonst aus config.json).
70        #[serde(default)]
71        signature_name: Option<String>,
72        /// Optional: Bezugs-Mail-ID (für Antwort-Kontext im Entwurf).
73        #[serde(default)]
74        reply_to_local_id: Option<String>,
75    },
76    MailMarkRead {
77        local_id: String,
78        account: String,
79        mailbox: String,
80        read: bool,
81    },
82    MailMove {
83        local_id: String,
84        account: String,
85        from_mailbox: String,
86        to_mailbox: String,
87    },
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum RiskLevel {
93    Low,
94    Medium,
95    High,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "snake_case")]
100pub enum Reversibility {
101    Reversible,
102    BestEffort,
103    Irreversible,
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "snake_case")]
108pub enum PlanStatus {
109    PendingApproval,
110    Approved,
111    Applied,
112    Failed,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct StoredPlan {
117    pub schema_version: String,
118    pub plan_id: String,
119    pub profile: String,
120    pub summary: String,
121    pub created_at_unix: u64,
122    pub expires_at_unix: u64,
123    pub status: PlanStatus,
124    pub risk_level: RiskLevel,
125    pub reversibility: Reversibility,
126    pub plan_hash: String,
127    pub approval_code: String,
128    #[serde(default)]
129    pub approved_at_unix: Option<u64>,
130    #[serde(default)]
131    pub applied_at_unix: Option<u64>,
132    pub operations: Vec<PlanOperation>,
133    pub preview_lines: Vec<String>,
134}
135
136impl PlanOperation {
137    pub fn risk_level(&self) -> RiskLevel {
138        match self {
139            Self::NotesCreate { .. }
140            | Self::NotesCreateFolder { .. }
141            | Self::MailCreateDraft { .. }
142            | Self::MailMarkRead { .. } => RiskLevel::Low,
143            Self::NotesAppend { .. }
144            | Self::NotesMove { .. }
145            | Self::NotesMoveFolderContents { .. }
146            | Self::NotesDeleteEmptyFolder { .. }
147            | Self::MailMove { .. } => RiskLevel::Medium,
148        }
149    }
150
151    pub fn reversibility(&self) -> Reversibility {
152        match self {
153            Self::NotesAppend { .. } => Reversibility::BestEffort,
154            _ => Reversibility::Reversible,
155        }
156    }
157
158    pub fn preview(&self) -> String {
159        match self {
160            Self::NotesCreate {
161                folder,
162                title,
163                body,
164                ..
165            } => format!(
166                "[notes.create] Neue Notiz '{}' in Ordner '{}' ({} Zeichen)",
167                title,
168                folder,
169                body.chars().count()
170            ),
171            Self::NotesAppend { note_id, text, .. } => format!(
172                "[notes.append] An Notiz '{}' anhängen ({} Zeichen)",
173                note_id,
174                text.chars().count()
175            ),
176            Self::NotesMove {
177                note_id,
178                destination_folder,
179                ..
180            } => format!(
181                "[notes.move] Notiz '{}' → Ordner '{}'",
182                note_id, destination_folder
183            ),
184            Self::NotesMoveFolderContents {
185                source_folder_path,
186                destination_folder_path,
187                ..
188            } => format!(
189                "[notes.move_folder_contents] Alle Notizen aus '{}' → '{}'",
190                source_folder_path, destination_folder_path
191            ),
192            Self::NotesCreateFolder {
193                name,
194                parent_folder,
195                ..
196            } => match parent_folder {
197                Some(p) => format!("[notes.create_folder] Neuer Unterordner '{p}/{name}'"),
198                None => format!("[notes.create_folder] Neuer Ordner '{name}'"),
199            },
200            Self::NotesDeleteEmptyFolder {
201                folder_id,
202                folder_name,
203            } => format!(
204                "[notes.delete_empty_folder] Leeren Ordner '{}' ({}) entfernen",
205                folder_name, folder_id
206            ),
207            Self::MailCreateDraft {
208                to,
209                subject,
210                body,
211                ..
212            } => format!(
213                "[mail.create_draft] Entwurf an {} | Betreff: '{}' ({} Zeichen, KEIN Versand)",
214                to.join(", "),
215                subject,
216                body.chars().count()
217            ),
218            Self::MailMarkRead {
219                local_id,
220                mailbox,
221                read,
222                ..
223            } => format!(
224                "[mail.mark_read] Mail '{}' in '{}' als {} markieren",
225                local_id,
226                mailbox,
227                if *read { "gelesen" } else { "ungelesen" }
228            ),
229            Self::MailMove {
230                local_id,
231                from_mailbox,
232                to_mailbox,
233                ..
234            } => format!(
235                "[mail.move] Mail '{}' von '{}' → '{}'",
236                local_id, from_mailbox, to_mailbox
237            ),
238        }
239    }
240
241    pub fn validate_against_profile(
242        &self,
243        profile_name: &str,
244        profile: &ProfileConfig,
245    ) -> Result<(), MacflyError> {
246        match self {
247            Self::NotesCreate {
248                account, folder, ..
249            } => {
250                if let Some(acc) = account
251                    && !profile.notes.is_account_allowed(acc)
252                {
253                    return Err(MacflyError::ScopeDenied(format!(
254                        "Notes-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
255                    )));
256                }
257                if !profile.notes.is_folder_allowed(folder) {
258                    return Err(MacflyError::ScopeDenied(format!(
259                        "Zielordner '{folder}' im Profil '{profile_name}' gesperrt"
260                    )));
261                }
262            }
263            Self::NotesMove {
264                destination_folder,
265                destination_account,
266                ..
267            } => {
268                if let Some(acc) = destination_account
269                    && !profile.notes.is_account_allowed(acc)
270                {
271                    return Err(MacflyError::ScopeDenied(format!(
272                        "Ziel-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
273                    )));
274                }
275                if !profile.notes.is_folder_allowed(destination_folder) {
276                    return Err(MacflyError::ScopeDenied(format!(
277                        "Zielordner '{destination_folder}' im Profil '{profile_name}' gesperrt"
278                    )));
279                }
280            }
281            Self::NotesMoveFolderContents {
282                source_folder_path,
283                destination_folder_path,
284                destination_account,
285                ..
286            } => {
287                if let Some(acc) = destination_account
288                    && !profile.notes.is_account_allowed(acc)
289                {
290                    return Err(MacflyError::ScopeDenied(format!(
291                        "Ziel-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
292                    )));
293                }
294                if !profile.notes.is_folder_allowed(source_folder_path)
295                    || !profile.notes.is_folder_allowed(destination_folder_path)
296                {
297                    return Err(MacflyError::ScopeDenied(format!(
298                        "Verschiebung '{source_folder_path}' → '{destination_folder_path}' im Profil '{profile_name}' gesperrt"
299                    )));
300                }
301            }
302            Self::NotesCreateFolder { account, name, .. } => {
303                if let Some(acc) = account
304                    && !profile.notes.is_account_allowed(acc)
305                {
306                    return Err(MacflyError::ScopeDenied(format!(
307                        "Notes-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
308                    )));
309                }
310                if !profile.notes.is_folder_allowed(name) {
311                    return Err(MacflyError::ScopeDenied(format!(
312                        "Ordnername '{name}' im Profil '{profile_name}' gesperrt"
313                    )));
314                }
315            }
316            Self::NotesDeleteEmptyFolder { folder_name, .. } => {
317                if !profile.notes.is_folder_allowed(folder_name) {
318                    return Err(MacflyError::ScopeDenied(format!(
319                        "Ordner '{folder_name}' im Profil '{profile_name}' gesperrt"
320                    )));
321                }
322            }
323            Self::NotesAppend { .. } => {}
324            Self::MailCreateDraft { account, to, .. } => {
325                if to.is_empty() {
326                    return Err(MacflyError::PlanError(
327                        "mail.create_draft benötigt mindestens einen Empfänger in `to`".to_string(),
328                    ));
329                }
330                if let Some(acc) = account
331                    && !profile.mail.is_account_allowed(acc)
332                {
333                    return Err(MacflyError::ScopeDenied(format!(
334                        "Mail-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
335                    )));
336                }
337            }
338            Self::MailMarkRead {
339                account, mailbox, ..
340            } => {
341                if !profile.mail.is_account_allowed(account)
342                    || !profile.mail.is_mailbox_allowed(mailbox)
343                {
344                    return Err(MacflyError::ScopeDenied(format!(
345                        "Postfach '{account}/{mailbox}' im Profil '{profile_name}' gesperrt"
346                    )));
347                }
348            }
349            Self::MailMove {
350                account,
351                from_mailbox,
352                to_mailbox,
353                ..
354            } => {
355                if !profile.mail.is_account_allowed(account)
356                    || !profile.mail.is_mailbox_allowed(from_mailbox)
357                    || !profile.mail.is_mailbox_allowed(to_mailbox)
358                {
359                    return Err(MacflyError::ScopeDenied(format!(
360                        "Mail-Verschiebung in '{account}' im Profil '{profile_name}' gesperrt"
361                    )));
362                }
363            }
364        }
365        Ok(())
366    }
367}
368
369pub struct PlanStore {
370    plans_dir: PathBuf,
371}
372
373impl PlanStore {
374    pub fn default_store() -> Self {
375        Self::new(data_dir().join("plans"))
376    }
377
378    pub fn new(plans_dir: PathBuf) -> Self {
379        Self { plans_dir }
380    }
381
382    pub fn create(
383        &self,
384        profile_name: &str,
385        profile: &ProfileConfig,
386        proposal: PlanProposal,
387        ttl_secs: u64,
388    ) -> Result<StoredPlan, MacflyError> {
389        if proposal.operations.is_empty() {
390            return Err(MacflyError::PlanError(
391                "Änderungsplan enthält keine Operationen".to_string(),
392            ));
393        }
394
395        for op in &proposal.operations {
396            op.validate_against_profile(profile_name, profile)?;
397        }
398
399        let now = now_unix();
400        let canonical_ops = serde_json::to_string(&proposal.operations)?;
401        let hash_input = format!("{profile_name}\n{canonical_ops}");
402        let full_hash = compute_sha256_hex(&hash_input);
403        let plan_hash = format!("sha256:{full_hash}");
404        let approval_code = full_hash[..6].to_ascii_uppercase();
405        let plan_id = format!("plan-{now}-{}", &full_hash[..8]);
406
407        let mut risk_level = proposal
408            .operations
409            .iter()
410            .map(PlanOperation::risk_level)
411            .max()
412            .unwrap_or(RiskLevel::Low);
413        if proposal.operations.len() > 5 && risk_level < RiskLevel::High {
414            risk_level = RiskLevel::High;
415        }
416
417        let reversibility = if proposal
418            .operations
419            .iter()
420            .any(|o| o.reversibility() == Reversibility::Irreversible)
421        {
422            Reversibility::Irreversible
423        } else if proposal
424            .operations
425            .iter()
426            .any(|o| o.reversibility() == Reversibility::BestEffort)
427        {
428            Reversibility::BestEffort
429        } else {
430            Reversibility::Reversible
431        };
432
433        let preview_lines: Vec<String> =
434            proposal.operations.iter().map(PlanOperation::preview).collect();
435        let summary = proposal
436            .summary
437            .unwrap_or_else(|| format!("{} Operation(en)", proposal.operations.len()));
438
439        let plan = StoredPlan {
440            schema_version: "1.0".to_string(),
441            plan_id,
442            profile: profile_name.to_string(),
443            summary,
444            created_at_unix: now,
445            expires_at_unix: now + ttl_secs,
446            status: PlanStatus::PendingApproval,
447            risk_level,
448            reversibility,
449            plan_hash,
450            approval_code,
451            approved_at_unix: None,
452            applied_at_unix: None,
453            operations: proposal.operations,
454            preview_lines,
455        };
456
457        self.save(&plan)?;
458        Ok(plan)
459    }
460
461    pub fn load(&self, plan_id: &str) -> Result<StoredPlan, MacflyError> {
462        let path = self.plan_path(plan_id)?;
463        if !path.exists() {
464            return Err(MacflyError::NotFound(format!(
465                "Plan '{plan_id}' nicht gefunden"
466            )));
467        }
468        let raw = fs::read_to_string(&path)?;
469        let plan: StoredPlan = serde_json::from_str(&raw)?;
470        verify_plan_integrity(&plan)?;
471        Ok(plan)
472    }
473
474    pub fn list(&self) -> Result<Vec<StoredPlan>, MacflyError> {
475        if !self.plans_dir.exists() {
476            return Ok(Vec::new());
477        }
478        let mut plans = Vec::new();
479        for entry in fs::read_dir(&self.plans_dir)? {
480            let entry = entry?;
481            let path = entry.path();
482            if path.extension().and_then(|e| e.to_str()) != Some("json") {
483                continue;
484            }
485            if let Ok(raw) = fs::read_to_string(&path)
486                && let Ok(plan) = serde_json::from_str::<StoredPlan>(&raw)
487            {
488                plans.push(plan);
489            }
490        }
491        plans.sort_by_key(|a| std::cmp::Reverse(a.created_at_unix));
492        Ok(plans)
493    }
494
495    pub fn approve(&self, plan_id: &str, confirm_code: &str) -> Result<StoredPlan, MacflyError> {
496        let mut plan = self.load(plan_id)?;
497        let now = now_unix();
498        if now > plan.expires_at_unix {
499            return Err(MacflyError::ApprovalError(format!(
500                "Plan '{plan_id}' ist abgelaufen (bitte neu erstellen)"
501            )));
502        }
503        if plan.status != PlanStatus::PendingApproval {
504            return Err(MacflyError::ApprovalError(format!(
505                "Plan '{plan_id}' hat Status {:?} und kann nicht erneut freigegeben werden",
506                plan.status
507            )));
508        }
509        if !confirm_code.trim().eq_ignore_ascii_case(&plan.approval_code) {
510            return Err(MacflyError::ApprovalError(format!(
511                "Ungültiger Bestätigungscode (erwartet: {})",
512                plan.approval_code
513            )));
514        }
515        plan.status = PlanStatus::Approved;
516        plan.approved_at_unix = Some(now);
517        self.save(&plan)?;
518        Ok(plan)
519    }
520
521    pub fn save(&self, plan: &StoredPlan) -> Result<(), MacflyError> {
522        ensure_private_dir(&self.plans_dir)?;
523        let path = self.plan_path(&plan.plan_id)?;
524        let json = serde_json::to_string_pretty(plan)?;
525        write_private_file(&path, &format!("{json}\n"))?;
526        Ok(())
527    }
528
529    fn plan_path(&self, plan_id: &str) -> Result<PathBuf, MacflyError> {
530        if plan_id.contains('/') || plan_id.contains('\\') || plan_id.contains("..") {
531            return Err(MacflyError::PlanError(format!(
532                "Ungültige Plan-ID '{plan_id}'"
533            )));
534        }
535        Ok(self.plans_dir.join(format!("{plan_id}.json")))
536    }
537}
538
539pub fn verify_plan_integrity(plan: &StoredPlan) -> Result<(), MacflyError> {
540    let canonical_ops = serde_json::to_string(&plan.operations)?;
541    let expected = format!(
542        "sha256:{}",
543        compute_sha256_hex(&format!("{}\n{}", plan.profile, canonical_ops))
544    );
545    if plan.plan_hash != expected {
546        return Err(MacflyError::ApprovalError(format!(
547            "Integritätsfehler: Plan '{}' wurde nach Erstellung verändert!",
548            plan.plan_id
549        )));
550    }
551    Ok(())
552}
553
554pub fn now_unix() -> u64 {
555    SystemTime::now()
556        .duration_since(UNIX_EPOCH)
557        .map(|d| d.as_secs())
558        .unwrap_or(0)
559}
560
561pub fn ensure_private_dir(path: &Path) -> Result<(), MacflyError> {
562    fs::create_dir_all(path)?;
563    #[cfg(unix)]
564    {
565        use std::os::unix::fs::PermissionsExt;
566        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o700));
567    }
568    Ok(())
569}
570
571pub fn write_private_file(path: &Path, content: &str) -> Result<(), MacflyError> {
572    fs::write(path, content)?;
573    #[cfg(unix)]
574    {
575        use std::os::unix::fs::PermissionsExt;
576        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
577    }
578    Ok(())
579}
580
581fn default_schema_version() -> String {
582    "1.0".to_string()
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588
589    fn temp_store(tag: &str) -> PlanStore {
590        let dir = std::env::temp_dir().join(format!("macfly-test-{tag}-{}", now_unix()));
591        let _ = fs::remove_dir_all(&dir);
592        PlanStore::new(dir)
593    }
594
595    #[test]
596    fn plan_create_approve_and_tamper_detection() {
597        let store = temp_store("tamper");
598        let profile = ProfileConfig::default();
599        let proposal = PlanProposal {
600            schema_version: "1.0".to_string(),
601            summary: Some("Ordner aufräumen".to_string()),
602            operations: vec![PlanOperation::NotesMove {
603                note_id: "x-coredata://123".to_string(),
604                expected_revision: None,
605                destination_folder: "Archiv".to_string(),
606                destination_account: None,
607            }],
608        };
609
610        let plan = store.create("default", &profile, proposal, 600).unwrap();
611        assert_eq!(plan.status, PlanStatus::PendingApproval);
612        assert_eq!(plan.risk_level, RiskLevel::Medium);
613
614        // Falscher Code wird abgewiesen
615        assert!(store.approve(&plan.plan_id, "000000").is_err());
616
617        // Richtiger Code gibt frei
618        let approved = store.approve(&plan.plan_id, &plan.approval_code).unwrap();
619        assert_eq!(approved.status, PlanStatus::Approved);
620
621        // Manipulation der gespeicherten Datei wird erkannt
622        let path = store.plan_path(&plan.plan_id).unwrap();
623        let raw = fs::read_to_string(&path).unwrap().replace("Archiv", "Manipuliert");
624        fs::write(&path, raw).unwrap();
625        assert!(store.load(&plan.plan_id).is_err());
626    }
627
628    #[test]
629    fn blocks_denied_folder_in_plan() {
630        let store = temp_store("scope");
631        let profile = ProfileConfig::default();
632        let proposal = PlanProposal {
633            schema_version: "1.0".to_string(),
634            summary: None,
635            operations: vec![PlanOperation::NotesMove {
636                note_id: "x-coredata://123".to_string(),
637                expected_revision: None,
638                destination_folder: "Passwörter".to_string(),
639                destination_account: None,
640            }],
641        };
642        let err = store.create("default", &profile, proposal, 600).unwrap_err();
643        assert_eq!(err.code(), "SCOPE_DENIED");
644    }
645}