Skip to main content

passless_core/
config.rs

1//! Application configuration using clap-serde-derive
2//!
3//! This module provides a unified configuration approach where settings can come from:
4//! 1. CLI arguments (highest priority)
5//! 2. Configuration file (medium priority)
6//! 3. Default values (lowest priority)
7
8use std::fs::{self, File};
9use std::io::BufReader;
10use std::path::{Path, PathBuf};
11
12use clap::{ArgAction, Parser, Subcommand, ValueEnum};
13use clap_serde_derive::ClapSerde;
14use libc::{PR_SET_DUMPABLE, prctl};
15use libc::{mlock, munlock};
16use log::debug;
17use nix::sys::resource::{Resource, setrlimit};
18use passless_config_doc::ConfigDoc;
19use serde::{Deserialize, Serialize};
20
21#[cfg(feature = "agent")]
22use crate::agent::AgentConfig;
23
24use crate::error::Error;
25
26/// Compute default local storage path
27pub fn local_path() -> String {
28    dirs::data_dir()
29        .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
30        .join("passless/local")
31        .to_string_lossy()
32        .into_owned()
33}
34
35/// Local backend configuration
36#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
37#[group(id = "local-backend-config")]
38pub struct LocalBackendConfig {
39    /// Path to local storage directory
40    #[arg(
41        long = "local-path",
42        env = "PASSLESS_LOCAL_PATH",
43        id = "local-path",
44        value_name = "PATH"
45    )]
46    #[serde(default)]
47    #[default(local_path())]
48    pub path: String,
49}
50
51/// Compute default password-store path
52pub fn pass_store_path() -> String {
53    dirs::home_dir()
54        .expect("Could not determine home directory: $HOME")
55        .join(".password-store")
56        .to_string_lossy()
57        .into_owned()
58}
59/// Pass (password-store) backend configuration
60#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
61#[group(id = "pass-backend-config")]
62pub struct PassBackendConfig {
63    /// Path to password store directory
64    #[arg(
65        long = "pass-store-path",
66        env = "PASSLESS_PASS_STORE_PATH",
67        id = "pass-store-path",
68        value_name = "PATH"
69    )]
70    #[serde(default)]
71    #[default(pass_store_path())]
72    pub store_path: String,
73
74    /// Relative path within password store for FIDO2 entries
75    #[arg(
76        long = "pass-path",
77        env = "PASSLESS_PASS_PATH",
78        id = "pass-path",
79        value_name = "PATH"
80    )]
81    #[serde(default)]
82    #[default("fido2".to_string())]
83    pub path: String,
84
85    /// GPG backend: "gpgme" or "gnupg-bin"
86    #[arg(
87        long = "pass-gpg-backend",
88        env = "PASSLESS_PASS_GPG_BACKEND",
89        value_name = "BACKEND"
90    )]
91    #[serde(default)]
92    #[default("gnupg-bin".to_string())]
93    pub gpg_backend: String,
94
95    /// Automatically synchronize password-store Git around Passless operations
96    #[arg(
97        long = "pass-git-sync",
98        env = "PASSLESS_PASS_GIT_SYNC",
99        action = ArgAction::Set,
100        require_equals = true,
101        num_args = 0..=1,
102        default_missing_value = "true"
103    )]
104    #[serde(default)]
105    #[default(true)]
106    pub git_sync: bool,
107
108    /// Automatically push password-store Git commits to the remote (default: true).
109    /// When disabled, Git sync still pulls and commits changes locally.
110    #[arg(
111        long = "pass-git-auto-push",
112        env = "PASSLESS_PASS_GIT_AUTO_PUSH",
113        action = ArgAction::Set,
114        require_equals = true,
115        num_args = 0..=1,
116        default_missing_value = "true"
117    )]
118    #[serde(default)]
119    #[default(true)]
120    pub git_auto_push: bool,
121}
122
123/// Compute default TPM storage path
124pub fn tpm_path() -> String {
125    dirs::data_dir()
126        .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
127        .join("passless/tpm")
128        .to_string_lossy()
129        .into_owned()
130}
131
132/// TPM backend configuration
133#[cfg(feature = "tpm")]
134#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
135#[group(id = "tpm-backend-config")]
136pub struct TpmBackendConfig {
137    /// Path to TPM storage directory
138    #[arg(
139        long = "tpm-path",
140        env = "PASSLESS_TPM_PATH",
141        id = "tpm-path",
142        value_name = "PATH"
143    )]
144    #[serde(default)]
145    #[default(tpm_path())]
146    pub path: String,
147
148    /// TPM TCTI (TPM Command Transmission Interface) configuration
149    #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI", value_name = "TCTI")]
150    #[serde(default)]
151    #[default("device:/dev/tpmrm0".to_string())]
152    pub tcti: String,
153
154    /// Use portable TPM backend with TPM-resident credential keys
155    #[arg(long = "tpm-portable", env = "PASSLESS_TPM_PORTABLE")]
156    #[serde(default)]
157    #[default(false)]
158    pub portable: bool,
159}
160
161/// Security configuration
162#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
163#[group(id = "security")]
164pub struct SecurityConfig {
165    /// Check if mlock is available to prevent credentials from being swapped to disk
166    #[arg(long = "check-mlock", env = "PASSLESS_CHECK_MLOCK")]
167    #[serde(default)]
168    #[default(true)]
169    pub check_mlock: bool,
170
171    /// Disable core dumps to prevent credential leakage
172    #[arg(long = "disable-core-dumps", env = "PASSLESS_DISABLE_CORE_DUMPS")]
173    #[serde(default)]
174    #[default(true)]
175    pub disable_core_dumps: bool,
176
177    /// Enable constant signature counter to help RPs detect cloned authenticators
178    #[arg(
179        long = "constant-signature-counter",
180        env = "PASSLESS_CONSTANT_SIGNATURE_COUNTER",
181        action = ArgAction::Set,
182        require_equals = true,
183        num_args = 0..=1,
184        default_missing_value = "true"
185    )]
186    #[serde(default)]
187    pub constant_signature_counter: bool,
188
189    /// Enable Passless encrypted credential backup/restore vendor commands.
190    ///
191    /// Also sets the WebAuthn backup-eligibility (BE) flag assigned to newly
192    /// registered credentials: `false` (default) marks them single-device
193    /// (`BE=0`), `true` marks them backup-eligible (`BE=1`). Existing
194    /// credentials are not migrated; they keep the state they were created with.
195    ///
196    /// Disabled by default because exporting a software credential changes its
197    /// security model. TPM and other non-exportable key providers remain
198    /// unsupported. Strict relying parties (e.g. Kanidm) reject a credential
199    /// whose BE flag changes after registration, so keep this setting stable.
200    /// See docs/CREDENTIAL_BACKUP.md.
201    #[arg(
202        long = "enable-credential-backup",
203        env = "PASSLESS_ENABLE_CREDENTIAL_BACKUP",
204        action = ArgAction::Set,
205        require_equals = true,
206        num_args = 0..=1,
207        default_missing_value = "true"
208    )]
209    #[serde(default)]
210    pub enable_credential_backup: bool,
211
212    /// Always require user verification for all operations
213    /// - When PIN is set + pin.enforcement="required": requires PIN
214    /// - When PIN is set + pin.enforcement="optional": depends on context
215    /// - When PIN is set + pin.enforcement="never": uses notification fallback
216    /// - When PIN not set: uses notification
217    #[arg(
218        long = "always-uv",
219        env = "PASSLESS_ALWAYS_UV",
220        action = ArgAction::Set,
221        require_equals = true,
222        num_args = 0..=1,
223        default_value = "true",
224        default_missing_value = "true"
225    )]
226    #[serde(default)]
227    #[default(true)]
228    pub always_uv: bool,
229
230    /// Show user verification notification during registration
231    #[arg(
232        long = "user-verification-registration",
233        env = "PASSLESS_USER_VERIFICATION_REGISTRATION"
234    )]
235    #[serde(default)]
236    #[default(true)]
237    pub user_verification_registration: bool,
238
239    /// Show user verification notification during authentication
240    #[arg(
241        long = "user-verification-authentication",
242        env = "PASSLESS_USER_VERIFICATION_AUTHENTICATION"
243    )]
244    #[serde(default)]
245    #[default(true)]
246    pub user_verification_authentication: bool,
247
248    /// Notification timeout in seconds (0 = no timeout)
249    #[arg(
250        long = "notification-timeout",
251        env = "PASSLESS_NOTIFICATION_TIMEOUT",
252        value_name = "SECONDS"
253    )]
254    #[serde(default)]
255    #[default(30)]
256    pub notification_timeout: u32,
257}
258
259/// PIN enforcement policy
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
261#[serde(rename_all = "lowercase")]
262pub enum PinEnforcement {
263    /// Never require PIN, always use notification fallback (backward compatible)
264    Never,
265    /// Use PIN only when always_uv=true or client requests UV
266    #[default]
267    Optional,
268    /// Always require PIN when set (most secure)
269    Required,
270}
271
272impl std::str::FromStr for PinEnforcement {
273    type Err = String;
274
275    fn from_str(s: &str) -> Result<Self, Self::Err> {
276        match s.to_lowercase().as_str() {
277            "never" => Ok(PinEnforcement::Never),
278            "optional" => Ok(PinEnforcement::Optional),
279            "required" => Ok(PinEnforcement::Required),
280            _ => Err(format!(
281                "Invalid PIN enforcement '{}'. Must be: never, optional, or required",
282                s
283            )),
284        }
285    }
286}
287
288impl std::fmt::Display for PinEnforcement {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290        match self {
291            PinEnforcement::Never => write!(f, "never"),
292            PinEnforcement::Optional => write!(f, "optional"),
293            PinEnforcement::Required => write!(f, "required"),
294        }
295    }
296}
297
298/// PIN configuration
299#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
300#[group(id = "pin")]
301pub struct PinConfig {
302    /// PIN enforcement policy when PIN is set:
303    /// - "never": Always use notification fallback (backward compatible, convenience)
304    /// - "optional": Use PIN only when always_uv=true or client requests UV
305    /// - "required": Always require PIN when set (most secure)
306    #[arg(
307        long = "pin-enforcement",
308        env = "PASSLESS_PIN_ENFORCEMENT",
309        value_name = "POLICY"
310    )]
311    #[serde(default)]
312    #[default(PinEnforcement::Optional)]
313    pub enforcement: PinEnforcement,
314
315    /// Minimum PIN length in characters (CTAP spec: 4-63)
316    #[arg(
317        long = "pin-min-length",
318        env = "PASSLESS_PIN_MIN_LENGTH",
319        value_name = "LENGTH"
320    )]
321    #[serde(default)]
322    #[default(4)]
323    pub min_length: u8,
324
325    /// Maximum PIN retry attempts before lockout (CTAP spec: 8)
326    #[arg(
327        long = "pin-max-retries",
328        env = "PASSLESS_PIN_MAX_RETRIES",
329        value_name = "RETRIES"
330    )]
331    #[serde(default)]
332    #[default(8)]
333    pub max_retries: u8,
334
335    /// Maximum user verification retry attempts before UV is blocked (default: 8)
336    ///
337    /// This controls how many consecutive UV failures are allowed before UV is blocked.
338    /// Use `passless client pin uv-reset` to restore the retry counter after authentication.
339    /// Higher values improve usability but may reduce security against brute-force attacks.
340    #[arg(
341        long = "pin-max-uv-retries",
342        env = "PASSLESS_PIN_MAX_UV_RETRIES",
343        value_name = "RETRIES"
344    )]
345    #[serde(default)]
346    #[default(8)]
347    pub max_uv_retries: u8,
348
349    /// Auto-lock timeout in seconds after max failed attempts (0 = disabled)
350    /// After lockout, authenticator must be reset to use PIN again
351    #[arg(
352        long = "pin-auto-lock-timeout",
353        env = "PASSLESS_PIN_AUTO_LOCK_TIMEOUT",
354        value_name = "SECONDS"
355    )]
356    #[serde(default)]
357    #[default(0)]
358    pub auto_lock_timeout: u32,
359}
360
361impl PinConfig {
362    /// Validate PIN configuration values
363    pub fn validate(&self) -> crate::error::Result<()> {
364        if self.min_length < 4 || self.min_length > 63 {
365            return Err(crate::error::Error::Config(format!(
366                "pin.min_length must be between 4 and 63, got {}",
367                self.min_length
368            )));
369        }
370        if self.max_retries == 0 {
371            return Err(crate::error::Error::Config(
372                "pin.max_retries must be greater than 0".to_string(),
373            ));
374        }
375        if self.max_uv_retries == 0 {
376            return Err(crate::error::Error::Config(
377                "pin.max_uv_retries must be greater than 0".to_string(),
378            ));
379        }
380        Ok(())
381    }
382}
383
384impl SecurityConfig {
385    /// Apply security hardening measures
386    pub fn apply_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
387        if self.disable_core_dumps {
388            self.disable_core_dumps_impl()?;
389        }
390        if self.check_mlock {
391            self.probe_mlock_capability()?;
392        }
393        Ok(())
394    }
395
396    /// Disable core dumps to prevent credential leakage
397    fn disable_core_dumps_impl(&self) -> Result<(), Box<dyn std::error::Error>> {
398        debug!("Disabling core dumps to prevent credential leakage");
399        setrlimit(Resource::RLIMIT_CORE, 0, 0)?;
400        let r = unsafe { prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) };
401        if r != 0 {
402            log::warn!("prctl(PR_SET_DUMPABLE) failed: {}", r);
403        }
404        Ok(())
405    }
406
407    /// Probe mlock capability by testing with a small allocation
408    fn probe_mlock_capability(&self) -> Result<(), Box<dyn std::error::Error>> {
409        debug!("Check mlock capability");
410
411        let test_size = 4096;
412        let test_buffer = vec![0u8; test_size];
413        let ptr = test_buffer.as_ptr() as *const libc::c_void;
414
415        let lock_result = unsafe { mlock(ptr, test_size) };
416
417        if lock_result == 0 {
418            unsafe { munlock(ptr, test_size) };
419            log::debug!("MLOCK is enabled - sensitive data will not be swapped to disk");
420        } else {
421            log::warn!(
422                "mlock capability probe failed - memory locking may not be available.\n\
423                 Hint: grant CAP_IPC_LOCK to the binary with: 'sudo setcap cap_ipc_lock=+ep $(which passless)'"
424            );
425        }
426        Ok(())
427    }
428}
429
430/// Main application configuration
431/// Note: Cannot derive Clone/Debug because it has #[clap_serde] fields
432#[derive(ClapSerde, Serialize, Deserialize, Debug, ConfigDoc)]
433pub struct AppConfig {
434    /// Storage backend type: pass, tpm (experimental), or local (for testing)
435    #[arg(short = 't', long = "backend-type", env = "PASSLESS_BACKEND_TYPE")]
436    #[serde(default)]
437    #[default("pass".to_string())]
438    pub backend_type: String,
439
440    /// Enable verbose logging
441    // workaround for allowing `-v` syntax instead of `-v=true`
442    #[arg(
443        short,
444        long,
445        env = "PASSLESS_VERBOSE",
446        action = ArgAction::Set,
447        require_equals = true,
448        num_args = 0..=1,
449        default_missing_value = "true"
450    )]
451    #[default(true)]
452    #[serde(default)]
453    pub verbose: bool,
454
455    /// Pass backend configuration
456    #[clap_serde]
457    #[serde(default)]
458    #[command(flatten)]
459    pub pass: PassBackendConfig,
460
461    /// TPM backend configuration
462    #[cfg(feature = "tpm")]
463    #[clap_serde]
464    #[serde(default)]
465    #[command(flatten)]
466    pub tpm: TpmBackendConfig,
467
468    /// Local backend configuration
469    #[clap_serde]
470    #[serde(default)]
471    #[command(flatten)]
472    pub local: LocalBackendConfig,
473
474    /// Security hardening configuration
475    #[clap_serde]
476    #[serde(default)]
477    #[command(flatten)]
478    pub security: SecurityConfig,
479
480    /// PIN configuration
481    #[clap_serde]
482    #[serde(default)]
483    #[command(flatten)]
484    pub pin: PinConfig,
485
486    /// Agent configuration (only available with the `agent` feature)
487    #[cfg(feature = "agent")]
488    #[arg(skip)]
489    pub agents: AgentConfig,
490}
491
492/// Backend-specific configuration
493#[derive(Debug, Clone)]
494pub enum BackendConfig {
495    Local {
496        path: String,
497    },
498    Pass {
499        store_path: String,
500        path: String,
501        gpg_backend: String,
502    },
503    #[cfg(feature = "tpm")]
504    Tpm {
505        path: String,
506        tcti: String,
507        portable: bool,
508    },
509}
510
511impl BackendConfig {
512    /// Canonicalize a path, resolving symlinks for existing parents.
513    ///
514    /// If the full path does not exist, canonicalize the longest existing
515    /// prefix and append the remaining components lexically.
516    pub fn canonicalize_path(path: &Path) -> PathBuf {
517        match fs::canonicalize(path) {
518            Ok(p) => p,
519            Err(_) => {
520                let mut current = path.to_path_buf();
521                let mut suffix = Vec::new();
522                loop {
523                    match fs::canonicalize(&current) {
524                        Ok(base) => {
525                            let mut result = base;
526                            for component in suffix.iter().rev() {
527                                result.push(component);
528                            }
529                            return result;
530                        }
531                        Err(_) => {
532                            if let Some(file_name) = current.file_name() {
533                                suffix.push(file_name.to_os_string());
534                                current = current
535                                    .parent()
536                                    .map(|p| p.to_path_buf())
537                                    .unwrap_or_default();
538                            } else {
539                                return path.to_path_buf();
540                            }
541                        }
542                    }
543                }
544            }
545        }
546    }
547
548    /// Return the canonical state path for this backend.
549    ///
550    /// This is used as the identity for the instance lock: two daemons with the
551    /// same canonical state path will contend for the same lock.
552    pub fn state_path(&self) -> PathBuf {
553        match self {
554            BackendConfig::Local { path } => Self::canonicalize_path(Path::new(path)),
555            BackendConfig::Pass {
556                store_path, path, ..
557            } => Self::canonicalize_path(&Path::new(store_path).join(path)),
558            #[cfg(feature = "tpm")]
559            BackendConfig::Tpm { path, .. } => Self::canonicalize_path(Path::new(path)),
560        }
561    }
562
563    /// Return a human-readable display string for the backend state path.
564    pub fn state_display(&self) -> String {
565        match self {
566            BackendConfig::Local { path } => path.clone(),
567            BackendConfig::Pass {
568                store_path, path, ..
569            } => {
570                format!("{}/{}", store_path, path)
571            }
572            #[cfg(feature = "tpm")]
573            BackendConfig::Tpm { path, .. } => path.clone(),
574        }
575    }
576
577    /// Validate backend configuration for security and correctness.
578    ///
579    /// This checks that paths are well-formed and don't escape their intended roots.
580    pub fn validate(&self) -> crate::error::Result<()> {
581        match self {
582            BackendConfig::Local { path } => {
583                let p = Path::new(path);
584                if !p.is_absolute() && !p.starts_with("~") {
585                    debug!("Local backend path is relative: {}, canonicalizing", path);
586                }
587                Ok(())
588            }
589            BackendConfig::Pass {
590                store_path, path, ..
591            } => {
592                let p = Path::new(path);
593                if p.is_absolute() {
594                    return Err(Error::Config(format!(
595                        "Pass backend 'path' must be relative, got absolute path: {}",
596                        path
597                    )));
598                }
599                if path.contains("..") {
600                    return Err(Error::Config(format!(
601                        "Pass backend 'path' must not contain '..': {}",
602                        path
603                    )));
604                }
605                // Verify the combined path doesn't escape the store
606                let combined = Path::new(store_path).join(path);
607                let canonical_store = Self::canonicalize_path(Path::new(store_path));
608                let canonical_combined = Self::canonicalize_path(&combined);
609                if !canonical_combined.starts_with(&canonical_store) {
610                    return Err(Error::Config(format!(
611                        "Pass backend 'path' escapes store_path: {} not beneath {}",
612                        canonical_combined.display(),
613                        canonical_store.display()
614                    )));
615                }
616                Ok(())
617            }
618            #[cfg(feature = "tpm")]
619            BackendConfig::Tpm { path, .. } => {
620                let p = Path::new(path);
621                if !p.is_absolute() && !p.starts_with("~") {
622                    debug!("TPM backend path is relative: {}, canonicalizing", path);
623                }
624                Ok(())
625            }
626        }
627    }
628}
629
630impl AppConfig {
631    /// The configuration file [`Self::load`] reads: `--config`/`PASSLESS_CONFIG`, else the default
632    /// `~/.config/passless/config.toml`, if it exists.
633    pub fn config_file_path(args: &Args) -> Option<PathBuf> {
634        let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));
635        args.config_path
636            .clone()
637            .or(default_config_path)
638            .filter(|p| p.exists())
639    }
640
641    /// Load configuration with precedence: CLI > config file > defaults
642    pub fn load(args: &mut Args) -> crate::error::Result<Self> {
643        let config_file_path = Self::config_file_path(args);
644
645        if let Some(path) = config_file_path.as_ref()
646            && let Ok(f) = File::open(path)
647        {
648            log::info!("Loading configuration from: {}", path.display());
649            let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
650
651            #[cfg(feature = "agent")]
652            let agent_config = AgentConfig::from_toml_str(&content, &path.display().to_string())?;
653
654            match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
655                Ok(file_config) => {
656                    #[allow(unused_mut)]
657                    let mut config = AppConfig::from(file_config).merge(&mut args.config);
658                    #[cfg(feature = "agent")]
659                    {
660                        config.agents = agent_config;
661                    }
662                    return Ok(config);
663                }
664                Err(e) => {
665                    return Err(Error::Config(format!(
666                        "failed to parse config file {}: {}",
667                        path.display(),
668                        e
669                    )));
670                }
671            }
672        }
673
674        #[allow(unused_mut)]
675        let mut config = AppConfig::from(&mut args.config);
676        #[cfg(feature = "agent")]
677        {
678            config.agents = AgentConfig::default();
679        }
680        Ok(config)
681    }
682
683    /// Get the backend configuration based on the backend_type
684    pub fn backend(&self) -> crate::error::Result<BackendConfig> {
685        match self.backend_type.as_str() {
686            "local" => Ok(BackendConfig::Local {
687                path: self.local.path.clone(),
688            }),
689            "pass" => Ok(BackendConfig::Pass {
690                store_path: self.pass.store_path.clone(),
691                path: self.pass.path.clone(),
692                gpg_backend: self.pass.gpg_backend.clone(),
693            }),
694            #[cfg(feature = "tpm")]
695            "tpm" => Ok(BackendConfig::Tpm {
696                path: self.tpm.path.clone(),
697                tcti: self.tpm.tcti.clone(),
698                portable: self.tpm.portable,
699            }),
700            _ => Err(crate::error::Error::Config(format!(
701                "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
702                self.backend_type
703            ))),
704        }
705    }
706
707    /// Apply security hardening measures
708    pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
709        self.security.apply_hardening()
710    }
711
712    /// Get security configuration
713    pub fn security_config(&self) -> SecurityConfig {
714        self.security.clone()
715    }
716
717    /// Get PIN configuration
718    pub fn pin_config(&self) -> PinConfig {
719        self.pin.clone()
720    }
721
722    /// Everything the daemon checks of the configuration before it starts serving: [`Self::validate`]
723    /// and the backend's own validation (`main.rs` runs the same steps one by one, with its own
724    /// log messages). Used by `passless config check` and `passless doctor`.
725    pub fn check_startup(&self) -> crate::error::Result<()> {
726        self.validate()?;
727        self.backend()?.validate()
728    }
729
730    /// Validate the configuration
731    pub fn validate(&self) -> crate::error::Result<()> {
732        self.pin.validate()?;
733        #[cfg(feature = "agent")]
734        {
735            let human_path = self.backend().ok().map(|b| b.state_path());
736            self.agents.validate(human_path.as_deref())?;
737        }
738        Ok(())
739    }
740}
741
742/// CLI arguments structure
743#[derive(Parser)]
744#[command(author, version, about)]
745pub struct Args {
746    /// Path to configuration file (TOML format)
747    #[arg(short, long, env = "PASSLESS_CONFIG")]
748    pub config_path: Option<PathBuf>,
749
750    /// Application configuration (can come from CLI or config file)
751    #[command(flatten)]
752    pub config: <AppConfig as ClapSerde>::Opt,
753
754    /// Subcommands
755    #[command(subcommand)]
756    pub command: Option<Commands>,
757}
758
759/// Output format for client commands
760#[derive(Debug, Clone, Copy, PartialEq, Eq)]
761pub enum OutputFormat {
762    /// Human-readable plain text output
763    Plain,
764    /// JSON output for programmatic consumption
765    Json,
766}
767
768impl std::str::FromStr for OutputFormat {
769    type Err = String;
770
771    fn from_str(s: &str) -> Result<Self, Self::Err> {
772        match s.to_lowercase().as_str() {
773            "plain" => Ok(OutputFormat::Plain),
774            "json" => Ok(OutputFormat::Json),
775            _ => Err(format!(
776                "Invalid output format '{}'. Must be 'plain' or 'json'",
777                s
778            )),
779        }
780    }
781}
782
783impl std::fmt::Display for OutputFormat {
784    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
785        match self {
786            OutputFormat::Plain => write!(f, "plain"),
787            OutputFormat::Json => write!(f, "json"),
788        }
789    }
790}
791
792/// Subcommands for passless
793#[derive(Subcommand, Debug, Clone)]
794pub enum Commands {
795    /// Configuration management commands
796    Config {
797        #[command(subcommand)]
798        action: ConfigAction,
799    },
800    /// FIDO2 client commands for managing authenticators
801    ///
802    /// These commands require a running authenticator. For testing:
803    /// 1. Start authenticator: PASSLESS_E2E_AUTO_ACCEPT_UV=1 cargo run -- --backend-type local
804    /// 2. Run client commands in another terminal with the same environment variable
805    Client {
806        /// Select device by index (0-based) or name. Use 'devices' subcommand to list available devices.
807        #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
808        device: Option<String>,
809
810        /// Output format: plain (default) or json
811        #[arg(
812            short = 'o',
813            long = "output",
814            value_name = "FORMAT",
815            default_value = "plain",
816            global = true
817        )]
818        output: OutputFormat,
819
820        #[command(subcommand)]
821        action: ClientAction,
822    },
823    /// Agent administration commands
824    #[cfg(feature = "agent")]
825    AgentAdmin {
826        /// Output format: json (default) or plain
827        #[arg(
828            short = 'o',
829            long = "output",
830            value_name = "FORMAT",
831            default_value = "json",
832            global = true
833        )]
834        output: OutputFormat,
835
836        #[command(subcommand)]
837        action: AgentAdminAction,
838    },
839    /// Check this host (does not need a running daemon)
840    #[cfg(feature = "agent")]
841    Doctor {
842        /// Check the agent browser path: a supported browser binary, the interception extension,
843        /// the native messaging host manifest, the notification bus, the state directory and the
844        /// containment of the native WebAuthn path
845        #[arg(long)]
846        agents: bool,
847
848        /// Output format: plain (default) or json
849        #[arg(
850            short = 'o',
851            long = "output",
852            value_name = "FORMAT",
853            default_value = "plain"
854        )]
855        output: OutputFormat,
856    },
857    /// Agent principal and session commands
858    #[cfg(feature = "agent")]
859    Agent {
860        /// Profile to use for principal commands
861        #[arg(long, value_name = "PROFILE", global = true)]
862        profile: Option<String>,
863
864        /// Output format: json (default) or plain
865        #[arg(
866            short = 'o',
867            long = "output",
868            value_name = "FORMAT",
869            default_value = "json",
870            global = true
871        )]
872        output: OutputFormat,
873
874        #[command(subcommand)]
875        action: crate::AgentCommand,
876    },
877    /// TPM portable parent management
878    #[cfg(feature = "tpm")]
879    Tpm {
880        #[command(subcommand)]
881        action: TpmAction,
882    },
883}
884
885/// TPM portable parent actions
886#[cfg(feature = "tpm")]
887#[derive(Subcommand, Debug, Clone)]
888pub enum TpmAction {
889    /// Provision the portable TPM parent from a recovery seed
890    #[command(group(clap::ArgGroup::new("seed-source").args(["generate", "seed_file", "seed_stdin"])))]
891    Provision {
892        /// Generate a new random 32-byte recovery seed and print it
893        #[arg(long)]
894        generate: bool,
895        /// Read the recovery seed (hex) from this file instead of prompting
896        #[arg(long = "seed-file", value_name = "PATH")]
897        seed_file: Option<PathBuf>,
898        /// Read the recovery seed (hex) from stdin instead of prompting
899        #[arg(long = "seed-stdin")]
900        seed_stdin: bool,
901        /// TPM storage directory
902        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
903        path: Option<String>,
904        /// TPM TCTI configuration
905        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
906        tcti: Option<String>,
907    },
908    /// Show provisioning status
909    Status {
910        /// TPM storage directory
911        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
912        path: Option<String>,
913        /// TPM TCTI configuration
914        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
915        tcti: Option<String>,
916    },
917    /// Remove the provisioned portable parent
918    Remove {
919        /// Confirm the removal
920        #[arg(long)]
921        confirm: bool,
922        /// TPM storage directory
923        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
924        path: Option<String>,
925        /// TPM TCTI configuration
926        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
927        tcti: Option<String>,
928    },
929    /// Migrate legacy sealed credentials to portable TPM format
930    #[command(group(clap::ArgGroup::new("selection").args(["credential_id", "all"]).required(true)))]
931    Migrate {
932        /// Migrate a specific credential by ID (hex)
933        #[arg(long = "credential-id", value_name = "ID")]
934        credential_id: Option<String>,
935        /// Migrate all migratable legacy credentials
936        #[arg(long)]
937        all: bool,
938        /// Show what would be migrated without making changes
939        #[arg(long)]
940        dry_run: bool,
941        /// Directory to store backups of legacy records
942        #[arg(long = "backup-dir", value_name = "PATH")]
943        backup_dir: Option<String>,
944        /// TPM storage directory
945        #[arg(long = "tpm-path", env = "PASSLESS_TPM_PATH")]
946        path: Option<String>,
947        /// TPM TCTI configuration
948        #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI")]
949        tcti: Option<String>,
950    },
951}
952
953/// Configuration actions
954#[derive(Subcommand, Debug, Clone)]
955pub enum ConfigAction {
956    /// Print the default configuration in TOML format
957    Print,
958    /// Validate the configuration offline, as the daemon would at startup
959    ///
960    /// Loads the file like the daemon does (CLI flags and file merged, agent profiles parsed) and
961    /// runs the daemon's validation, including the agent profile rules and deprecation warnings.
962    /// Prints the warnings and exits non-zero on an error. It needs no running daemon, D-Bus or
963    /// UHID: run it before restarting the service.
964    Check {
965        /// Configuration file to check (default: `PASSLESS_CONFIG`, else
966        /// `~/.config/passless/config.toml`)
967        #[arg(short = 'c', long, value_name = "PATH")]
968        config_path: Option<PathBuf>,
969    },
970}
971
972/// Agent administration actions
973#[cfg(feature = "agent")]
974#[derive(Subcommand, Debug, Clone)]
975pub enum AgentAdminAction {
976    /// Install the Passless skill for a supported coding agent
977    Install {
978        /// Agent to install for; auto installs to every detected agent
979        #[arg(value_enum, default_value_t = AgentSkillTarget::Auto)]
980        target: AgentSkillTarget,
981
982        /// Install for the current user or the current Git worktree
983        #[arg(long, value_enum, default_value_t = AgentSkillScope::User)]
984        scope: AgentSkillScope,
985
986        /// Replace a different existing file at the skill target
987        #[arg(long)]
988        force: bool,
989    },
990    /// Profile management
991    Profile {
992        #[command(subcommand)]
993        action: AdminProfileAction,
994    },
995    /// Policy management
996    Policy {
997        #[command(subcommand)]
998        action: AdminPolicyAction,
999    },
1000    /// Credential management
1001    Credential {
1002        #[command(subcommand)]
1003        action: AdminCredentialAction,
1004    },
1005    /// Persistent granted rules (escalation approvals)
1006    Grants {
1007        #[command(subcommand)]
1008        action: AdminGrantsAction,
1009    },
1010    /// Browser bearer sessions (session grants)
1011    #[command(alias = "delegation")]
1012    Sessions {
1013        #[command(subcommand)]
1014        action: AdminSessionsAction,
1015    },
1016    /// Principal sessions
1017    #[command(alias = "session")]
1018    Principals {
1019        #[command(subcommand)]
1020        action: AdminPrincipalsAction,
1021    },
1022    /// Browser session management
1023    Browser {
1024        #[command(subcommand)]
1025        action: AdminBrowserAction,
1026    },
1027    /// Audit log management
1028    Audit {
1029        #[command(subcommand)]
1030        action: AdminAuditAction,
1031    },
1032    /// Shut down the running daemon
1033    #[command(hide = true)]
1034    Shutdown {
1035        /// Confirm the shutdown
1036        #[arg(long)]
1037        confirm: bool,
1038    },
1039}
1040
1041/// Admin profile actions
1042#[cfg(feature = "agent")]
1043#[derive(Subcommand, Debug, Clone)]
1044pub enum AdminProfileAction {
1045    /// Check if a profile exists and is valid
1046    Check {
1047        /// Profile identifier
1048        #[arg(value_name = "PROFILE")]
1049        profile: String,
1050    },
1051    /// Show profile details
1052    Show {
1053        /// Profile identifier
1054        #[arg(value_name = "PROFILE")]
1055        profile: String,
1056    },
1057    /// List all configured profiles
1058    List,
1059    /// Enable a profile
1060    Enable {
1061        /// Profile identifier
1062        #[arg(value_name = "PROFILE")]
1063        profile: String,
1064    },
1065    /// Disable a profile
1066    Disable {
1067        /// Profile identifier
1068        #[arg(value_name = "PROFILE")]
1069        profile: String,
1070    },
1071}
1072
1073/// Admin policy actions
1074#[cfg(feature = "agent")]
1075#[derive(Subcommand, Debug, Clone)]
1076pub enum AdminPolicyAction {
1077    /// Check policy validity for a profile
1078    Check {
1079        /// Profile identifier
1080        #[arg(value_name = "PROFILE")]
1081        profile: String,
1082    },
1083    /// Reload policy for a profile
1084    Reload {
1085        /// Profile identifier
1086        #[arg(value_name = "PROFILE")]
1087        profile: String,
1088    },
1089    /// Show current policy for a profile
1090    Show {
1091        /// Profile identifier
1092        #[arg(value_name = "PROFILE")]
1093        profile: String,
1094    },
1095}
1096
1097/// Admin credential actions
1098#[cfg(feature = "agent")]
1099#[derive(Subcommand, Debug, Clone)]
1100pub enum AdminCredentialAction {
1101    /// List credentials
1102    List {
1103        /// Filter by relying party ID
1104        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1105        rp_id: Option<String>,
1106    },
1107    /// Show credential details
1108    Show {
1109        /// Credential reference (hex)
1110        #[arg(value_name = "CREDENTIAL_REF")]
1111        credential_ref: String,
1112    },
1113    /// Revoke a credential
1114    Revoke {
1115        /// Credential reference (hex)
1116        #[arg(value_name = "CREDENTIAL_REF")]
1117        credential_ref: String,
1118        /// Confirm the revocation
1119        #[arg(long)]
1120        confirm: bool,
1121    },
1122    /// Delete a credential
1123    Delete {
1124        /// Credential reference (hex)
1125        #[arg(value_name = "CREDENTIAL_REF")]
1126        credential_ref: String,
1127        /// Confirm the deletion
1128        #[arg(long)]
1129        confirm: bool,
1130    },
1131}
1132
1133/// Admin granted-rule actions (ADR 0014 section 8.4)
1134#[cfg(feature = "agent")]
1135#[derive(Subcommand, Debug, Clone)]
1136pub enum AdminGrantsAction {
1137    /// List granted rules
1138    List {
1139        /// Filter by profile
1140        #[arg(long, value_name = "PROFILE")]
1141        profile: Option<String>,
1142    },
1143    /// Revoke the granted rule of one RP
1144    Revoke {
1145        /// Profile identifier
1146        #[arg(long, value_name = "PROFILE")]
1147        profile: String,
1148        /// Relying party ID
1149        #[arg(long = "rp", value_name = "RP_ID")]
1150        rp_id: String,
1151        /// Action of the granted rule
1152        #[arg(long, value_enum, default_value_t = AdminGrantAction::Authenticate)]
1153        action: AdminGrantAction,
1154        /// Confirm the revocation
1155        #[arg(long)]
1156        confirm: bool,
1157    },
1158    /// Revoke every granted rule of a profile
1159    Clear {
1160        /// Profile identifier
1161        #[arg(long, value_name = "PROFILE")]
1162        profile: String,
1163        /// Confirm the revocation
1164        #[arg(long)]
1165        confirm: bool,
1166    },
1167}
1168
1169/// Action of a granted rule (only `authenticate` is ever granted)
1170#[cfg(feature = "agent")]
1171#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1172pub enum AdminGrantAction {
1173    Authenticate,
1174}
1175
1176/// Admin browser bearer session actions
1177#[cfg(feature = "agent")]
1178#[derive(Subcommand, Debug, Clone)]
1179pub enum AdminSessionsAction {
1180    /// Show session grant details
1181    Show {
1182        /// Grant identifier (hex)
1183        #[arg(value_name = "GRANT_ID")]
1184        grant_id: String,
1185    },
1186    /// List all session grants
1187    List {
1188        /// Filter by profile
1189        #[arg(long, value_name = "PROFILE")]
1190        profile: Option<String>,
1191    },
1192    /// Revoke a session grant
1193    Revoke {
1194        /// Grant identifier (hex)
1195        #[arg(value_name = "GRANT_ID")]
1196        grant_id: String,
1197        /// Confirm the revocation
1198        #[arg(long)]
1199        confirm: bool,
1200    },
1201}
1202
1203/// Admin principal session actions
1204#[cfg(feature = "agent")]
1205#[derive(Subcommand, Debug, Clone)]
1206pub enum AdminPrincipalsAction {
1207    /// Show principal session details
1208    Show {
1209        /// Session identifier (hex)
1210        #[arg(value_name = "SESSION_ID")]
1211        session_id: String,
1212    },
1213    /// List all sessions
1214    List {
1215        /// Filter by profile
1216        #[arg(long, value_name = "PROFILE")]
1217        profile: Option<String>,
1218    },
1219    /// Revoke a session
1220    Revoke {
1221        /// Session identifier (hex)
1222        #[arg(value_name = "SESSION_ID")]
1223        session_id: String,
1224        /// Confirm the revocation
1225        #[arg(long)]
1226        confirm: bool,
1227    },
1228}
1229
1230/// Admin browser actions
1231#[cfg(feature = "agent")]
1232#[derive(Subcommand, Debug, Clone)]
1233pub enum AdminBrowserAction {
1234    /// Launch a browser session with the agent extension
1235    Launch {
1236        /// Profile identifier
1237        #[arg(long, value_name = "PROFILE")]
1238        profile: String,
1239        /// Start URL to open in the browser
1240        #[arg(long, value_name = "URL")]
1241        url: Option<String>,
1242    },
1243}
1244
1245/// Admin audit actions
1246#[cfg(feature = "agent")]
1247#[derive(Subcommand, Debug, Clone)]
1248pub enum AdminAuditAction {
1249    /// Show audit subsystem status
1250    Status,
1251    /// Verify audit log integrity
1252    Verify,
1253    /// Export audit log entries
1254    Export {
1255        /// Export format
1256        #[arg(long, value_enum, default_value_t = AdminAuditExportFormat::Json)]
1257        format: AdminAuditExportFormat,
1258    },
1259}
1260
1261/// Audit export format for CLI
1262#[cfg(feature = "agent")]
1263#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1264pub enum AdminAuditExportFormat {
1265    Json,
1266    Csv,
1267}
1268
1269/// Supported coding-agent skill targets
1270#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1271pub enum AgentSkillTarget {
1272    Auto,
1273    Opencode,
1274    Claude,
1275    Pi,
1276}
1277
1278/// Skill installation scope
1279#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1280pub enum AgentSkillScope {
1281    User,
1282    Project,
1283}
1284
1285/// Client actions for FIDO2 authenticator management
1286#[derive(Subcommand, Debug, Clone)]
1287pub enum ClientAction {
1288    /// List all available FIDO2 authenticators/devices
1289    Devices,
1290    /// Get authenticator information (capabilities, AAGUID, versions, etc.)
1291    Info,
1292    /// Reset the authenticator (WARNING: deletes ALL credentials)
1293    Reset {
1294        /// Confirmation flag that must be provided twice for safety
1295        #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
1296        confirm: u8,
1297    },
1298    /// List all credentials on the authenticator
1299    List {
1300        /// Filter by relying party ID (domain)
1301        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
1302        rp_id: Option<String>,
1303    },
1304    /// Show detailed information about a specific credential
1305    Show {
1306        /// Credential ID in hexadecimal format
1307        #[arg(value_name = "CREDENTIAL_ID")]
1308        credential_id: String,
1309    },
1310    /// Delete a specific credential by ID
1311    Delete {
1312        /// Credential ID in hexadecimal format
1313        #[arg(value_name = "CREDENTIAL_ID")]
1314        credential_id: String,
1315    },
1316    /// Rename a credential (update user name and/or display name)
1317    Rename {
1318        /// Credential ID in hexadecimal format
1319        #[arg(value_name = "CREDENTIAL_ID")]
1320        credential_id: String,
1321        /// New user name (login identifier)
1322        #[arg(short = 'u', long = "user-name", value_name = "NAME")]
1323        user_name: Option<String>,
1324        /// New display name (friendly name)
1325        #[arg(short = 'n', long = "display-name", value_name = "NAME")]
1326        display_name: Option<String>,
1327    },
1328    /// Export one software-backed credential as an opaque encrypted bundle.
1329    Backup {
1330        /// Credential ID in hexadecimal format
1331        #[arg(value_name = "CREDENTIAL_ID")]
1332        credential_id: String,
1333        /// Authenticator-local credential-backup wrapping-key identifier
1334        #[arg(long, value_name = "RECIPIENT")]
1335        recipient: String,
1336        /// Destination bundle path
1337        #[arg(long, value_name = "PATH")]
1338        output_file: PathBuf,
1339        /// Explicitly acknowledge that a passkey is being exported
1340        #[arg(long = "yes-i-understand-this-exports-a-passkey")]
1341        confirm: bool,
1342    },
1343    /// Restore an encrypted Passless credential bundle.
1344    Restore {
1345        /// Source bundle path
1346        #[arg(value_name = "PATH")]
1347        input_file: PathBuf,
1348        /// Replace a credential with the same ID
1349        #[arg(long)]
1350        replace: bool,
1351        /// Explicitly acknowledge that a passkey is being restored
1352        #[arg(long = "yes-i-understand-this-restores-a-passkey")]
1353        confirm: bool,
1354    },
1355    /// PIN management commands
1356    Pin {
1357        #[command(subcommand)]
1358        action: PinAction,
1359    },
1360}
1361
1362/// PIN management actions
1363#[derive(Subcommand, Debug, Clone)]
1364pub enum PinAction {
1365    /// Set a new PIN (authenticator must not have a PIN set)
1366    Set {
1367        /// The new PIN (minimum 4 characters)
1368        #[arg(value_name = "PIN")]
1369        pin: String,
1370    },
1371    /// Change the existing PIN
1372    Change {
1373        /// The current PIN
1374        #[arg(value_name = "OLD_PIN")]
1375        old_pin: String,
1376        /// The new PIN (minimum 4 characters)
1377        #[arg(value_name = "NEW_PIN")]
1378        new_pin: String,
1379    },
1380    /// Reset built-in user verification retries without deleting credentials
1381    UvReset,
1382}
1383
1384/// Agent principal and session commands
1385#[cfg(feature = "agent")]
1386#[derive(Subcommand, Debug, Clone)]
1387pub enum AgentCommand {
1388    /// Run health diagnostics
1389    Doctor,
1390    /// Show the profile's effective authority (per-RP rules, credential scope, session limits)
1391    Capabilities,
1392    /// Show principal instructions
1393    Instructions,
1394    /// Credential queries
1395    Credential {
1396        #[command(subcommand)]
1397        action: AgentCredentialAction,
1398    },
1399    /// Show browser bridge status
1400    BrowserStatus,
1401    /// Send a CDP command to the managed browser session
1402    ///
1403    /// WARNING: This is the full browser-session authority interface.
1404    /// CDP commands can access cookies, DOM, network state, and session data.
1405    /// Output may contain CDP response data — do not mix with credential/admin output.
1406    BrowserControl {
1407        /// CDP request as JSON (e.g. '{"id":1,"method":"Page.navigate","params":{"url":"https://example.com"}}')
1408        #[arg(long, value_name = "JSON", conflicts_with = "request_file")]
1409        request: Option<String>,
1410        /// Path to file containing CDP request JSON (owner/symlink/size checked)
1411        #[arg(long, value_name = "PATH", conflicts_with = "request")]
1412        request_file: Option<std::path::PathBuf>,
1413        /// Timeout in milliseconds (default: 5000, max: 30000)
1414        #[arg(long, value_name = "MS", default_value = "5000")]
1415        timeout_ms: u32,
1416    },
1417    /// Ensure the managed browser of this principal and print how to reach it
1418    ///
1419    /// Idempotent: the browser is started on the first call and the same endpoint is printed
1420    /// while it runs (the profile's `browser_scope` decides whether sessions share it). The
1421    /// endpoint is withheld until the interception extension is attached and allowed in
1422    /// incognito, so a printed endpoint is always an intercepted browser. With
1423    /// `browser_cdp_expose = "port"` the CDP endpoint is printed. In pipe mode (the default)
1424    /// there is no endpoint: the browser is ensured and CDP goes through
1425    /// `passless agent browser-control`. It must run inside a principal session of the profile
1426    /// (the browser is closed when that session ends), e.g. an agent started with
1427    /// `passless agent run --profile P -- <command>`.
1428    Browser {
1429        /// Print JSON ({endpoint, ...}) instead of the bare endpoint URL
1430        #[arg(long, conflicts_with = "env")]
1431        json: bool,
1432        /// Print `PASSLESS_CDP_URL=<endpoint>`, for `eval` or a dotenv file
1433        #[arg(long)]
1434        env: bool,
1435        /// Block until the browser is intercepting (attached, incognito allowed) before printing
1436        #[arg(long)]
1437        wait: bool,
1438        /// Start a headed browser instead of the default `--headless=new`
1439        #[arg(long)]
1440        headed: bool,
1441        /// Open this URL once interception is attached
1442        #[arg(long, value_name = "URL")]
1443        url: Option<String>,
1444    },
1445    /// MCP server adapters for the managed browser (stdio launchers)
1446    #[command(args_conflicts_with_subcommands = true)]
1447    Mcp {
1448        /// Print a ready-to-paste MCP server entry for a client instead of running a server
1449        #[arg(long, value_enum, value_name = "CLIENT")]
1450        print_config: Option<McpConfigTarget>,
1451        /// The adapter the printed entry runs
1452        #[arg(long, value_enum, default_value_t = McpAdapterKind::Playwright, requires = "print_config")]
1453        server: McpAdapterKind,
1454        #[command(subcommand)]
1455        adapter: Option<McpAdapter>,
1456    },
1457    /// Run Playwright MCP with lazy access to the profile's trusted CDP browser
1458    ///
1459    /// Deprecated alias of `agent mcp playwright`, kept for one release.
1460    #[command(hide = true)]
1461    PlaywrightMcp {
1462        /// Profile to bind the Playwright session to
1463        #[arg(long, value_name = "PROFILE")]
1464        profile: String,
1465        /// Start URL to open in the managed browser
1466        #[arg(long, value_name = "URL")]
1467        url: Option<String>,
1468        /// Absolute Playwright MCP executable and arguments
1469        #[arg(last = true, required = true)]
1470        command: Vec<std::path::PathBuf>,
1471    },
1472    /// Internal: the principal-session side of `agent mcp playwright`
1473    ///
1474    /// Started by `agent mcp playwright` through the admin socket, never by hand. It holds the
1475    /// principal session's capability descriptor and answers one request on its stdin, "ensure
1476    /// the browser", with the CDP endpoint. It exits when its stdin closes.
1477    #[command(hide = true)]
1478    McpSessionBroker {
1479        /// Profile of the principal session
1480        #[arg(long, value_name = "PROFILE")]
1481        profile: String,
1482        /// Start URL to open in the managed browser
1483        #[arg(long, value_name = "URL")]
1484        url: Option<String>,
1485    },
1486    /// Launch a detached principal session
1487    Run {
1488        /// Profile to launch
1489        #[arg(long, value_name = "PROFILE")]
1490        profile: String,
1491        /// Absolute command path and arguments
1492        #[arg(last = true, required = true)]
1493        command: Vec<std::path::PathBuf>,
1494    },
1495}
1496
1497/// An MCP server the adapters run against the managed browser.
1498#[cfg(feature = "agent")]
1499#[derive(Subcommand, Debug, Clone)]
1500pub enum McpAdapter {
1501    /// Run `npx @playwright/mcp --cdp-endpoint <url>` (the endpoint is resolved on first use)
1502    Playwright {
1503        /// npm package to run (default `@playwright/mcp`; pin a version here)
1504        #[arg(long, value_name = "SPEC")]
1505        package: Option<String>,
1506        /// npx executable (default: `npx` from PATH)
1507        #[arg(long, value_name = "PATH")]
1508        npx: Option<std::path::PathBuf>,
1509        /// Open this URL once interception is attached
1510        #[arg(long, value_name = "URL")]
1511        url: Option<String>,
1512        /// Print a ready-to-paste MCP server entry for a client instead of running the server
1513        #[arg(long, value_enum, value_name = "CLIENT")]
1514        print_config: Option<McpConfigTarget>,
1515        /// Extra arguments for @playwright/mcp (after `--`)
1516        #[arg(last = true)]
1517        extra: Vec<String>,
1518    },
1519    /// Run `npx chrome-devtools-mcp --browserUrl <url>`
1520    ///
1521    /// The browser starts when the server starts: puppeteer asks `<browserUrl>/json/version`
1522    /// at the root of the URL and cannot send the bootstrap's bearer header, so a lazy,
1523    /// authenticated discovery endpoint is not possible.
1524    ChromeDevtools {
1525        /// npm package to run (default `chrome-devtools-mcp`; pin a version here)
1526        #[arg(long, value_name = "SPEC")]
1527        package: Option<String>,
1528        /// npx executable (default: `npx` from PATH)
1529        #[arg(long, value_name = "PATH")]
1530        npx: Option<std::path::PathBuf>,
1531        /// Open this URL once interception is attached
1532        #[arg(long, value_name = "URL")]
1533        url: Option<String>,
1534        /// Print a ready-to-paste MCP server entry for a client instead of running the server
1535        #[arg(long, value_enum, value_name = "CLIENT")]
1536        print_config: Option<McpConfigTarget>,
1537        /// Extra arguments for chrome-devtools-mcp (after `--`)
1538        #[arg(last = true)]
1539        extra: Vec<String>,
1540    },
1541    /// Rewrite plain Playwright MCP / chrome-devtools-mcp entries of a client to run through Passless
1542    ///
1543    /// Finds entries that start their own browser (`npx @playwright/mcp`, `pnpm dlx`, `bunx`,
1544    /// `yarn dlx`, a `playwright-mcp` binary, `chrome-devtools-mcp`) in the client's MCP
1545    /// configuration and rewrites each in place to `passless agent mcp playwright|chrome-devtools`,
1546    /// so the agent keeps its tools and passkeys go through the managed browser and the profile's
1547    /// rules. A file with no such entry gets a new `playwright` server that runs through Passless
1548    /// (a file that does not exist is created; a different server named `playwright` is never
1549    /// replaced). With `--user` on Claude Code, entries kept per project by `claude mcp add`
1550    /// (local scope, in `projects.<path>.mcpServers`) are rewritten too. The default is a dry run
1551    /// that prints a diff; `--yes` writes, after saving a backup.
1552    /// The profile is the global `--profile`: required unless exactly one usable profile (with
1553    /// `browser_cdp_expose = "port"`) is configured.
1554    Install {
1555        /// The MCP client whose configuration to change
1556        #[arg(long, value_enum, value_name = "CLIENT")]
1557        client: McpInstallClient,
1558        /// Change the client's user-level configuration (the default)
1559        #[arg(long, conflicts_with = "project")]
1560        user: bool,
1561        /// Change the configuration of this project directory instead
1562        #[arg(long, value_name = "DIR", conflicts_with = "user")]
1563        project: Option<std::path::PathBuf>,
1564        /// Write the change (after saving `<file>.passless-backup-<UTC timestamp>`); without it,
1565        /// print the diff only
1566        #[arg(long)]
1567        yes: bool,
1568        /// Also install or refresh the bundled `passless-agent` skill for the client
1569        #[arg(long)]
1570        skill: bool,
1571        /// The `passless` the entries run (absolute path). Default: the first `passless` on
1572        /// `PATH`, else this executable
1573        #[arg(long, value_name = "ABS")]
1574        passless_path: Option<std::path::PathBuf>,
1575    },
1576}
1577
1578/// Which adapter `agent mcp --print-config` prints an entry for.
1579#[cfg(feature = "agent")]
1580#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1581pub enum McpAdapterKind {
1582    Playwright,
1583    ChromeDevtools,
1584}
1585
1586/// MCP clients `agent mcp install` can rewrite the configuration of.
1587#[cfg(feature = "agent")]
1588#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1589pub enum McpInstallClient {
1590    /// `opencode.json` (`mcp.servers.<name>`, or the legacy `mcp.<name>`)
1591    Opencode,
1592    /// `~/.claude.json` (`$CLAUDE_CONFIG_DIR/.claude.json`) and `.mcp.json`: `mcpServers.<name>`
1593    ClaudeCode,
1594}
1595
1596/// MCP clients `agent mcp --print-config` knows the configuration format of.
1597#[cfg(feature = "agent")]
1598#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1599pub enum McpConfigTarget {
1600    /// `.mcp.json` / `claude mcp add-json`
1601    ClaudeCode,
1602    /// `opencode.json`
1603    Opencode,
1604    /// `.cursor/mcp.json`
1605    Cursor,
1606    /// `.vscode/mcp.json`
1607    Vscode,
1608}
1609
1610/// Agent credential actions
1611#[cfg(feature = "agent")]
1612#[derive(Subcommand, Debug, Clone)]
1613pub enum AgentCredentialAction {
1614    /// List credentials for the profile
1615    List,
1616    /// Show credential details
1617    Show {
1618        /// Credential reference (hex)
1619        #[arg(value_name = "CREDENTIAL_REF")]
1620        credential_ref: String,
1621    },
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626    use super::*;
1627
1628    #[cfg(feature = "agent")]
1629    #[test]
1630    fn test_agent_admin_install_defaults() {
1631        let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1632        assert!(matches!(
1633            args.command,
1634            Some(Commands::AgentAdmin {
1635                action: AgentAdminAction::Install {
1636                    target: AgentSkillTarget::Auto,
1637                    scope: AgentSkillScope::User,
1638                    force: false,
1639                },
1640                ..
1641            })
1642        ));
1643    }
1644
1645    #[cfg(feature = "agent")]
1646    #[test]
1647    fn test_agent_admin_install_explicit_options() {
1648        let args = Args::try_parse_from([
1649            "passless",
1650            "agent-admin",
1651            "install",
1652            "claude",
1653            "--scope",
1654            "project",
1655            "--force",
1656        ])
1657        .unwrap();
1658        assert!(matches!(
1659            args.command,
1660            Some(Commands::AgentAdmin {
1661                action: AgentAdminAction::Install {
1662                    target: AgentSkillTarget::Claude,
1663                    scope: AgentSkillScope::Project,
1664                    force: true,
1665                },
1666                ..
1667            })
1668        ));
1669    }
1670
1671    #[test]
1672    fn test_pin_config_default_max_uv_retries() {
1673        let config = PinConfig {
1674            enforcement: PinEnforcement::Optional,
1675            min_length: 4,
1676            max_retries: 8,
1677            max_uv_retries: 8,
1678            auto_lock_timeout: 0,
1679        };
1680        assert_eq!(config.max_uv_retries, 8);
1681    }
1682
1683    #[test]
1684    fn test_pin_config_validate_success() {
1685        let config = PinConfig {
1686            enforcement: PinEnforcement::Optional,
1687            min_length: 4,
1688            max_retries: 8,
1689            max_uv_retries: 8,
1690            auto_lock_timeout: 0,
1691        };
1692        assert!(config.validate().is_ok());
1693    }
1694
1695    #[test]
1696    fn test_pin_config_validate_zero_max_uv_retries() {
1697        let config = PinConfig {
1698            enforcement: PinEnforcement::Optional,
1699            min_length: 4,
1700            max_retries: 8,
1701            max_uv_retries: 0,
1702            auto_lock_timeout: 0,
1703        };
1704        let result = config.validate();
1705        assert!(result.is_err());
1706        assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1707    }
1708
1709    #[test]
1710    fn test_pin_config_validate_zero_max_retries() {
1711        let config = PinConfig {
1712            enforcement: PinEnforcement::Optional,
1713            min_length: 4,
1714            max_retries: 0,
1715            max_uv_retries: 8,
1716            auto_lock_timeout: 0,
1717        };
1718        let result = config.validate();
1719        assert!(result.is_err());
1720        assert!(result.unwrap_err().to_string().contains("max_retries"));
1721    }
1722
1723    #[test]
1724    fn test_pin_config_validate_invalid_min_length() {
1725        let config = PinConfig {
1726            enforcement: PinEnforcement::Optional,
1727            min_length: 3,
1728            max_retries: 8,
1729            max_uv_retries: 8,
1730            auto_lock_timeout: 0,
1731        };
1732        let result = config.validate();
1733        assert!(result.is_err());
1734        assert!(result.unwrap_err().to_string().contains("min_length"));
1735    }
1736
1737    #[test]
1738    fn test_canonicalize_path_existing() {
1739        let dir = std::env::temp_dir();
1740        let canonical = BackendConfig::canonicalize_path(&dir);
1741        assert!(canonical.is_absolute());
1742        assert!(canonical.exists());
1743    }
1744
1745    #[test]
1746    fn test_canonicalize_path_nonexistent() {
1747        let base = std::env::temp_dir();
1748        let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1749        let canonical = BackendConfig::canonicalize_path(&nonexistent);
1750        assert!(canonical.is_absolute());
1751        assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1752    }
1753
1754    #[test]
1755    fn test_canonicalize_path_symlink() {
1756        let dir = tempfile::tempdir().unwrap();
1757        let real = dir.path().join("real");
1758        std::fs::create_dir(&real).unwrap();
1759        let link = dir.path().join("link");
1760        std::os::unix::fs::symlink(&real, &link).unwrap();
1761
1762        let canonical_real = BackendConfig::canonicalize_path(&real);
1763        let canonical_link = BackendConfig::canonicalize_path(&link);
1764        assert_eq!(canonical_real, canonical_link);
1765    }
1766
1767    #[test]
1768    fn test_local_state_path_relative_and_absolute() {
1769        let dir = tempfile::tempdir_in(".").unwrap();
1770        let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1771        let rel_path = dir.path().to_path_buf();
1772
1773        let backend_abs = BackendConfig::Local {
1774            path: abs_path.display().to_string(),
1775        };
1776        let backend_rel = BackendConfig::Local {
1777            path: rel_path.display().to_string(),
1778        };
1779        assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1780    }
1781
1782    #[test]
1783    fn test_pass_state_path_different_subpaths() {
1784        let store = "/tmp/passless_test_store";
1785        let backend_a = BackendConfig::Pass {
1786            store_path: store.to_string(),
1787            path: "fido2".to_string(),
1788            gpg_backend: "gnupg-bin".to_string(),
1789        };
1790        let backend_b = BackendConfig::Pass {
1791            store_path: store.to_string(),
1792            path: "fido2-other".to_string(),
1793            gpg_backend: "gnupg-bin".to_string(),
1794        };
1795        assert_ne!(backend_a.state_path(), backend_b.state_path());
1796    }
1797
1798    #[test]
1799    fn test_different_local_paths_produce_different_identities() {
1800        let backend_a = BackendConfig::Local {
1801            path: "/tmp/passless_a".to_string(),
1802        };
1803        let backend_b = BackendConfig::Local {
1804            path: "/tmp/passless_b".to_string(),
1805        };
1806        assert_ne!(backend_a.state_path(), backend_b.state_path());
1807    }
1808
1809    #[cfg(feature = "agent")]
1810    #[test]
1811    fn test_agent_admin_profile_list() {
1812        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1813        assert!(matches!(
1814            args.command,
1815            Some(Commands::AgentAdmin {
1816                action: AgentAdminAction::Profile {
1817                    action: AdminProfileAction::List,
1818                },
1819                ..
1820            })
1821        ));
1822    }
1823
1824    #[cfg(feature = "agent")]
1825    #[test]
1826    fn test_agent_admin_credential_delete_without_confirm() {
1827        let args = Args::try_parse_from([
1828            "passless",
1829            "agent-admin",
1830            "credential",
1831            "delete",
1832            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1833        ])
1834        .unwrap();
1835        assert!(matches!(
1836            args.command,
1837            Some(Commands::AgentAdmin {
1838                action: AgentAdminAction::Credential {
1839                    action: AdminCredentialAction::Delete { confirm: false, .. },
1840                },
1841                ..
1842            })
1843        ));
1844    }
1845
1846    #[cfg(feature = "agent")]
1847    #[test]
1848    fn test_agent_admin_credential_delete_with_confirm() {
1849        let args = Args::try_parse_from([
1850            "passless",
1851            "agent-admin",
1852            "credential",
1853            "delete",
1854            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1855            "--confirm",
1856        ])
1857        .unwrap();
1858        assert!(matches!(
1859            args.command,
1860            Some(Commands::AgentAdmin {
1861                action: AgentAdminAction::Credential {
1862                    action: AdminCredentialAction::Delete { confirm: true, .. },
1863                },
1864                ..
1865            })
1866        ));
1867    }
1868
1869    #[cfg(feature = "agent")]
1870    #[test]
1871    fn test_agent_admin_shutdown_hidden() {
1872        let args =
1873            Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1874        assert!(matches!(
1875            args.command,
1876            Some(Commands::AgentAdmin {
1877                action: AgentAdminAction::Shutdown { confirm: true },
1878                ..
1879            })
1880        ));
1881    }
1882
1883    #[cfg(feature = "agent")]
1884    #[test]
1885    fn test_agent_admin_output_default_json() {
1886        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1887        match args.command {
1888            Some(Commands::AgentAdmin { output, .. }) => {
1889                assert_eq!(output, OutputFormat::Json);
1890            }
1891            _ => panic!("expected AgentAdmin command"),
1892        }
1893    }
1894
1895    #[cfg(feature = "agent")]
1896    #[test]
1897    fn test_agent_admin_output_plain() {
1898        let args = Args::try_parse_from([
1899            "passless",
1900            "agent-admin",
1901            "--output",
1902            "plain",
1903            "profile",
1904            "list",
1905        ])
1906        .unwrap();
1907        match args.command {
1908            Some(Commands::AgentAdmin { output, .. }) => {
1909                assert_eq!(output, OutputFormat::Plain);
1910            }
1911            _ => panic!("expected AgentAdmin command"),
1912        }
1913    }
1914
1915    #[cfg(feature = "agent")]
1916    #[test]
1917    fn test_agent_doctor_parses() {
1918        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1919        assert!(matches!(
1920            args.command,
1921            Some(Commands::Agent {
1922                action: AgentCommand::Doctor,
1923                ..
1924            })
1925        ));
1926    }
1927
1928    #[cfg(feature = "agent")]
1929    #[test]
1930    fn test_agent_browser_parses() {
1931        let args = Args::try_parse_from([
1932            "passless",
1933            "agent",
1934            "--profile",
1935            "p",
1936            "browser",
1937            "--json",
1938            "--wait",
1939            "--headed",
1940        ])
1941        .unwrap();
1942        let Some(Commands::Agent {
1943            profile,
1944            action:
1945                AgentCommand::Browser {
1946                    json,
1947                    env,
1948                    wait,
1949                    headed,
1950                    url,
1951                },
1952            ..
1953        }) = args.command
1954        else {
1955            panic!("not agent browser");
1956        };
1957        assert_eq!(profile.as_deref(), Some("p"));
1958        assert!(json && wait && headed && !env && url.is_none());
1959        // `--profile` after the subcommand works too (it is global), and `--json` excludes `--env`.
1960        let args =
1961            Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
1962                .unwrap();
1963        assert!(matches!(
1964            args.command,
1965            Some(Commands::Agent {
1966                action: AgentCommand::Browser { env: true, .. },
1967                ..
1968            })
1969        ));
1970        assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
1971    }
1972
1973    #[cfg(feature = "agent")]
1974    #[test]
1975    fn test_agent_mcp_parses() {
1976        let args = Args::try_parse_from([
1977            "passless",
1978            "agent",
1979            "mcp",
1980            "playwright",
1981            "--profile",
1982            "p",
1983            "--",
1984            "--isolated",
1985        ])
1986        .unwrap();
1987        let Some(Commands::Agent {
1988            action:
1989                AgentCommand::Mcp {
1990                    adapter: Some(McpAdapter::Playwright { extra, .. }),
1991                    print_config: None,
1992                    ..
1993                },
1994            profile,
1995            ..
1996        }) = args.command
1997        else {
1998            panic!("not agent mcp playwright");
1999        };
2000        assert_eq!(profile.as_deref(), Some("p"));
2001        assert_eq!(extra, ["--isolated"]);
2002
2003        let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
2004        assert!(matches!(
2005            args.command,
2006            Some(Commands::Agent {
2007                action: AgentCommand::Mcp {
2008                    adapter: Some(McpAdapter::ChromeDevtools { .. }),
2009                    ..
2010                },
2011                ..
2012            })
2013        ));
2014
2015        for (name, target) in [
2016            ("claude-code", McpConfigTarget::ClaudeCode),
2017            ("opencode", McpConfigTarget::Opencode),
2018            ("cursor", McpConfigTarget::Cursor),
2019            ("vscode", McpConfigTarget::Vscode),
2020        ] {
2021            let args = Args::try_parse_from([
2022                "passless",
2023                "agent",
2024                "--profile",
2025                "p",
2026                "mcp",
2027                "--print-config",
2028                name,
2029            ])
2030            .unwrap();
2031            assert!(matches!(
2032                args.command,
2033                Some(Commands::Agent {
2034                    action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
2035                    ..
2036                }) if t == target
2037            ));
2038        }
2039        assert!(
2040            Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
2041        );
2042        // The same flag on the adapter subcommand, with `--profile` after it.
2043        let args = Args::try_parse_from([
2044            "passless",
2045            "agent",
2046            "mcp",
2047            "playwright",
2048            "--profile",
2049            "coding",
2050            "--print-config",
2051            "claude-code",
2052        ])
2053        .unwrap();
2054        assert!(matches!(
2055            args.command,
2056            Some(Commands::Agent {
2057                profile: Some(ref profile),
2058                action: AgentCommand::Mcp {
2059                    print_config: None,
2060                    adapter: Some(McpAdapter::Playwright {
2061                        print_config: Some(McpConfigTarget::ClaudeCode),
2062                        ..
2063                    }),
2064                    ..
2065                },
2066                ..
2067            }) if profile == "coding"
2068        ));
2069        assert!(
2070            Args::try_parse_from([
2071                "passless",
2072                "agent",
2073                "mcp",
2074                "chrome-devtools",
2075                "--print-config",
2076                "opencode",
2077            ])
2078            .is_ok()
2079        );
2080        // The old name still parses (hidden alias, one release).
2081        assert!(
2082            Args::try_parse_from([
2083                "passless",
2084                "agent",
2085                "playwright-mcp",
2086                "--profile",
2087                "p",
2088                "--",
2089                "/usr/bin/npx",
2090                "x",
2091            ])
2092            .is_ok()
2093        );
2094    }
2095
2096    #[cfg(feature = "agent")]
2097    #[test]
2098    fn test_agent_mcp_install_parses() {
2099        let parse = |extra: &[&str]| {
2100            let mut argv = vec!["passless", "agent", "mcp", "install"];
2101            argv.extend_from_slice(extra);
2102            Args::try_parse_from(argv)
2103        };
2104        // The client is required; everything else is optional and the default is a dry run.
2105        assert!(parse(&[]).is_err());
2106        assert!(parse(&["--client", "emacs"]).is_err());
2107        let args = parse(&["--client", "opencode"]).unwrap();
2108        assert!(matches!(
2109            args.command,
2110            Some(Commands::Agent {
2111                profile: None,
2112                action: AgentCommand::Mcp {
2113                    adapter: Some(McpAdapter::Install {
2114                        client: McpInstallClient::Opencode,
2115                        user: false,
2116                        project: None,
2117                        yes: false,
2118                        skill: false,
2119                        passless_path: None,
2120                    }),
2121                    ..
2122                },
2123                ..
2124            })
2125        ));
2126        let args = parse(&[
2127            "--client",
2128            "claude-code",
2129            "--project",
2130            "/work/p",
2131            "--profile",
2132            "agent",
2133            "--yes",
2134            "--skill",
2135        ])
2136        .unwrap();
2137        match args.command {
2138            Some(Commands::Agent {
2139                profile,
2140                action:
2141                    AgentCommand::Mcp {
2142                        adapter:
2143                            Some(McpAdapter::Install {
2144                                client,
2145                                project,
2146                                yes,
2147                                skill,
2148                                ..
2149                            }),
2150                        ..
2151                    },
2152                ..
2153            }) => {
2154                assert_eq!(profile.as_deref(), Some("agent"));
2155                assert_eq!(client, McpInstallClient::ClaudeCode);
2156                assert_eq!(project, Some(std::path::PathBuf::from("/work/p")));
2157                assert!(yes && skill);
2158            }
2159            other => panic!("unexpected: {other:?}"),
2160        }
2161        // `--user` and `--project` exclude each other.
2162        assert!(parse(&["--client", "opencode", "--user", "--project", "/p"]).is_err());
2163        assert!(parse(&["--client", "opencode", "--user"]).is_ok());
2164        let args = parse(&[
2165            "--client",
2166            "opencode",
2167            "--passless-path",
2168            "/usr/bin/passless",
2169        ])
2170        .unwrap();
2171        assert!(matches!(
2172            args.command,
2173            Some(Commands::Agent {
2174                action: AgentCommand::Mcp {
2175                    adapter: Some(McpAdapter::Install { passless_path: Some(ref p), .. }),
2176                    ..
2177                },
2178                ..
2179            }) if p == std::path::Path::new("/usr/bin/passless")
2180        ));
2181    }
2182
2183    #[cfg(feature = "agent")]
2184    #[test]
2185    fn test_doctor_agents_parses() {
2186        let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
2187        assert!(matches!(
2188            args.command,
2189            Some(Commands::Doctor {
2190                agents: true,
2191                output: OutputFormat::Json
2192            })
2193        ));
2194    }
2195
2196    #[cfg(feature = "agent")]
2197    #[test]
2198    fn test_agent_run_with_command() {
2199        let args = Args::try_parse_from([
2200            "passless",
2201            "agent",
2202            "run",
2203            "--profile",
2204            "myprofile",
2205            "--",
2206            "/usr/bin/test",
2207            "arg1",
2208        ])
2209        .unwrap();
2210        match args.command {
2211            Some(Commands::Agent {
2212                action: AgentCommand::Run { profile, command },
2213                ..
2214            }) => {
2215                assert_eq!(profile, "myprofile");
2216                assert_eq!(command.len(), 2);
2217            }
2218            _ => panic!("expected Agent Run command"),
2219        }
2220    }
2221
2222    #[cfg(feature = "agent")]
2223    #[test]
2224    fn test_agent_admin_grants_parse() {
2225        let args = Args::try_parse_from([
2226            "passless",
2227            "agent-admin",
2228            "grants",
2229            "revoke",
2230            "--profile",
2231            "coding",
2232            "--rp",
2233            "example.com",
2234            "--confirm",
2235        ])
2236        .unwrap();
2237        assert!(matches!(
2238            args.command,
2239            Some(Commands::AgentAdmin {
2240                action: AgentAdminAction::Grants {
2241                    action: AdminGrantsAction::Revoke {
2242                        ref profile,
2243                        ref rp_id,
2244                        action: AdminGrantAction::Authenticate,
2245                        confirm: true,
2246                    },
2247                },
2248                ..
2249            }) if profile == "coding" && rp_id == "example.com"
2250        ));
2251        let args = Args::try_parse_from([
2252            "passless",
2253            "agent-admin",
2254            "grants",
2255            "clear",
2256            "--profile",
2257            "p",
2258        ])
2259        .unwrap();
2260        assert!(matches!(
2261            args.command,
2262            Some(Commands::AgentAdmin {
2263                action: AgentAdminAction::Grants {
2264                    action: AdminGrantsAction::Clear { confirm: false, .. },
2265                },
2266                ..
2267            })
2268        ));
2269        assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2270    }
2271
2272    #[cfg(feature = "agent")]
2273    #[test]
2274    fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2275        for (spelling, expect_sessions) in [
2276            ("sessions", true),
2277            ("delegation", true),
2278            ("principals", false),
2279            ("session", false),
2280        ] {
2281            let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2282            let is_sessions = matches!(
2283                args.command,
2284                Some(Commands::AgentAdmin {
2285                    action: AgentAdminAction::Sessions { .. },
2286                    ..
2287                })
2288            );
2289            let is_principals = matches!(
2290                args.command,
2291                Some(Commands::AgentAdmin {
2292                    action: AgentAdminAction::Principals { .. },
2293                    ..
2294                })
2295            );
2296            assert_eq!(is_sessions, expect_sessions, "{spelling}");
2297            assert_eq!(is_principals, !expect_sessions, "{spelling}");
2298        }
2299        assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2300    }
2301
2302    #[cfg(feature = "agent")]
2303    #[test]
2304    fn test_agent_output_default_json() {
2305        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2306        match args.command {
2307            Some(Commands::Agent { output, .. }) => {
2308                assert_eq!(output, OutputFormat::Json);
2309            }
2310            _ => panic!("expected Agent command"),
2311        }
2312    }
2313
2314    #[cfg(feature = "agent")]
2315    #[test]
2316    fn test_shell_completions_contain_agent_commands() {
2317        use clap::CommandFactory;
2318
2319        let cmd = Args::command();
2320        let mut buf = Vec::new();
2321        clap_complete::generate(
2322            clap_complete::Shell::Bash,
2323            &mut cmd.clone(),
2324            "passless",
2325            &mut buf,
2326        );
2327        let completion = String::from_utf8(buf).unwrap();
2328
2329        for expected in [
2330            "agent-admin",
2331            "agent",
2332            "install",
2333            "browser-control",
2334            "grants",
2335            "sessions",
2336            "principals",
2337            "doctor",
2338            "capabilities",
2339            "instructions",
2340        ] {
2341            assert!(
2342                completion.contains(expected),
2343                "bash completion missing '{}'",
2344                expected
2345            );
2346        }
2347    }
2348
2349    #[cfg(feature = "agent")]
2350    #[test]
2351    fn test_shell_completions_zsh_contain_agent_commands() {
2352        use clap::CommandFactory;
2353
2354        let cmd = Args::command();
2355        let mut buf = Vec::new();
2356        clap_complete::generate(
2357            clap_complete::Shell::Zsh,
2358            &mut cmd.clone(),
2359            "passless",
2360            &mut buf,
2361        );
2362        let completion = String::from_utf8(buf).unwrap();
2363
2364        for expected in ["agent-admin", "agent", "install", "browser-control"] {
2365            assert!(
2366                completion.contains(expected),
2367                "zsh completion missing '{}'",
2368                expected
2369            );
2370        }
2371    }
2372
2373    #[cfg(feature = "agent")]
2374    #[test]
2375    fn test_config_print_includes_agent_fields() {
2376        let mut default_args = Args::parse_from(["passless"]);
2377        let config = AppConfig::from(&mut default_args.config);
2378        let toml_output = config.to_toml_with_comments();
2379
2380        assert!(
2381            toml_output.contains("backend_type"),
2382            "config print missing backend_type"
2383        );
2384        assert!(
2385            toml_output.contains("[security]"),
2386            "config print missing [security] section"
2387        );
2388        assert!(
2389            toml_output.contains("[pin]"),
2390            "config print missing [pin] section"
2391        );
2392        assert!(
2393            toml_output.contains("always_uv"),
2394            "config print missing always_uv"
2395        );
2396        assert!(
2397            toml_output.contains("notification_timeout"),
2398            "config print missing notification_timeout"
2399        );
2400    }
2401
2402    #[test]
2403    fn test_config_print_contains_passless_header() {
2404        let mut default_args = Args::parse_from(["passless"]);
2405        let config = AppConfig::from(&mut default_args.config);
2406        let toml_output = config.to_toml_with_comments();
2407
2408        assert!(toml_output.contains("Passless Configuration File"));
2409        assert!(toml_output.contains("~/.config/passless/config.toml"));
2410    }
2411
2412    #[test]
2413    fn test_config_print_contains_local_backend_section() {
2414        let mut default_args = Args::parse_from(["passless"]);
2415        let config = AppConfig::from(&mut default_args.config);
2416        let toml_output = config.to_toml_with_comments();
2417
2418        assert!(toml_output.contains("[local]"));
2419        assert!(toml_output.contains("path"));
2420    }
2421
2422    #[test]
2423    fn test_config_print_contains_pass_backend_section() {
2424        let mut default_args = Args::parse_from(["passless"]);
2425        let config = AppConfig::from(&mut default_args.config);
2426        let toml_output = config.to_toml_with_comments();
2427
2428        assert!(toml_output.contains("[pass]"));
2429        assert!(toml_output.contains("store_path"));
2430        assert!(toml_output.contains("gpg_backend"));
2431    }
2432
2433    #[test]
2434    fn test_config_print_produces_valid_toml_without_none_literals() {
2435        let mut default_args = Args::parse_from(["passless"]);
2436        let config = AppConfig::from(&mut default_args.config);
2437        let toml_output = config.to_toml_with_comments();
2438
2439        for (line_no, line) in toml_output.lines().enumerate() {
2440            let trimmed = line.trim();
2441            if trimmed.starts_with('#') || trimmed.is_empty() {
2442                continue;
2443            }
2444            assert!(
2445                !trimmed.contains("= None"),
2446                "Line {} contains invalid TOML 'None' literal: {}",
2447                line_no + 1,
2448                line
2449            );
2450        }
2451
2452        let parse_result: Result<toml::Table, _> = toml_output.parse();
2453        assert!(
2454            parse_result.is_ok(),
2455            "Generated TOML is not valid: {:?}",
2456            parse_result.err()
2457        );
2458    }
2459
2460    #[cfg(feature = "agent")]
2461    #[test]
2462    fn test_config_print_comments_out_none_option_fields() {
2463        let mut default_args = Args::parse_from(["passless"]);
2464        let config = AppConfig::from(&mut default_args.config);
2465        let toml_output = config.to_toml_with_comments();
2466
2467        assert!(
2468            toml_output.contains("# audit_path = <not set>"),
2469            "Option::None field 'audit_path' should be commented out, got:\n{}",
2470            toml_output
2471        );
2472    }
2473}