rust-sanitize 0.10.0

Deterministic one-way data sanitization engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
use crate::{AppsAddArgs, AppsArgs, AppsEditArgs, AppsRemoveArgs, AppsSubCommand};
use sanitize_engine::processor::FileTypeProfile;
use sanitize_engine::secrets::SecretEntry;
use std::fs;
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Built-in app bundles
// ---------------------------------------------------------------------------
//
// Each app lives in  src/bin/apps/<name>/
//   secrets.yaml  — Vec<SecretEntry>  (optional; omit when the app has none)
//   profile.yaml  — Vec<FileTypeProfile> (optional)
//
// User-defined apps follow the same two-file convention in a directory
// specified by the SANITIZE_APPS_DIR environment variable, falling back to
// ~/.config/sanitize/apps  (XDG-compatible).
//
// The first YAML comment line (# ...) in either file is shown as the
// description in  `sanitize apps`.

/// Compiled content loaded from an app bundle directory.
pub(crate) struct AppBundle {
    pub(crate) secrets: Vec<SecretEntry>,
    pub(crate) profiles: Vec<FileTypeProfile>,
}

pub(crate) struct BuiltinApp {
    pub(crate) name: &'static str,
    pub(crate) description: &'static str,
    /// `Vec<SecretEntry>` YAML; None when the app has no unique secrets patterns.
    pub(crate) secrets_yaml: Option<&'static str>,
    /// `Vec<FileTypeProfile>` YAML; None when the app has no profile rules.
    pub(crate) profile_yaml: Option<&'static str>,
}

