Skip to main content

ma_core/config/
mod.rs

1//! Configuration for ma-core-based daemons.
2//!
3//! Provides [`Config`], a configuration model that supports:
4//!
5//! - native daemon bootstrapping from CLI/env/YAML/defaults via
6//!   [`Config::from_args`]
7//! - storage-agnostic serialization workflows (including wasm) via
8//!   [`Config::from_yaml_str`] and [`Config::to_yaml_string`]
9//!
10//! Native `from_args` resolves fields from (in decreasing priority):
11//!
12//! 1. Explicit CLI arguments (via [`MaArgs`])
13//! 2. `MA_*` environment variables
14//! 3. YAML config file (`XDG_CONFIG_HOME/ma/<slug>.yaml`)
15//! 4. Built-in defaults
16//!
17//! The config path is selected from explicit `--config`, then CLI/environment
18//! slug, then the default slug before YAML is loaded. A YAML `slug` sets the
19//! effective runtime slug only after that selected file has been read.
20//!
21//! # Native compile-time constant requirement
22//!
23//! Binaries using [`Config::from_args`] **must** declare a compile-time
24//! constant:
25//!
26//! ```no_run
27//! const MA_DEFAULT_SLUG: &str = "panteia";
28//! ```
29//!
30//! This constant serves a dual purpose:
31//! - **Default slug** — used for file naming when `--slug` is not set.
32//! - **Env-var prefix** — uppercased to `MA_PANTEIA_*` for env-var lookup.
33//!   This prefix is fixed at compile time and cannot be changed at runtime.
34//!   Only file-naming can be overridden via `--slug`.
35
36#[cfg(not(target_arch = "wasm32"))]
37pub mod cli;
38#[cfg(not(target_arch = "wasm32"))]
39mod logging;
40#[cfg(target_arch = "wasm32")]
41mod logging_wasm;
42pub mod secrets;
43
44#[cfg(not(target_arch = "wasm32"))]
45pub use cli::MaArgs;
46pub use secrets::SecretBundle;
47
48#[cfg(target_arch = "wasm32")]
49use std::path::PathBuf;
50#[cfg(not(target_arch = "wasm32"))]
51use std::path::{Path, PathBuf};
52
53use crate::error::{Error, Result};
54use base64::engine::general_purpose::STANDARD as B64;
55use base64::Engine;
56use noyalib::compat::serde_yaml;
57use serde::{Deserialize, Serialize};
58
59// ─── Defaults ────────────────────────────────────────────────────────────────
60
61const DEFAULT_LOG_LEVEL: &str = "info";
62const DEFAULT_LOG_LEVEL_STDOUT: &str = "info";
63const DEFAULT_DID_RESOLVER_POSITIVE_TTL_SECS: u64 = 60;
64const DEFAULT_DID_RESOLVER_NEGATIVE_TTL_SECS: u64 = 10;
65#[cfg(not(target_arch = "wasm32"))]
66const DEFAULT_KUBO_RPC_URL: &str = "http://127.0.0.1:5001";
67
68// ─── Remote pinning ─────────────────────────────────────────────────────────
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct RemotePinConfig {
72    pub service: String,
73    pub name: String,
74    pub overwrite: bool,
75}
76
77// ─── Config struct ───────────────────────────────────────────────────────────
78
79/// Runtime configuration for a ma daemon.
80///
81/// Build via [`Config::from_args`] on native targets or via YAML/string
82/// serialization helpers on wasm.
83#[derive(Debug, Clone)]
84pub struct Config {
85    /// Short printable slug identifying this daemon instance.
86    /// Used in default bundle and log file names, and in the default config
87    /// filename when selected through CLI/environment before YAML is read.
88    pub slug: String,
89
90    /// Log level written to the log file (e.g. `"info"`, `"debug"`).
91    pub log_level: String,
92
93    /// Log level written to stdout.
94    pub log_level_stdout: String,
95
96    /// Cache TTL (seconds) for successful DID document resolutions.
97    /// Set to `0` to disable positive cache entries.
98    pub did_resolver_positive_ttl_secs: u64,
99
100    /// Cache TTL (seconds) for failed DID document resolutions.
101    /// Set to `0` to disable negative cache entries.
102    pub did_resolver_negative_ttl_secs: u64,
103
104    /// Path to the log file. `None` → resolved to `XDG_DATA_HOME/ma/<slug>.log`
105    /// on first use.
106    pub log_file: Option<PathBuf>,
107
108    #[cfg(not(target_arch = "wasm32"))]
109    /// Kubo JSON-RPC API URL.
110    pub kubo_rpc_url: String,
111
112    #[cfg(not(target_arch = "wasm32"))]
113    /// IPNS key alias registered in Kubo for this daemon.
114    pub kubo_key_alias: String,
115
116    /// Path to the encrypted secret bundle. `None` → `XDG_CONFIG_HOME/ma/<slug>.bin`.
117    pub secret_bundle: Option<PathBuf>,
118
119    /// Passphrase to unlock the secret bundle.
120    /// In headless configs this is stored in cleartext in the YAML file.
121    pub secret_bundle_passphrase: Option<String>,
122
123    /// Path where this config was loaded from or will be saved to.
124    pub config_path: Option<PathBuf>,
125
126    /// Whether to mirror selected CIDs to a configured Kubo remote pinning service.
127    pub pin_remote: bool,
128
129    /// Kubo remote pinning service name, e.g. `pinata`.
130    pub pin_remote_service: Option<String>,
131
132    /// Operator-visible remote pin name. Callers supply a default when unset.
133    pub pin_remote_name: Option<String>,
134
135    /// Replace older pins with the same managed name after a new pin succeeds.
136    pub pin_overwrite: bool,
137
138    /// Extra user-defined YAML keys that are not part of the core schema.
139    /// Preserved during load and save so callers can extend the config freely.
140    pub extra: serde_yaml::Mapping,
141}
142
143/// Browser-friendly identity export payload.
144///
145/// Contains serialized config text and an encrypted secret bundle encoded as
146/// base64 so it can be stored or copied as plain JSON.
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct BrowserIdentityExport {
149    pub version: u8,
150    pub config_yaml: String,
151    pub encrypted_secret_bundle_base64: String,
152}
153
154impl BrowserIdentityExport {
155    pub fn new(config_yaml: String, encrypted_secret_bundle: &[u8]) -> Self {
156        Self {
157            version: 1,
158            config_yaml,
159            encrypted_secret_bundle_base64: B64.encode(encrypted_secret_bundle),
160        }
161    }
162
163    pub fn encrypted_secret_bundle_bytes(&self) -> Result<Vec<u8>> {
164        B64.decode(self.encrypted_secret_bundle_base64.as_bytes())
165            .map_err(|e| Error::Config(format!("invalid encrypted bundle base64: {e}")))
166    }
167
168    pub fn to_json_string(&self) -> Result<String> {
169        serde_json::to_string(self)
170            .map_err(|e| Error::Config(format!("failed to serialize browser export: {e}")))
171    }
172
173    pub fn from_json_str(json: &str) -> Result<Self> {
174        serde_json::from_str(json)
175            .map_err(|e| Error::Config(format!("failed to parse browser export JSON: {e}")))
176    }
177}
178
179// ─── XDG path helpers ────────────────────────────────────────────────────────
180
181#[cfg(not(target_arch = "wasm32"))]
182fn project_dirs() -> Result<directories::ProjectDirs> {
183    directories::ProjectDirs::from("", "ma", "ma")
184        .ok_or_else(|| Error::Config("cannot determine XDG base directories".to_string()))
185}
186
187/// Default YAML config path: `XDG_CONFIG_HOME/ma/<slug>.yaml`.
188#[cfg(not(target_arch = "wasm32"))]
189pub fn default_config_path(slug: &str) -> Result<PathBuf> {
190    Ok(project_dirs()?.config_dir().join(format!("{slug}.yaml")))
191}
192
193/// Default secret bundle path: `XDG_CONFIG_HOME/ma/<slug>.bin`.
194#[cfg(not(target_arch = "wasm32"))]
195pub fn default_secret_bundle_path(slug: &str) -> Result<PathBuf> {
196    Ok(project_dirs()?.config_dir().join(format!("{slug}.bin")))
197}
198
199/// Default log file path: `XDG_DATA_HOME/ma/<slug>.log`.
200#[cfg(not(target_arch = "wasm32"))]
201pub fn default_log_file_path(slug: &str) -> Result<PathBuf> {
202    Ok(project_dirs()?.data_dir().join(format!("{slug}.log")))
203}
204
205// ─── Secure file I/O ─────────────────────────────────────────────────────────
206
207/// Write `data` to `path`, creating parent directories as needed.
208///
209/// On Unix the file is created (or truncated) with mode `0600`. On other
210/// platforms the file is written without special permission handling.
211#[cfg(not(target_arch = "wasm32"))]
212pub(crate) fn write_secure(path: &Path, data: &[u8]) -> Result<()> {
213    use std::io::Write;
214
215    if let Some(parent) = path.parent() {
216        std::fs::create_dir_all(parent).map_err(|e| {
217            Error::Config(format!("failed to create dir {}: {e}", parent.display()))
218        })?;
219    }
220
221    #[cfg(unix)]
222    let mut file = {
223        use std::os::unix::fs::OpenOptionsExt;
224        std::fs::OpenOptions::new()
225            .write(true)
226            .create(true)
227            .truncate(true)
228            .mode(0o600)
229            .open(path)
230            .map_err(|e| Error::Config(format!("failed to open {}: {e}", path.display())))?
231    };
232
233    #[cfg(not(unix))]
234    let mut file = std::fs::OpenOptions::new()
235        .write(true)
236        .create(true)
237        .truncate(true)
238        .open(path)
239        .map_err(|e| Error::Config(format!("failed to open {}: {e}", path.display())))?;
240
241    file.write_all(data)
242        .map_err(|e| Error::Config(format!("failed to write {}: {e}", path.display())))?;
243
244    // Belt-and-suspenders: also set permissions after creation (handles the
245    // case where the file already existed with wider permissions).
246    #[cfg(unix)]
247    {
248        use std::os::unix::fs::PermissionsExt;
249        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|e| {
250            Error::Config(format!(
251                "failed to set permissions on {}: {e}",
252                path.display()
253            ))
254        })?;
255    }
256
257    Ok(())
258}
259
260/// Check that a file's permissions are not wider than `0600` and log a
261/// warning if they are. Only active on Unix.
262#[cfg(all(not(target_arch = "wasm32"), unix))]
263fn check_permissions(path: &Path) {
264    use std::os::unix::fs::MetadataExt;
265    if let Ok(meta) = std::fs::metadata(path) {
266        let mode = meta.mode() & 0o777;
267        if mode > 0o600 {
268            tracing::warn!(
269                path = %path.display(),
270                mode = format!("{mode:04o}"),
271                "config file has permissions wider than 0600 — consider `chmod 0600 {}`",
272                path.display()
273            );
274        }
275    }
276}
277
278#[cfg(all(not(target_arch = "wasm32"), not(unix)))]
279fn check_permissions(_path: &Path) {}
280
281// ─── YAML helpers ────────────────────────────────────────────────────────────
282
283#[cfg(not(target_arch = "wasm32"))]
284fn load_yaml_mapping(path: &Path) -> Result<serde_yaml::Mapping> {
285    let content = std::fs::read_to_string(path)
286        .map_err(|e| Error::Config(format!("failed to read {}: {e}", path.display())))?;
287    let val: serde_yaml::Value = serde_yaml::from_str(&content)
288        .map_err(|e| Error::Config(format!("invalid YAML in {}: {e}", path.display())))?;
289    if let serde_yaml::Value::Mapping(m) = val {
290        Ok(m)
291    } else {
292        Err(Error::Config(format!(
293            "config file {} must be a YAML mapping",
294            path.display()
295        )))
296    }
297}
298
299#[cfg(not(target_arch = "wasm32"))]
300fn yaml_get<'a>(m: &'a serde_yaml::Mapping, key: &str) -> Option<&'a serde_yaml::Value> {
301    m.get(key)
302}
303
304#[cfg(not(target_arch = "wasm32"))]
305fn yaml_str(m: &serde_yaml::Mapping, key: &str) -> Option<String> {
306    yaml_get(m, key).and_then(|v| v.as_str()).map(String::from)
307}
308
309#[cfg(not(target_arch = "wasm32"))]
310fn yaml_path(m: &serde_yaml::Mapping, key: &str) -> Option<PathBuf> {
311    yaml_get(m, key).and_then(|v| v.as_str()).map(PathBuf::from)
312}
313
314#[cfg(not(target_arch = "wasm32"))]
315fn yaml_u64(m: &serde_yaml::Mapping, key: &str) -> Option<u64> {
316    yaml_get(m, key).and_then(|v| match v {
317        serde_yaml::Value::Number(n) => n.as_u64(),
318        serde_yaml::Value::String(s) => s.parse::<u64>().ok(),
319        _ => None,
320    })
321}
322
323#[cfg(not(target_arch = "wasm32"))]
324fn yaml_bool(m: &serde_yaml::Mapping, key: &str) -> Option<bool> {
325    yaml_get(m, key).and_then(|v| match v {
326        serde_yaml::Value::Bool(b) => Some(*b),
327        serde_yaml::Value::String(s) => s.parse::<bool>().ok(),
328        _ => None,
329    })
330}
331
332// ─── Config impl ─────────────────────────────────────────────────────────────
333
334impl Config {
335    /// Construct a config value suitable for wasm/local storage workflows.
336    ///
337    /// This constructor is storage-agnostic and does not touch the filesystem.
338    pub fn new_for_storage(slug: impl AsRef<str>) -> Self {
339        let slug = slug.as_ref().to_string();
340        Self {
341            slug: slug.clone(),
342            log_level: DEFAULT_LOG_LEVEL.to_string(),
343            log_level_stdout: DEFAULT_LOG_LEVEL_STDOUT.to_string(),
344            did_resolver_positive_ttl_secs: DEFAULT_DID_RESOLVER_POSITIVE_TTL_SECS,
345            did_resolver_negative_ttl_secs: DEFAULT_DID_RESOLVER_NEGATIVE_TTL_SECS,
346            log_file: None,
347            #[cfg(not(target_arch = "wasm32"))]
348            kubo_rpc_url: DEFAULT_KUBO_RPC_URL.to_string(),
349            #[cfg(not(target_arch = "wasm32"))]
350            kubo_key_alias: slug,
351            secret_bundle: None,
352            secret_bundle_passphrase: None,
353            config_path: None,
354            pin_remote: false,
355            pin_remote_service: None,
356            pin_remote_name: None,
357            pin_overwrite: true,
358            extra: serde_yaml::Mapping::new(),
359        }
360    }
361
362    /// Deserialize a config value from YAML text without filesystem I/O.
363    pub fn from_yaml_str(yaml_text: &str) -> Result<Self> {
364        let val: serde_yaml::Value = serde_yaml::from_str(yaml_text)
365            .map_err(|e| Error::Config(format!("failed to parse config YAML: {e}")))?;
366        let mut m = match val {
367            serde_yaml::Value::Mapping(m) => m,
368            _ => {
369                return Err(Error::Config(
370                    "config YAML must be a mapping at the top level".to_string(),
371                ));
372            }
373        };
374
375        let take_str = |map: &mut serde_yaml::Mapping, key: &str| {
376            map.remove(key)
377                .and_then(|v| v.as_str().map(ToOwned::to_owned))
378        };
379
380        let take_path = |map: &mut serde_yaml::Mapping, key: &str| {
381            map.remove(key).and_then(|v| v.as_str().map(PathBuf::from))
382        };
383
384        let take_u64 = |map: &mut serde_yaml::Mapping, key: &str| {
385            map.remove(key).and_then(|v| match v {
386                serde_yaml::Value::Number(n) => n.as_u64(),
387                serde_yaml::Value::String(s) => s.parse::<u64>().ok(),
388                _ => None,
389            })
390        };
391
392        let take_bool = |map: &mut serde_yaml::Mapping, key: &str| {
393            map.remove(key).and_then(|v| match v {
394                serde_yaml::Value::Bool(b) => Some(b),
395                serde_yaml::Value::String(s) => s.parse::<bool>().ok(),
396                _ => None,
397            })
398        };
399
400        let slug = take_str(&mut m, "slug").unwrap_or_else(|| "ma".to_string());
401        let log_level =
402            take_str(&mut m, "log_level").unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_string());
403        let log_level_stdout = take_str(&mut m, "log_level_stdout")
404            .unwrap_or_else(|| DEFAULT_LOG_LEVEL_STDOUT.to_string());
405        let did_resolver_positive_ttl_secs = take_u64(&mut m, "did_resolver_positive_ttl_secs")
406            .unwrap_or(DEFAULT_DID_RESOLVER_POSITIVE_TTL_SECS);
407        let did_resolver_negative_ttl_secs = take_u64(&mut m, "did_resolver_negative_ttl_secs")
408            .unwrap_or(DEFAULT_DID_RESOLVER_NEGATIVE_TTL_SECS);
409        // `config_path` is runtime state and should never be restored from YAML.
410        let _ignored_config_path = take_path(&mut m, "config_path");
411        // Legacy key; consumed so it does not linger in `extra`.
412        let _ignored_old_pin_batch_size = take_u64(&mut m, "old_pin_batch_size");
413        #[cfg(not(target_arch = "wasm32"))]
414        let kubo_rpc_url =
415            take_str(&mut m, "kubo_rpc_url").unwrap_or_else(|| DEFAULT_KUBO_RPC_URL.to_string());
416        #[cfg(not(target_arch = "wasm32"))]
417        let kubo_key_alias = take_str(&mut m, "kubo_key_alias").unwrap_or_else(|| slug.clone());
418
419        Ok(Self {
420            slug,
421            log_level,
422            log_level_stdout,
423            did_resolver_positive_ttl_secs,
424            did_resolver_negative_ttl_secs,
425            log_file: take_path(&mut m, "log_file"),
426            #[cfg(not(target_arch = "wasm32"))]
427            kubo_rpc_url,
428            #[cfg(not(target_arch = "wasm32"))]
429            kubo_key_alias,
430            secret_bundle: take_path(&mut m, "secret_bundle"),
431            secret_bundle_passphrase: take_str(&mut m, "secret_bundle_passphrase"),
432            config_path: None,
433            pin_remote: take_bool(&mut m, "pin_remote").unwrap_or(false),
434            pin_remote_service: take_str(&mut m, "pin_remote_service"),
435            pin_remote_name: take_str(&mut m, "pin_remote_name"),
436            pin_overwrite: take_bool(&mut m, "pin_overwrite").unwrap_or(true),
437            extra: m,
438        })
439    }
440
441    /// Serialize config to YAML text without filesystem I/O.
442    pub fn to_yaml_string(&self) -> Result<String> {
443        let mut m = self.extra.clone();
444
445        let mut set = |k: &str, v: serde_yaml::Value| {
446            m.insert(k, v);
447        };
448
449        set("slug", serde_yaml::Value::String(self.slug.clone()));
450        set(
451            "log_level",
452            serde_yaml::Value::String(self.log_level.clone()),
453        );
454        set(
455            "log_level_stdout",
456            serde_yaml::Value::String(self.log_level_stdout.clone()),
457        );
458        set(
459            "did_resolver_positive_ttl_secs",
460            serde_yaml::Value::Number(serde_yaml::Number::from(
461                self.did_resolver_positive_ttl_secs,
462            )),
463        );
464        set(
465            "did_resolver_negative_ttl_secs",
466            serde_yaml::Value::Number(serde_yaml::Number::from(
467                self.did_resolver_negative_ttl_secs,
468            )),
469        );
470        #[cfg(not(target_arch = "wasm32"))]
471        set(
472            "kubo_rpc_url",
473            serde_yaml::Value::String(self.kubo_rpc_url.clone()),
474        );
475        #[cfg(not(target_arch = "wasm32"))]
476        set(
477            "kubo_key_alias",
478            serde_yaml::Value::String(self.kubo_key_alias.clone()),
479        );
480
481        if let Some(ref p) = self.log_file {
482            set(
483                "log_file",
484                serde_yaml::Value::String(p.to_string_lossy().into_owned()),
485            );
486        }
487        if let Some(ref p) = self.secret_bundle {
488            set(
489                "secret_bundle",
490                serde_yaml::Value::String(p.to_string_lossy().into_owned()),
491            );
492        }
493        if let Some(ref pw) = self.secret_bundle_passphrase {
494            set(
495                "secret_bundle_passphrase",
496                serde_yaml::Value::String(pw.clone()),
497            );
498        }
499        set("pin_remote", serde_yaml::Value::Bool(self.pin_remote));
500        if let Some(ref service) = self.pin_remote_service {
501            set(
502                "pin_remote_service",
503                serde_yaml::Value::String(service.clone()),
504            );
505        }
506        if let Some(ref name) = self.pin_remote_name {
507            set("pin_remote_name", serde_yaml::Value::String(name.clone()));
508        }
509        set("pin_overwrite", serde_yaml::Value::Bool(self.pin_overwrite));
510
511        serde_yaml::to_string(&serde_yaml::Value::Mapping(m))
512            .map_err(|e| Error::Config(format!("failed to serialize config: {e}")))
513    }
514
515    /// Serialize config to YAML text while excluding secret passphrase fields.
516    ///
517    /// Useful for browser storage where passphrases should be provided by
518    /// runtime user input instead of persisted state.
519    pub fn to_yaml_string_without_passphrase(&self) -> Result<String> {
520        let mut copy = self.clone();
521        copy.secret_bundle_passphrase = None;
522        copy.to_yaml_string()
523    }
524
525    #[cfg(not(target_arch = "wasm32"))]
526    /// Build a `Config` by merging CLI arguments, environment variables, a
527    /// YAML config file, and built-in defaults.
528    ///
529    /// # Required compile-time constant
530    ///
531    /// Callers **MUST** pass a compile-time constant `MA_DEFAULT_SLUG: &'static str`.
532    /// This determines BOTH the default slug for file naming AND the fixed
533    /// env-var prefix. Only file naming may be overridden via `--slug`.
534    ///
535    /// ```
536    /// # #[cfg(all(feature = "config", not(target_arch = "wasm32")))]
537    /// # {
538    /// use ma_core::config::{Config, MaArgs};
539    /// let args = MaArgs::default();
540    /// let config = Config::from_args(&args, "doctest")?;
541    /// assert_eq!(config.slug, "doctest");
542    /// # }
543    /// # Ok::<(), ma_core::Error>(())
544    /// ```
545    ///
546    /// # Priority
547    ///
548    /// For each field other than config-file selection, the resolution order is:
549    /// 1. Explicit CLI argument
550    /// 2. `MA_FIELD` environment variable
551    /// 3. Value from the YAML config file
552    /// 4. Built-in default
553    #[allow(clippy::too_many_lines)]
554    pub fn from_args(args: &MaArgs, default_slug: &'static str) -> Result<Self> {
555        // Select the config path before loading YAML. A slug within the loaded
556        // file may set the effective runtime slug, but cannot redirect this read.
557        let config_slug = args
558            .slug
559            .clone()
560            .unwrap_or_else(|| default_slug.to_string());
561
562        // Config file path: explicit → slug-based XDG default.
563        let config_path = if let Some(ref p) = args.config {
564            p.clone()
565        } else {
566            default_config_path(&config_slug)?
567        };
568
569        // Load YAML if the file exists.
570        let yaml = if config_path.exists() {
571            check_permissions(&config_path);
572            Some(load_yaml_mapping(&config_path)?)
573        } else {
574            None
575        };
576
577        let slug = args
578            .slug
579            .clone()
580            .or_else(|| yaml.as_ref().and_then(|m| yaml_str(m, "slug")))
581            .unwrap_or_else(|| default_slug.to_string());
582
583        // Helper: resolve a string field through the priority chain.
584        // NOTE: closures borrow `yaml` and `prefix` immutably; NLL ensures
585        // the borrows end before we move `yaml` below.
586        let resolve_str = |cli: Option<String>, env_key: &str, default: &str| -> String {
587            cli.or_else(|| std::env::var(format!("MA_{env_key}")).ok())
588                .or_else(|| {
589                    yaml.as_ref()
590                        .and_then(|m| yaml_str(m, &env_key.to_lowercase()))
591                })
592                .unwrap_or_else(|| default.to_string())
593        };
594
595        let resolve_opt_str = |cli: Option<String>, env_key: &str| -> Option<String> {
596            cli.or_else(|| std::env::var(format!("MA_{env_key}")).ok())
597                .or_else(|| {
598                    yaml.as_ref()
599                        .and_then(|m| yaml_str(m, &env_key.to_lowercase()))
600                })
601        };
602
603        let resolve_opt_path = |cli: Option<PathBuf>, env_key: &str| -> Option<PathBuf> {
604            cli.or_else(|| {
605                std::env::var(format!("MA_{env_key}"))
606                    .ok()
607                    .map(PathBuf::from)
608            })
609            .or_else(|| {
610                yaml.as_ref()
611                    .and_then(|m| yaml_path(m, &env_key.to_lowercase()))
612            })
613        };
614
615        let resolve_u64 = |cli: Option<u64>, env_key: &str, default: u64| -> u64 {
616            cli.or_else(|| {
617                std::env::var(format!("MA_{env_key}"))
618                    .ok()
619                    .and_then(|v| v.parse::<u64>().ok())
620            })
621            .or_else(|| {
622                yaml.as_ref()
623                    .and_then(|m| yaml_u64(m, &env_key.to_lowercase()))
624            })
625            .unwrap_or(default)
626        };
627
628        let resolve_bool = |cli: Option<bool>, env_key: &str, default: bool| -> bool {
629            cli.or_else(|| {
630                std::env::var(format!("MA_{env_key}"))
631                    .ok()
632                    .and_then(|v| v.parse::<bool>().ok())
633            })
634            .or_else(|| {
635                yaml.as_ref()
636                    .and_then(|m| yaml_bool(m, &env_key.to_lowercase()))
637            })
638            .unwrap_or(default)
639        };
640
641        let log_level = resolve_str(args.log_level.clone(), "LOG_LEVEL", DEFAULT_LOG_LEVEL);
642        let log_level_stdout = resolve_str(
643            args.log_level_stdout.clone(),
644            "LOG_LEVEL_STDOUT",
645            DEFAULT_LOG_LEVEL_STDOUT,
646        );
647        let log_file = resolve_opt_path(args.log_file.clone(), "LOG_FILE");
648        let did_resolver_positive_ttl_secs = resolve_u64(
649            args.did_resolver_positive_ttl_secs,
650            "DID_RESOLVER_POSITIVE_TTL_SECS",
651            DEFAULT_DID_RESOLVER_POSITIVE_TTL_SECS,
652        );
653        let did_resolver_negative_ttl_secs = resolve_u64(
654            args.did_resolver_negative_ttl_secs,
655            "DID_RESOLVER_NEGATIVE_TTL_SECS",
656            DEFAULT_DID_RESOLVER_NEGATIVE_TTL_SECS,
657        );
658        let kubo_rpc_url = resolve_str(
659            args.kubo_rpc_url.clone(),
660            "KUBO_RPC_URL",
661            DEFAULT_KUBO_RPC_URL,
662        );
663        let kubo_key_alias =
664            resolve_str(args.kubo_key_alias.clone(), "KUBO_KEY_ALIAS", &slug.clone());
665        let secret_bundle = resolve_opt_path(args.secret_bundle.clone(), "SECRET_BUNDLE");
666        let secret_bundle_passphrase = resolve_opt_str(
667            args.secret_bundle_passphrase.clone(),
668            "SECRET_BUNDLE_PASSPHRASE",
669        );
670        let pin_remote = resolve_bool(args.pin_remote, "PIN_REMOTE", false);
671        let pin_remote_service =
672            resolve_opt_str(args.pin_remote_service.clone(), "PIN_REMOTE_SERVICE");
673        let pin_remote_name = resolve_opt_str(args.pin_remote_name.clone(), "PIN_REMOTE_NAME");
674        let pin_overwrite = resolve_bool(args.pin_overwrite, "PIN_OVERWRITE", true);
675
676        // Extra: all YAML keys that are not part of the core schema.
677        let known: &[&str] = &[
678            "slug",
679            "log_level",
680            "log_level_stdout",
681            "log_file",
682            "did_resolver_positive_ttl_secs",
683            "did_resolver_negative_ttl_secs",
684            "kubo_rpc_url",
685            "kubo_key_alias",
686            "secret_bundle",
687            "secret_bundle_passphrase",
688            "pin_remote",
689            "pin_remote_service",
690            "pin_remote_name",
691            "pin_overwrite",
692            // Legacy key; ignored and never persisted.
693            "old_pin_batch_size",
694            // Legacy key; ignored and never persisted.
695            "config_path",
696        ];
697        let extra = yaml
698            .map(|mut m| {
699                for k in known {
700                    m.remove(k);
701                }
702                m
703            })
704            .unwrap_or_default();
705
706        Ok(Config {
707            slug,
708            log_level,
709            log_level_stdout,
710            did_resolver_positive_ttl_secs,
711            did_resolver_negative_ttl_secs,
712            log_file,
713            #[cfg(not(target_arch = "wasm32"))]
714            kubo_rpc_url,
715            #[cfg(not(target_arch = "wasm32"))]
716            kubo_key_alias,
717            secret_bundle,
718            secret_bundle_passphrase,
719            config_path: Some(config_path),
720            pin_remote,
721            pin_remote_service,
722            pin_remote_name,
723            pin_overwrite,
724            extra,
725        })
726    }
727
728    /// Return validated remote pinning settings using `default_name` when the
729    /// config does not specify `pin_remote_name`.
730    pub fn remote_pin_config_with_default_name(
731        &self,
732        default_name: impl Into<String>,
733    ) -> Result<Option<RemotePinConfig>> {
734        if !self.pin_remote {
735            return Ok(None);
736        }
737        let service = self
738            .pin_remote_service
739            .as_deref()
740            .map(str::trim)
741            .filter(|value| !value.is_empty())
742            .ok_or_else(|| Error::Config("pin_remote requires pin_remote_service".to_string()))?;
743        let default_name = default_name.into();
744        let name = self
745            .pin_remote_name
746            .as_deref()
747            .map(str::trim)
748            .filter(|value| !value.is_empty())
749            .unwrap_or(default_name.as_str());
750        Ok(Some(RemotePinConfig {
751            service: service.to_string(),
752            name: name.to_string(),
753            overwrite: self.pin_overwrite,
754        }))
755    }
756
757    /// The effective log file path: `self.log_file` if set, otherwise the
758    /// XDG default `XDG_DATA_HOME/ma/<slug>.log`.
759    #[cfg(not(target_arch = "wasm32"))]
760    pub fn effective_log_file(&self) -> Result<PathBuf> {
761        if let Some(ref p) = self.log_file {
762            Ok(p.clone())
763        } else {
764            default_log_file_path(&self.slug)
765        }
766    }
767
768    /// The effective secret bundle path: `self.secret_bundle` if set,
769    /// otherwise the XDG default `XDG_CONFIG_HOME/ma/<slug>.bin`.
770    #[cfg(not(target_arch = "wasm32"))]
771    pub fn effective_secret_bundle(&self) -> Result<PathBuf> {
772        if let Some(ref p) = self.secret_bundle {
773            Ok(p.clone())
774        } else {
775            default_secret_bundle_path(&self.slug)
776        }
777    }
778
779    /// Save this config to [`Self::config_path`] as YAML with 0600
780    /// permissions. Returns an error if `config_path` is not set.
781    ///
782    /// Known fields are serialized explicitly; extra fields are merged in
783    /// afterwards so user-defined keys are preserved.
784    #[cfg(not(target_arch = "wasm32"))]
785    pub fn save(&self) -> Result<()> {
786        let path = self
787            .config_path
788            .as_ref()
789            .ok_or_else(|| Error::Config("cannot save config: no config_path set".to_string()))?;
790
791        let yaml_text = self.to_yaml_string()?;
792
793        write_secure(path, yaml_text.as_bytes())
794    }
795
796    /// Generate a complete headless config:
797    ///
798    /// 1. Generate a fresh [`SecretBundle`] with four random 32-byte keys.
799    /// 2. Encrypt the bundle (using `args.secret_bundle_passphrase` or a
800    ///    freshly generated random passphrase).
801    /// 3. Write the encrypted bundle to `XDG_CONFIG_HOME/ma/<slug>.bin`
802    ///    (or the path from `--secret-bundle`) with mode 0600.
803    /// 4. Write the YAML config to `XDG_CONFIG_HOME/ma/<slug>.yaml`
804    ///    (or the path from `--config`) with the passphrase in cleartext and
805    ///    mode 0600.
806    /// 5. Print the paths of both files to stdout.
807    ///
808    /// Returns an error if either file already exists.
809    #[cfg(not(target_arch = "wasm32"))]
810    pub fn gen_headless(args: &MaArgs, default_slug: &'static str) -> Result<()> {
811        let slug = args.slug.as_deref().unwrap_or(default_slug).to_string();
812
813        let config_path = if let Some(ref p) = args.config {
814            p.clone()
815        } else {
816            default_config_path(&slug)?
817        };
818        let bundle_path = if let Some(ref p) = args.secret_bundle {
819            p.clone()
820        } else {
821            default_secret_bundle_path(&slug)?
822        };
823
824        if config_path.exists() {
825            return Err(Error::Config(format!(
826                "config file already exists: {} (remove it first or use --config)",
827                config_path.display()
828            )));
829        }
830        if bundle_path.exists() {
831            return Err(Error::Config(format!(
832                "secret bundle already exists: {} (remove it first or use --secret-bundle)",
833                bundle_path.display()
834            )));
835        }
836
837        // Generate or use provided passphrase.
838        let passphrase = if let Some(ref p) = args.secret_bundle_passphrase {
839            p.clone()
840        } else {
841            SecretBundle::generate_passphrase()
842        };
843
844        // Generate and save the bundle.
845        let bundle = SecretBundle::generate();
846        bundle.save(&bundle_path, &passphrase)?;
847
848        // Build and save the config.
849        let config = Config {
850            slug: slug.clone(),
851            log_level: DEFAULT_LOG_LEVEL.to_string(),
852            log_level_stdout: DEFAULT_LOG_LEVEL_STDOUT.to_string(),
853            did_resolver_positive_ttl_secs: DEFAULT_DID_RESOLVER_POSITIVE_TTL_SECS,
854            did_resolver_negative_ttl_secs: DEFAULT_DID_RESOLVER_NEGATIVE_TTL_SECS,
855            log_file: None,
856            #[cfg(not(target_arch = "wasm32"))]
857            kubo_rpc_url: DEFAULT_KUBO_RPC_URL.to_string(),
858            #[cfg(not(target_arch = "wasm32"))]
859            kubo_key_alias: slug.clone(),
860            secret_bundle: Some(bundle_path.clone()),
861            secret_bundle_passphrase: Some(passphrase),
862            config_path: Some(config_path.clone()),
863            pin_remote: false,
864            pin_remote_service: None,
865            pin_remote_name: None,
866            pin_overwrite: true,
867            extra: serde_yaml::Mapping::new(),
868        };
869        config.save()?;
870
871        println!("Config:        {}", config_path.display());
872        println!("Secret bundle: {}", bundle_path.display());
873
874        Ok(())
875    }
876}
877
878#[cfg(test)]
879mod tests {
880    use super::*;
881
882    #[test]
883    fn remote_pin_config_uses_caller_default_name() {
884        let config = Config::from_yaml_str(
885            r"
886pin_remote: true
887pin_remote_service: pinata
888",
889        )
890        .unwrap();
891
892        let remote = config
893            .remote_pin_config_with_default_name("ma-runtime-ma-root")
894            .unwrap()
895            .unwrap();
896        assert_eq!(remote.service, "pinata");
897        assert_eq!(remote.name, "ma-runtime-ma-root");
898        assert!(remote.overwrite);
899    }
900
901    #[test]
902    fn remote_pin_config_requires_service_when_enabled() {
903        let config = Config::from_yaml_str("pin_remote: true\n").unwrap();
904
905        let err = config
906            .remote_pin_config_with_default_name("ma-runtime-ma-root")
907            .unwrap_err();
908        assert!(err.to_string().contains("pin_remote_service"));
909    }
910
911    #[test]
912    fn yaml_round_trip_preserves_slug() {
913        let config = Config::from_yaml_str("slug: testing\n").unwrap();
914
915        assert_eq!(config.slug, "testing");
916        assert!(config.to_yaml_string().unwrap().contains("slug: testing"));
917    }
918
919    #[cfg(not(target_arch = "wasm32"))]
920    #[test]
921    fn cli_pin_remote_overrides_yaml_default() {
922        let config = Config::from_args(
923            &MaArgs {
924                pin_remote: Some(true),
925                pin_remote_service: Some("pinata".to_string()),
926                pin_remote_name: Some("custom-root".to_string()),
927                ..MaArgs::default()
928            },
929            "test",
930        )
931        .unwrap();
932
933        assert!(config.pin_remote);
934        assert_eq!(config.pin_remote_service.as_deref(), Some("pinata"));
935        assert_eq!(config.pin_remote_name.as_deref(), Some("custom-root"));
936    }
937
938    #[cfg(not(target_arch = "wasm32"))]
939    #[test]
940    fn explicit_config_uses_yaml_slug_without_relocating_config_path() {
941        let path = std::env::temp_dir().join(format!(
942            "ma-core-config-explicit-slug-{}.yaml",
943            std::process::id()
944        ));
945        std::fs::write(&path, "slug: testing\n").unwrap();
946
947        let config = Config::from_args(
948            &MaArgs {
949                config: Some(path.clone()),
950                ..MaArgs::default()
951            },
952            "ma",
953        )
954        .unwrap();
955
956        assert_eq!(config.slug, "testing");
957        assert_eq!(config.config_path.as_deref(), Some(path.as_path()));
958        let _ = std::fs::remove_file(path);
959    }
960
961    #[cfg(not(target_arch = "wasm32"))]
962    #[test]
963    fn cli_slug_overrides_yaml_slug() {
964        let path = std::env::temp_dir().join(format!(
965            "ma-core-config-cli-slug-{}.yaml",
966            std::process::id()
967        ));
968        std::fs::write(&path, "slug: yaml-name\n").unwrap();
969
970        let config = Config::from_args(
971            &MaArgs {
972                config: Some(path.clone()),
973                slug: Some("cli-name".to_string()),
974                ..MaArgs::default()
975            },
976            "ma",
977        )
978        .unwrap();
979
980        assert_eq!(config.slug, "cli-name");
981        assert_eq!(config.config_path.as_deref(), Some(path.as_path()));
982        let _ = std::fs::remove_file(path);
983    }
984}