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