pub(crate) const BUILTIN_APPS: &[BuiltinApp] = &[
    BuiltinApp {
        name: "ansible",
        description: "Ansible — group_vars, host_vars, vault credentials",
        secrets_yaml: Some(include_str!("../../../apps/ansible/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/ansible/profile.yaml")),
    },
    BuiltinApp {
        name: "aws-cli",
        description: "AWS CLI — ~/.aws/credentials, ~/.aws/config access keys",
        secrets_yaml: Some(include_str!("../../../apps/aws-cli/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/aws-cli/profile.yaml")),
    },
    BuiltinApp {
        name: "circleci",
        description: "CircleCI — .circleci/config.yml job/step environment variables, docker auth",
        secrets_yaml: Some(include_str!("../../../apps/circleci/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/circleci/profile.yaml")),
    },
    BuiltinApp {
        name: "datadog",
        description: "Datadog Agent — datadog.yaml API keys, proxy credentials, SNMP auth, cluster agent tokens",
        secrets_yaml: Some(include_str!("../../../apps/datadog/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/datadog/profile.yaml")),
    },
    BuiltinApp {
        name: "django",
        description: "Django — .env files, SECRET_KEY, database credentials, third-party API keys",
        secrets_yaml: Some(include_str!("../../../apps/django/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/django/profile.yaml")),
    },
    BuiltinApp {
        name: "docker-compose",
        description: "Docker Compose — compose.yml environment variables, image credentials",
        secrets_yaml: Some(include_str!("../../../apps/docker-compose/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/docker-compose/profile.yaml")),
    },
    BuiltinApp {
        name: "elasticsearch",
        description: "Elasticsearch — elasticsearch.yml, Kibana/Logstash credentials",
        secrets_yaml: Some(include_str!("../../../apps/elasticsearch/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/elasticsearch/profile.yaml")),
    },
    BuiltinApp {
        name: "fstab",
        description: "fstab — /etc/fstab CIFS/SMB credentials, NFS and iSCSI server addresses",
        secrets_yaml: Some(include_str!("../../../apps/fstab/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/fstab/profile.yaml")),
    },
    BuiltinApp {
        name: "github-actions",
        description: "GitHub Actions — workflow env vars, step inputs, container registry credentials",
        secrets_yaml: Some(include_str!("../../../apps/github-actions/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/github-actions/profile.yaml")),
    },
    BuiltinApp {
        name: "gitlab",
        description: "GitLab — CI/CD logs, runner output, .gitlab-ci.yml variables",
        secrets_yaml: Some(include_str!("../../../apps/gitlab/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/gitlab/profile.yaml")),
    },
    BuiltinApp {
        name: "grafana",
        description: "Grafana — grafana.ini admin credentials, provisioning datasource secrets",
        secrets_yaml: Some(include_str!("../../../apps/grafana/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/grafana/profile.yaml")),
    },
    BuiltinApp {
        name: "bruno",
        description: "Bruno — .bru collections and OpenCollection YAML (Bruno 3.0+) credentials",
        secrets_yaml: Some(include_str!("../../../apps/bruno/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/bruno/profile.yaml")),
    },
    BuiltinApp {
        name: "har",
        description: "HAR (HTTP Archive) — browser-captured request/response traffic, auth headers, cookies",
        secrets_yaml: Some(include_str!("../../../apps/har/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/har/profile.yaml")),
    },
    BuiltinApp {
        name: "insomnia",
        description: "Insomnia — workspace exports, request auth, environment variables",
        secrets_yaml: Some(include_str!("../../../apps/insomnia/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/insomnia/profile.yaml")),
    },
    BuiltinApp {
        name: "heroku",
        description: "Heroku — app.json env values, add-on credentials (Postgres, Redis, SendGrid, Mailgun, Cloudinary…)",
        secrets_yaml: Some(include_str!("../../../apps/heroku/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/heroku/profile.yaml")),
    },
    BuiltinApp {
        name: "kubernetes",
        description: "Kubernetes — kubeconfig credentials, Secret manifests, Helm values",
        secrets_yaml: Some(include_str!("../../../apps/kubernetes/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/kubernetes/profile.yaml")),
    },
    BuiltinApp {
        name: "laravel",
        description: "Laravel — .env files, APP_KEY, Pusher, Passport, Stripe secrets",
        secrets_yaml: Some(include_str!("../../../apps/laravel/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/laravel/profile.yaml")),
    },
    BuiltinApp {
        name: "mongodb",
        description: "MongoDB — mongod.conf TLS passwords, .env connection strings",
        secrets_yaml: Some(include_str!("../../../apps/mongodb/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/mongodb/profile.yaml")),
    },
    BuiltinApp {
        name: "mysql",
        description: "MySQL / MariaDB — my.cnf credentials, .env DATABASE_URL",
        secrets_yaml: Some(include_str!("../../../apps/mysql/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/mysql/profile.yaml")),
    },
    BuiltinApp {
        name: "postman",
        description: "Postman — collection credentials, environment variables, auth configs",
        secrets_yaml: Some(include_str!("../../../apps/postman/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/postman/profile.yaml")),
    },
    BuiltinApp {
        name: "nginx",
        description: "Nginx — nginx.conf virtual hosts, proxy upstreams, access/error logs",
        secrets_yaml: Some(include_str!("../../../apps/nginx/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/nginx/profile.yaml")),
    },
    BuiltinApp {
        name: "postgresql",
        description: "PostgreSQL — postgresql.conf, connection strings, pg logs",
        secrets_yaml: Some(include_str!("../../../apps/postgresql/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/postgresql/profile.yaml")),
    },
    BuiltinApp {
        name: "rails",
        description: "Ruby on Rails — database.yml, .env, config/secrets.yml",
        secrets_yaml: Some(include_str!("../../../apps/rails/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/rails/profile.yaml")),
    },
    BuiltinApp {
        name: "redis",
        description: "Redis — redis.conf requirepass/masterauth, .env credentials",
        secrets_yaml: Some(include_str!("../../../apps/redis/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/redis/profile.yaml")),
    },
    BuiltinApp {
        name: "splunk",
        description: "Splunk — outputs.conf, inputs.conf, authentication.conf credentials",
        secrets_yaml: Some(include_str!("../../../apps/splunk/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/splunk/profile.yaml")),
    },
    BuiltinApp {
        name: "spring-boot",
        description:
            "Spring Boot — application.yml, application.properties, datasource credentials",
        secrets_yaml: Some(include_str!("../../../apps/spring-boot/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/spring-boot/profile.yaml")),
    },
    BuiltinApp {
        name: "terraform",
        description: "Terraform — *.tfvars variable files, terraform.tfstate sensitive outputs",
        secrets_yaml: Some(include_str!("../../../apps/terraform/secrets.yaml")),
        profile_yaml: Some(include_str!("../../../apps/terraform/profile.yaml")),
    },
];

