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