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