/// Return a sorted list of all built-in app names.
pub(crate) fn builtin_app_names() -> Vec<&'static str> {
    BUILTIN_APPS.iter().map(|a| a.name).collect()
}

/// Resolve the user-defined apps directory.
///
/// Checks `SANITIZE_APPS_DIR` first, then falls back to
/// `~/.config/sanitize/apps` (XDG base directory convention).
pub(crate) fn user_apps_dir() -> Option<PathBuf> {
    if let Ok(dir) = std::env::var("SANITIZE_APPS_DIR") {
        if !dir.is_empty() {
            return Some(PathBuf::from(dir));
        }
    }
    std::env::var("HOME").ok().map(|home| {
        PathBuf::from(home)
            .join(".config")
            .join("sanitize")
            .join("apps")
    })
}

/// Parse a YAML file as `T`, returning a clear error on failure.
fn parse_yaml_file<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, String> {
    let content =
        fs::read_to_string(path).map_err(|e| format!("failed to read {}: {e}", path.display()))?;
    serde_yaml_ng::from_str(&content)
        .map_err(|e| format!("failed to parse {}: {e}", path.display()))
}

/// Read the first `# description` comment line from a YAML file, if present.
fn read_app_description(app_dir: &Path) -> String {
    for filename in &["secrets.yaml", "profile.yaml"] {
        let path = app_dir.join(filename);
        if let Ok(content) = fs::read_to_string(&path) {
            if let Some(line) = content.lines().next() {
                if let Some(rest) = line.strip_prefix('#') {
                    let desc = rest.trim().to_string();
                    if !desc.is_empty() {
                        return desc;
                    }
                }
            }
        }
    }
    String::new()
}

/// Ensure a local user copy of a built-in app bundle exists.
///
/// Called automatically when `--app <name>` is used. If the user app directory
/// for `name` does not yet exist, both `profile.yaml` and `secrets.yaml` are
/// copied from the built-in bundle so that:
///
/// - The profile and secrets files are editable without running `sanitize apps edit`.
/// - Discovered literal values from the profile pass can be persisted back into
///   `secrets.yaml` by subsequent runs.
///
/// Returns the path to the user `secrets.yaml` on success, or `None` when the
/// app is not a built-in or the directory could not be created.
///
/// If the directory already exists this is a no-op; existing customisations are
/// never overwritten.
pub(crate) fn ensure_user_app_copy(name: &str) -> Option<PathBuf> {
    let apps_dir = user_apps_dir()?;
    let app_dir = apps_dir.join(name);

    // Already provisioned — return the secrets file path (may or may not exist yet).
    if app_dir.is_dir() {
        return Some(app_dir.join("secrets.yaml"));
    }

    // Only provision built-in apps; custom apps have no source to copy from.
    let entry = BUILTIN_APPS.iter().find(|a| a.name == name)?;

    if let Err(e) = fs::create_dir_all(&app_dir) {
        eprintln!(
            "warning: could not create app directory {}: {e}",
            app_dir.display()
        );
        return None;
    }

    let mut ok = true;

    if let Some(yaml) = entry.profile_yaml {
        let dst = app_dir.join("profile.yaml");
        if let Err(e) = fs::write(&dst, yaml) {
            eprintln!("warning: could not write {}: {e}", dst.display());
            ok = false;
        }
    }

    if let Some(yaml) = entry.secrets_yaml {
        let dst = app_dir.join("secrets.yaml");
        if let Err(e) = fs::write(&dst, yaml) {
            eprintln!("warning: could not write {}: {e}", dst.display());
            ok = false;
        }
    }

    if !ok {
        let _ = fs::remove_dir_all(&app_dir);
        return None;
    }

    Some(app_dir.join("secrets.yaml"))
}

/// Load an app bundle by name.
///
/// Resolution order:
///   1. User apps directory (`SANITIZE_APPS_DIR` or `~/.config/sanitize/apps/<name>/`)
///   2. Built-in apps embedded in the binary
pub(crate) fn load_app_bundle(name: &str) -> Result<AppBundle, String> {
    // 1. User-defined app takes precedence over built-in.
    if let Some(apps_dir) = user_apps_dir() {
        let app_dir = apps_dir.join(name);
        if app_dir.is_dir() {
            let secrets_path = app_dir.join("secrets.yaml");
            let profile_path = app_dir.join("profile.yaml");

            let secrets: Vec<SecretEntry> = if secrets_path.exists() {
                parse_yaml_file(&secrets_path)?
            } else {
                vec![]
            };
            let profiles: Vec<FileTypeProfile> = if profile_path.exists() {
                parse_yaml_file(&profile_path)?
            } else {
                vec![]
            };
            return Ok(AppBundle { secrets, profiles });
        }
    }

    // 2. Built-in app.
    let entry = BUILTIN_APPS
        .iter()
        .find(|a| a.name == name)
        .ok_or_else(|| {
            format!(
                "unknown app '{}'. Built-in apps: {}. \
                 Add a custom app at $SANITIZE_APPS_DIR/{} (secrets.yaml / profile.yaml).",
                name,
                builtin_app_names().join(", "),
                name,
            )
        })?;

    let secrets: Vec<SecretEntry> = match entry.secrets_yaml {
        Some(yaml) => serde_yaml_ng::from_str(yaml)
            .map_err(|e| format!("failed to parse built-in secrets for '{}': {e}", name))?,
        None => vec![],
    };
    let profiles: Vec<FileTypeProfile> = match entry.profile_yaml {
        Some(yaml) => serde_yaml_ng::from_str(yaml)
            .map_err(|e| format!("failed to parse built-in profile for '{}': {e}", name))?,
        None => vec![],
    };

    Ok(AppBundle { secrets, profiles })
}

pub(crate) fn validate_app_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("app name cannot be empty".into());
    }
    if !name
        .chars()
        .next()
        .is_some_and(|c| c.is_ascii_alphanumeric())
    {
        return Err(format!(
            "app name '{name}' must start with a letter or digit"
        ));
    }
    if let Some(bad) = name
        .chars()
        .find(|c| !c.is_ascii_alphanumeric() && *c != '-' && *c != '_')
    {
        return Err(format!(
            "app name '{name}' contains invalid character '{bad}'; \
             only letters, digits, hyphens, and underscores are allowed"
        ));
    }
    Ok(())
}

pub(crate) fn run_apps(args: &AppsArgs) -> Result<(), (String, i32)> {
    match &args.command {
        None => run_apps_list(),
        Some(AppsSubCommand::Add(a)) => run_apps_add(a),
        Some(AppsSubCommand::Remove(a)) => run_apps_remove(a),
        Some(AppsSubCommand::Edit(a)) => run_apps_edit(a),
        Some(AppsSubCommand::Dir) => run_apps_dir(),
    }
}

fn run_apps_list() -> Result<(), (String, i32)> {
    let overridden: std::collections::HashSet<String> = user_apps_dir()
        .filter(|d| d.is_dir())
        .map(|d| {
            fs::read_dir(&d)
                .map(|entries| {
                    entries
                        .flatten()
                        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
                        .map(|e| e.file_name().to_string_lossy().to_string())
                        .collect()
                })
                .unwrap_or_default()
        })
        .unwrap_or_default();

    println!("Built-in app bundles (use with --app <name>):\n");
    for app in BUILTIN_APPS {
        if overridden.contains(app.name) {
            println!(
                "  {:<18} {} (overridden by user copy)",
                app.name, app.description
            );
        } else {
            println!("  {:<18} {}", app.name, app.description);
        }
    }

    let apps_dir = user_apps_dir();
    let dir_display = apps_dir
        .as_ref()
        .map(|d| d.display().to_string())
        .unwrap_or_else(|| "~/.config/sanitize/apps".into());

    if let Some(ref dir) = apps_dir {
        if dir.is_dir() {
            let mut user_apps: Vec<(String, String)> = fs::read_dir(dir)
                .map(|entries| {
                    entries
                        .flatten()
                        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
                        .map(|e| {
                            let name = e.file_name().to_string_lossy().to_string();
                            let desc = read_app_description(&e.path());
                            (name, desc)
                        })
                        .collect()
                })
                .unwrap_or_default();
            user_apps.sort_by(|a, b| a.0.cmp(&b.0));

            if !user_apps.is_empty() {
                println!("\nUser-defined apps (from {dir_display}):\n");
                for (name, desc) in &user_apps {
                    if desc.is_empty() {
                        println!("  {name}");
                    } else {
                        println!("  {:<18} {}", name, desc);
                    }
                }
            }
        }
    }

    println!("\nCombine multiple apps:  sanitize file.zip --app gitlab,nginx,postgresql");
    println!(
        "Manage custom apps:     sanitize apps edit <name>        # copy built-in for editing"
    );
    println!("                        sanitize apps add <name> --profile p.yaml --secrets s.yaml");
    println!("                        sanitize apps remove <name> --yes");
    println!("                        sanitize apps dir");
    Ok(())
}

fn run_apps_add(args: &AppsAddArgs) -> Result<(), (String, i32)> {
    validate_app_name(&args.name).map_err(|e| (e, 1))?;

    if args.profile.is_none() && args.secrets_file.is_none() {
        return Err((
            "at least one of --profile or --secrets-file must be provided".into(),
            1,
        ));
    }

    let apps_dir = user_apps_dir().ok_or_else(|| {
        (
            "cannot determine user apps directory: HOME is not set".into(),
            1,
        )
    })?;

    let target_dir = apps_dir.join(&args.name);

    if target_dir.exists() && !args.overwrite {
        return Err((
            format!(
                "app '{}' already exists at {}.\nUse --overwrite to replace it.",
                args.name,
                target_dir.display()
            ),
            1,
        ));
    }

    // Validate files parse correctly before touching the filesystem.
    if let Some(ref path) = args.profile {
        let _profiles: Vec<FileTypeProfile> =
            parse_yaml_file(path).map_err(|e| (format!("--profile: {e}"), 1))?;
    }
    if let Some(ref path) = args.secrets_file {
        let _secrets: Vec<SecretEntry> =
            parse_yaml_file(path).map_err(|e| (format!("--secrets-file: {e}"), 1))?;
    }

    fs::create_dir_all(&target_dir)
        .map_err(|e| (format!("failed to create {}: {e}", target_dir.display()), 1))?;

    if let Some(ref src) = args.profile {
        let dst = target_dir.join("profile.yaml");
        fs::copy(src, &dst).map_err(|e| {
            (
                format!("failed to copy profile to {}: {e}", dst.display()),
                1,
            )
        })?;
    }
    if let Some(ref src) = args.secrets_file {
        let dst = target_dir.join("secrets.yaml");
        fs::copy(src, &dst).map_err(|e| {
            (
                format!("failed to copy secrets to {}: {e}", dst.display()),
                1,
            )
        })?;
    }

    println!("Installed app '{}' → {}", args.name, target_dir.display());
    if args.profile.is_some() {
        println!("  profile.yaml  ✓");
    }
    if args.secrets_file.is_some() {
        println!("  secrets.yaml  ✓");
    }
    println!("\nUse it with:  sanitize <file> --app {}", args.name);
    Ok(())
}

fn run_apps_remove(args: &AppsRemoveArgs) -> Result<(), (String, i32)> {
    validate_app_name(&args.name).map_err(|e| (e, 1))?;

    let apps_dir = user_apps_dir().ok_or_else(|| {
        (
            "cannot determine user apps directory: HOME is not set".into(),
            1,
        )
    })?;

    let target_dir = apps_dir.join(&args.name);

    // Only a user copy (in the apps dir) can be removed.  Refuse when the
    // name is a built-in AND there is no user copy to revert.
    if !target_dir.is_dir() {
        if BUILTIN_APPS.iter().any(|a| a.name == args.name.as_str()) {
            return Err((
                format!(
                    "'{}' is a built-in app — nothing to remove.\n\
                     Use `sanitize apps edit {}` first to create a local copy.",
                    args.name, args.name
                ),
                1,
            ));
        }
        return Err((
            format!(
                "no custom app '{}' found at {}",
                args.name,
                target_dir.display()
            ),
            1,
        ));
    }

    if !args.yes {
        return Err((
            format!(
                "this will permanently delete {}\nRe-run with --yes to confirm.",
                target_dir.display()
            ),
            1,
        ));
    }

    fs::remove_dir_all(&target_dir)
        .map_err(|e| (format!("failed to remove {}: {e}", target_dir.display()), 1))?;

    let is_builtin = BUILTIN_APPS.iter().any(|a| a.name == args.name.as_str());
    println!("Removed app '{}'  ({})", args.name, target_dir.display());
    if is_builtin {
        println!("Built-in '{}' is now active again.", args.name);
    }
    Ok(())
}

fn run_apps_edit(args: &AppsEditArgs) -> Result<(), (String, i32)> {
    validate_app_name(&args.name).map_err(|e| (e, 1))?;

    let apps_dir = user_apps_dir().ok_or_else(|| {
        (
            "cannot determine user apps directory: HOME is not set".into(),
            1,
        )
    })?;

    let target_dir = apps_dir.join(&args.name);

    // Already a user-defined app — just show the path.
    if target_dir.is_dir() {
        println!("'{}' is already in your user apps directory:", args.name);
        println!("  {}", target_dir.display());
        for file in &["profile.yaml", "secrets.yaml"] {
            let p = target_dir.join(file);
            if p.exists() {
                println!("  {}", p.display());
            }
        }
        println!("\nEdits here already override the built-in.");
        println!("To revert:  sanitize apps remove {} --yes", args.name);
        return Ok(());
    }

    // Must be a built-in.
    let entry = BUILTIN_APPS
        .iter()
        .find(|a| a.name == args.name.as_str())
        .ok_or_else(|| {
            format!(
                "unknown app '{}'. Built-in apps: {}.",
                args.name,
                builtin_app_names().join(", ")
            )
        })
        .map_err(|e| (e, 1))?;

    fs::create_dir_all(&target_dir)
        .map_err(|e| (format!("failed to create {}: {e}", target_dir.display()), 1))?;

    let mut wrote: Vec<PathBuf> = vec![];

    if let Some(yaml) = entry.profile_yaml {
        let dst = target_dir.join("profile.yaml");
        fs::write(&dst, yaml)
            .map_err(|e| (format!("failed to write {}: {e}", dst.display()), 1))?;
        wrote.push(dst);
    }
    if let Some(yaml) = entry.secrets_yaml {
        let dst = target_dir.join("secrets.yaml");
        fs::write(&dst, yaml)
            .map_err(|e| (format!("failed to write {}: {e}", dst.display()), 1))?;
        wrote.push(dst);
    }

    println!(
        "Copied built-in '{}' to your user apps directory:",
        args.name
    );
    for path in &wrote {
        println!("  {}", path.display());
    }
    println!(
        "\nEdits here override the built-in — use --app {} as usual.",
        args.name
    );
    println!("To revert:  sanitize apps remove {} --yes", args.name);

    Ok(())
}

fn run_apps_dir() -> Result<(), (String, i32)> {
    let apps_dir = user_apps_dir().ok_or_else(|| {
        (
            "cannot determine user apps directory: HOME is not set".into(),
            1,
        )
    })?;

    println!("{}", apps_dir.display());

    if !apps_dir.exists() {
        eprintln!(
            "note: directory does not exist yet — it will be created automatically by `sanitize apps add`"
        );
    }

    Ok(())
}