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        /// Put `--with-access-tool` in the printed Playwright entry (see `agent mcp playwright --help`)
1481        #[arg(long, requires = "print_config")]
1482        with_access_tool: bool,
1483        #[command(subcommand)]
1484        adapter: Option<McpAdapter>,
1485    },
1486    /// Run Playwright MCP with lazy access to the profile's trusted CDP browser
1487    ///
1488    /// Deprecated alias of `agent mcp playwright`, kept for one release.
1489    #[command(hide = true)]
1490    PlaywrightMcp {
1491        /// Profile to bind the Playwright session to
1492        #[arg(long, value_name = "PROFILE")]
1493        profile: String,
1494        /// Start URL to open in the managed browser
1495        #[arg(long, value_name = "URL")]
1496        url: Option<String>,
1497        /// Absolute Playwright MCP executable and arguments
1498        #[arg(last = true, required = true)]
1499        command: Vec<std::path::PathBuf>,
1500    },
1501    /// Internal: the principal-session side of `agent mcp playwright`
1502    ///
1503    /// Started by `agent mcp playwright` through the admin socket, never by hand. It holds the
1504    /// principal session's capability descriptor and answers one request on its stdin, "ensure
1505    /// the browser", with the CDP endpoint. It exits when its stdin closes.
1506    #[command(hide = true)]
1507    McpSessionBroker {
1508        /// Profile of the principal session
1509        #[arg(long, value_name = "PROFILE")]
1510        profile: String,
1511        /// Start URL to open in the managed browser
1512        #[arg(long, value_name = "URL")]
1513        url: Option<String>,
1514    },
1515    /// Ask the human for passkey access to a site before navigating there
1516    ///
1517    /// Raises the same fixed system prompt a page-triggered `request` rule would, naming only the
1518    /// site and the action, without a page: use it when a site will need passkey sign-in (or, with
1519    /// --register, registration). The profile must list the action in `pre_request_actions` and the
1520    /// live rules must resolve the site to `request`. Approval does not sign in for you: navigate
1521    /// and use the site's normal WebAuthn flow afterwards. `pending` means the human has not
1522    /// decided yet: run the same command again with the same arguments.
1523    ///
1524    /// Inside a principal session (`agent run`) it uses that session. Outside one it runs itself in
1525    /// a fresh principal session, for `authenticate` only. `--register` needs the session that owns
1526    /// the browser, because its one-use approval (10 minutes) is bound to that session.
1527    ///
1528    /// Every answer is a normal result and exits 0; read the `state` (`already_allowed`,
1529    /// `pending`, `approved`, `denied`, `expired`, `cooldown`, `rate_limited`, `not_requestable`,
1530    /// `not_enabled`, `unavailable`, `busy`).
1531    RequestAccess {
1532        /// The site's RP ID, a domain such as example.com
1533        #[arg(value_name = "RP_ID")]
1534        rp_id: String,
1535        /// Ask for a one-time registration approval instead of a sign-in grant
1536        #[arg(long)]
1537        register: bool,
1538        /// A short reason, recorded in the audit log only (sanitized, at most 200 bytes, marked
1539        /// agent-supplied). It is NEVER shown to the human: explain in your own chat instead
1540        #[arg(long, value_name = "TEXT")]
1541        note: Option<String>,
1542        /// Seconds to wait for the human's decision before answering `pending` (0 to 120)
1543        #[arg(long, value_name = "SECS", default_value_t = 30, value_parser = clap::value_parser!(u32).range(0..=120))]
1544        wait: u32,
1545        /// Print the answer as one JSON object instead of text
1546        #[arg(long)]
1547        json: bool,
1548        /// Internal: set when this command re-ran itself in a fresh principal session
1549        #[arg(long, hide = true)]
1550        fresh_session: bool,
1551    },
1552    /// Launch a detached principal session
1553    Run {
1554        /// Profile to launch
1555        #[arg(long, value_name = "PROFILE")]
1556        profile: String,
1557        /// Absolute command path and arguments
1558        #[arg(last = true, required = true)]
1559        command: Vec<std::path::PathBuf>,
1560    },
1561}
1562
1563/// An MCP server the adapters run against the managed browser.
1564#[cfg(feature = "agent")]
1565#[derive(Subcommand, Debug, Clone)]
1566pub enum McpAdapter {
1567    /// Run `npx @playwright/mcp --cdp-endpoint <url>` (the endpoint is resolved on first use)
1568    Playwright {
1569        /// npm package to run (default `@playwright/mcp`; pin a version here)
1570        #[arg(long, value_name = "SPEC")]
1571        package: Option<String>,
1572        /// npx executable (default: `npx` from PATH)
1573        #[arg(long, value_name = "PATH")]
1574        npx: Option<std::path::PathBuf>,
1575        /// Open this URL once interception is attached
1576        #[arg(long, value_name = "URL")]
1577        url: Option<String>,
1578        /// Also expose the `passless_request_access` tool, which asks the human for passkey access
1579        /// to a site before the agent navigates there (opt-in)
1580        ///
1581        /// The wrapper then relays the MCP stdio instead of handing it to Playwright MCP, adding
1582        /// that one tool to `tools/list`; every other message passes through byte for byte. The
1583        /// profile must list the action in `pre_request_actions`. The tool's note is recorded in
1584        /// the audit log only and is never shown to the human.
1585        #[arg(long)]
1586        with_access_tool: bool,
1587        /// Print a ready-to-paste MCP server entry for a client instead of running the server
1588        #[arg(long, value_enum, value_name = "CLIENT")]
1589        print_config: Option<McpConfigTarget>,
1590        /// Extra arguments for @playwright/mcp (after `--`)
1591        #[arg(last = true)]
1592        extra: Vec<String>,
1593    },
1594    /// Run `npx chrome-devtools-mcp --browserUrl <url>`
1595    ///
1596    /// The browser starts when the server starts: puppeteer asks `<browserUrl>/json/version`
1597    /// at the root of the URL and cannot send the bootstrap's bearer header, so a lazy,
1598    /// authenticated discovery endpoint is not possible.
1599    ChromeDevtools {
1600        /// npm package to run (default `chrome-devtools-mcp`; pin a version here)
1601        #[arg(long, value_name = "SPEC")]
1602        package: Option<String>,
1603        /// npx executable (default: `npx` from PATH)
1604        #[arg(long, value_name = "PATH")]
1605        npx: Option<std::path::PathBuf>,
1606        /// Open this URL once interception is attached
1607        #[arg(long, value_name = "URL")]
1608        url: Option<String>,
1609        /// Print a ready-to-paste MCP server entry for a client instead of running the server
1610        #[arg(long, value_enum, value_name = "CLIENT")]
1611        print_config: Option<McpConfigTarget>,
1612        /// Extra arguments for chrome-devtools-mcp (after `--`)
1613        #[arg(last = true)]
1614        extra: Vec<String>,
1615    },
1616    /// Rewrite plain Playwright MCP / chrome-devtools-mcp entries of a client to run through Passless
1617    ///
1618    /// Finds entries that start their own browser (`npx @playwright/mcp`, `pnpm dlx`, `bunx`,
1619    /// `yarn dlx`, a `playwright-mcp` binary, `chrome-devtools-mcp`) in the client's MCP
1620    /// configuration and rewrites each in place to `passless agent mcp playwright|chrome-devtools`,
1621    /// so the agent keeps its tools and passkeys go through the managed browser and the profile's
1622    /// rules. A file with no such entry gets a new `playwright` server that runs through Passless
1623    /// (a file that does not exist is created; a different server named `playwright` is never
1624    /// replaced). With `--user` on Claude Code, entries kept per project by `claude mcp add`
1625    /// (local scope, in `projects.<path>.mcpServers`) are rewritten too. The default is a dry run
1626    /// that prints a diff; `--yes` writes, after saving a backup.
1627    /// The profile is the global `--profile`: required unless exactly one usable profile (with
1628    /// `browser_cdp_expose = "port"`) is configured.
1629    Install {
1630        /// The MCP client whose configuration to change
1631        #[arg(long, value_enum, value_name = "CLIENT")]
1632        client: McpInstallClient,
1633        /// Change the client's user-level configuration (the default)
1634        #[arg(long, conflicts_with = "project")]
1635        user: bool,
1636        /// Change the configuration of this project directory instead
1637        #[arg(long, value_name = "DIR", conflicts_with = "user")]
1638        project: Option<std::path::PathBuf>,
1639        /// Write the change (after saving `<file>.passless-backup-<UTC timestamp>`); without it,
1640        /// print the diff only
1641        #[arg(long)]
1642        yes: bool,
1643        /// Also install or refresh the bundled `passless-agent` skill for the client
1644        #[arg(long)]
1645        skill: bool,
1646        /// The `passless` the entries run (absolute path). Default: the first `passless` on
1647        /// `PATH`, else this executable
1648        #[arg(long, value_name = "ABS")]
1649        passless_path: Option<std::path::PathBuf>,
1650        /// Write `--with-access-tool` into the Playwright entries it rewrites or adds (an entry
1651        /// that already runs through passless is not changed)
1652        #[arg(long)]
1653        with_access_tool: bool,
1654    },
1655}
1656
1657/// Which adapter `agent mcp --print-config` prints an entry for.
1658#[cfg(feature = "agent")]
1659#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1660pub enum McpAdapterKind {
1661    Playwright,
1662    ChromeDevtools,
1663}
1664
1665/// MCP clients `agent mcp install` can rewrite the configuration of.
1666#[cfg(feature = "agent")]
1667#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1668pub enum McpInstallClient {
1669    /// `opencode.json` (`mcp.servers.<name>`, or the legacy `mcp.<name>`)
1670    Opencode,
1671    /// `~/.claude.json` (`$CLAUDE_CONFIG_DIR/.claude.json`) and `.mcp.json`: `mcpServers.<name>`
1672    ClaudeCode,
1673}
1674
1675/// MCP clients `agent mcp --print-config` knows the configuration format of.
1676#[cfg(feature = "agent")]
1677#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
1678pub enum McpConfigTarget {
1679    /// `.mcp.json` / `claude mcp add-json`
1680    ClaudeCode,
1681    /// `opencode.json`
1682    Opencode,
1683    /// `.cursor/mcp.json`
1684    Cursor,
1685    /// `.vscode/mcp.json`
1686    Vscode,
1687}
1688
1689/// Agent credential actions
1690#[cfg(feature = "agent")]
1691#[derive(Subcommand, Debug, Clone)]
1692pub enum AgentCredentialAction {
1693    /// List credentials for the profile
1694    List,
1695    /// Show credential details
1696    Show {
1697        /// Credential reference (hex)
1698        #[arg(value_name = "CREDENTIAL_REF")]
1699        credential_ref: String,
1700    },
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705    use super::*;
1706
1707    #[cfg(feature = "agent")]
1708    #[test]
1709    fn test_agent_admin_install_defaults() {
1710        let args = Args::try_parse_from(["passless", "agent-admin", "install"]).unwrap();
1711        assert!(matches!(
1712            args.command,
1713            Some(Commands::AgentAdmin {
1714                action: AgentAdminAction::Install {
1715                    target: AgentSkillTarget::Auto,
1716                    scope: AgentSkillScope::User,
1717                    force: false,
1718                },
1719                ..
1720            })
1721        ));
1722    }
1723
1724    #[cfg(feature = "agent")]
1725    #[test]
1726    fn test_agent_admin_install_explicit_options() {
1727        let args = Args::try_parse_from([
1728            "passless",
1729            "agent-admin",
1730            "install",
1731            "claude",
1732            "--scope",
1733            "project",
1734            "--force",
1735        ])
1736        .unwrap();
1737        assert!(matches!(
1738            args.command,
1739            Some(Commands::AgentAdmin {
1740                action: AgentAdminAction::Install {
1741                    target: AgentSkillTarget::Claude,
1742                    scope: AgentSkillScope::Project,
1743                    force: true,
1744                },
1745                ..
1746            })
1747        ));
1748    }
1749
1750    #[test]
1751    fn test_pin_config_default_max_uv_retries() {
1752        let config = PinConfig {
1753            enforcement: PinEnforcement::Optional,
1754            min_length: 4,
1755            max_retries: 8,
1756            max_uv_retries: 8,
1757            auto_lock_timeout: 0,
1758        };
1759        assert_eq!(config.max_uv_retries, 8);
1760    }
1761
1762    #[test]
1763    fn test_pin_config_validate_success() {
1764        let config = PinConfig {
1765            enforcement: PinEnforcement::Optional,
1766            min_length: 4,
1767            max_retries: 8,
1768            max_uv_retries: 8,
1769            auto_lock_timeout: 0,
1770        };
1771        assert!(config.validate().is_ok());
1772    }
1773
1774    #[test]
1775    fn test_pin_config_validate_zero_max_uv_retries() {
1776        let config = PinConfig {
1777            enforcement: PinEnforcement::Optional,
1778            min_length: 4,
1779            max_retries: 8,
1780            max_uv_retries: 0,
1781            auto_lock_timeout: 0,
1782        };
1783        let result = config.validate();
1784        assert!(result.is_err());
1785        assert!(result.unwrap_err().to_string().contains("max_uv_retries"));
1786    }
1787
1788    #[test]
1789    fn test_pin_config_validate_zero_max_retries() {
1790        let config = PinConfig {
1791            enforcement: PinEnforcement::Optional,
1792            min_length: 4,
1793            max_retries: 0,
1794            max_uv_retries: 8,
1795            auto_lock_timeout: 0,
1796        };
1797        let result = config.validate();
1798        assert!(result.is_err());
1799        assert!(result.unwrap_err().to_string().contains("max_retries"));
1800    }
1801
1802    #[test]
1803    fn test_pin_config_validate_invalid_min_length() {
1804        let config = PinConfig {
1805            enforcement: PinEnforcement::Optional,
1806            min_length: 3,
1807            max_retries: 8,
1808            max_uv_retries: 8,
1809            auto_lock_timeout: 0,
1810        };
1811        let result = config.validate();
1812        assert!(result.is_err());
1813        assert!(result.unwrap_err().to_string().contains("min_length"));
1814    }
1815
1816    #[test]
1817    fn test_canonicalize_path_existing() {
1818        let dir = std::env::temp_dir();
1819        let canonical = BackendConfig::canonicalize_path(&dir);
1820        assert!(canonical.is_absolute());
1821        assert!(canonical.exists());
1822    }
1823
1824    #[test]
1825    fn test_canonicalize_path_nonexistent() {
1826        let base = std::env::temp_dir();
1827        let nonexistent = base.join("passless_test_nonexistent_dir_12345/sub");
1828        let canonical = BackendConfig::canonicalize_path(&nonexistent);
1829        assert!(canonical.is_absolute());
1830        assert!(canonical.starts_with(BackendConfig::canonicalize_path(&base)));
1831    }
1832
1833    #[test]
1834    fn test_canonicalize_path_symlink() {
1835        let dir = tempfile::tempdir().unwrap();
1836        let real = dir.path().join("real");
1837        std::fs::create_dir(&real).unwrap();
1838        let link = dir.path().join("link");
1839        std::os::unix::fs::symlink(&real, &link).unwrap();
1840
1841        let canonical_real = BackendConfig::canonicalize_path(&real);
1842        let canonical_link = BackendConfig::canonicalize_path(&link);
1843        assert_eq!(canonical_real, canonical_link);
1844    }
1845
1846    #[test]
1847    fn test_local_state_path_relative_and_absolute() {
1848        let dir = tempfile::tempdir_in(".").unwrap();
1849        let abs_path = std::fs::canonicalize(dir.path()).unwrap();
1850        let rel_path = dir.path().to_path_buf();
1851
1852        let backend_abs = BackendConfig::Local {
1853            path: abs_path.display().to_string(),
1854        };
1855        let backend_rel = BackendConfig::Local {
1856            path: rel_path.display().to_string(),
1857        };
1858        assert_eq!(backend_abs.state_path(), backend_rel.state_path());
1859    }
1860
1861    #[test]
1862    fn test_pass_state_path_different_subpaths() {
1863        let store = "/tmp/passless_test_store";
1864        let backend_a = BackendConfig::Pass {
1865            store_path: store.to_string(),
1866            path: "fido2".to_string(),
1867            gpg_backend: "gnupg-bin".to_string(),
1868        };
1869        let backend_b = BackendConfig::Pass {
1870            store_path: store.to_string(),
1871            path: "fido2-other".to_string(),
1872            gpg_backend: "gnupg-bin".to_string(),
1873        };
1874        assert_ne!(backend_a.state_path(), backend_b.state_path());
1875    }
1876
1877    #[test]
1878    fn test_different_local_paths_produce_different_identities() {
1879        let backend_a = BackendConfig::Local {
1880            path: "/tmp/passless_a".to_string(),
1881        };
1882        let backend_b = BackendConfig::Local {
1883            path: "/tmp/passless_b".to_string(),
1884        };
1885        assert_ne!(backend_a.state_path(), backend_b.state_path());
1886    }
1887
1888    #[cfg(feature = "agent")]
1889    #[test]
1890    fn test_agent_admin_profile_list() {
1891        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1892        assert!(matches!(
1893            args.command,
1894            Some(Commands::AgentAdmin {
1895                action: AgentAdminAction::Profile {
1896                    action: AdminProfileAction::List,
1897                },
1898                ..
1899            })
1900        ));
1901    }
1902
1903    #[cfg(feature = "agent")]
1904    #[test]
1905    fn test_agent_admin_credential_delete_without_confirm() {
1906        let args = Args::try_parse_from([
1907            "passless",
1908            "agent-admin",
1909            "credential",
1910            "delete",
1911            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1912        ])
1913        .unwrap();
1914        assert!(matches!(
1915            args.command,
1916            Some(Commands::AgentAdmin {
1917                action: AgentAdminAction::Credential {
1918                    action: AdminCredentialAction::Delete { confirm: false, .. },
1919                },
1920                ..
1921            })
1922        ));
1923    }
1924
1925    #[cfg(feature = "agent")]
1926    #[test]
1927    fn test_agent_admin_credential_delete_with_confirm() {
1928        let args = Args::try_parse_from([
1929            "passless",
1930            "agent-admin",
1931            "credential",
1932            "delete",
1933            "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
1934            "--confirm",
1935        ])
1936        .unwrap();
1937        assert!(matches!(
1938            args.command,
1939            Some(Commands::AgentAdmin {
1940                action: AgentAdminAction::Credential {
1941                    action: AdminCredentialAction::Delete { confirm: true, .. },
1942                },
1943                ..
1944            })
1945        ));
1946    }
1947
1948    #[cfg(feature = "agent")]
1949    #[test]
1950    fn test_agent_admin_shutdown_hidden() {
1951        let args =
1952            Args::try_parse_from(["passless", "agent-admin", "shutdown", "--confirm"]).unwrap();
1953        assert!(matches!(
1954            args.command,
1955            Some(Commands::AgentAdmin {
1956                action: AgentAdminAction::Shutdown { confirm: true },
1957                ..
1958            })
1959        ));
1960    }
1961
1962    #[cfg(feature = "agent")]
1963    #[test]
1964    fn test_agent_admin_output_default_json() {
1965        let args = Args::try_parse_from(["passless", "agent-admin", "profile", "list"]).unwrap();
1966        match args.command {
1967            Some(Commands::AgentAdmin { output, .. }) => {
1968                assert_eq!(output, OutputFormat::Json);
1969            }
1970            _ => panic!("expected AgentAdmin command"),
1971        }
1972    }
1973
1974    #[cfg(feature = "agent")]
1975    #[test]
1976    fn test_agent_admin_output_plain() {
1977        let args = Args::try_parse_from([
1978            "passless",
1979            "agent-admin",
1980            "--output",
1981            "plain",
1982            "profile",
1983            "list",
1984        ])
1985        .unwrap();
1986        match args.command {
1987            Some(Commands::AgentAdmin { output, .. }) => {
1988                assert_eq!(output, OutputFormat::Plain);
1989            }
1990            _ => panic!("expected AgentAdmin command"),
1991        }
1992    }
1993
1994    #[cfg(feature = "agent")]
1995    #[test]
1996    fn test_agent_doctor_parses() {
1997        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
1998        assert!(matches!(
1999            args.command,
2000            Some(Commands::Agent {
2001                action: AgentCommand::Doctor,
2002                ..
2003            })
2004        ));
2005    }
2006
2007    #[cfg(feature = "agent")]
2008    #[test]
2009    fn test_agent_request_access_parses() {
2010        let args = Args::try_parse_from([
2011            "passless",
2012            "agent",
2013            "--profile",
2014            "p",
2015            "request-access",
2016            "example.org",
2017            "--register",
2018            "--note",
2019            "why",
2020            "--wait",
2021            "120",
2022            "--json",
2023        ])
2024        .unwrap();
2025        let Some(Commands::Agent {
2026            profile,
2027            action:
2028                AgentCommand::RequestAccess {
2029                    rp_id,
2030                    register,
2031                    note,
2032                    wait,
2033                    json,
2034                    fresh_session,
2035                },
2036            ..
2037        }) = args.command
2038        else {
2039            panic!("not agent request-access");
2040        };
2041        assert_eq!(profile.as_deref(), Some("p"));
2042        assert_eq!(rp_id, "example.org");
2043        assert!(register && json && !fresh_session);
2044        assert_eq!(note.as_deref(), Some("why"));
2045        assert_eq!(wait, 120);
2046
2047        // The defaults: a sign-in request that waits 30 s.
2048        let args =
2049            Args::try_parse_from(["passless", "agent", "request-access", "example.org"]).unwrap();
2050        assert!(matches!(
2051            args.command,
2052            Some(Commands::Agent {
2053                action: AgentCommand::RequestAccess {
2054                    register: false,
2055                    note: None,
2056                    wait: 30,
2057                    json: false,
2058                    ..
2059                },
2060                ..
2061            })
2062        ));
2063        // The wait is bounded like the protocol's `wait_ms`, and the RP ID is required.
2064        assert!(
2065            Args::try_parse_from([
2066                "passless",
2067                "agent",
2068                "request-access",
2069                "a.b",
2070                "--wait",
2071                "121"
2072            ])
2073            .is_err()
2074        );
2075        assert!(Args::try_parse_from(["passless", "agent", "request-access"]).is_err());
2076    }
2077
2078    #[cfg(feature = "agent")]
2079    #[test]
2080    fn test_agent_mcp_playwright_with_access_tool_parses() {
2081        let on = Args::try_parse_from([
2082            "passless",
2083            "agent",
2084            "mcp",
2085            "playwright",
2086            "--profile",
2087            "p",
2088            "--with-access-tool",
2089        ])
2090        .unwrap();
2091        assert!(matches!(
2092            on.command,
2093            Some(Commands::Agent {
2094                action: AgentCommand::Mcp {
2095                    adapter: Some(McpAdapter::Playwright {
2096                        with_access_tool: true,
2097                        ..
2098                    }),
2099                    ..
2100                },
2101                ..
2102            })
2103        ));
2104        // Off unless asked, and only the Playwright adapter has it.
2105        let off =
2106            Args::try_parse_from(["passless", "agent", "mcp", "playwright", "--profile", "p"])
2107                .unwrap();
2108        assert!(matches!(
2109            off.command,
2110            Some(Commands::Agent {
2111                action: AgentCommand::Mcp {
2112                    adapter: Some(McpAdapter::Playwright {
2113                        with_access_tool: false,
2114                        ..
2115                    }),
2116                    ..
2117                },
2118                ..
2119            })
2120        ));
2121        assert!(
2122            Args::try_parse_from([
2123                "passless",
2124                "agent",
2125                "mcp",
2126                "chrome-devtools",
2127                "--with-access-tool"
2128            ])
2129            .is_err()
2130        );
2131        // The top-level print form takes it too, and only with --print-config.
2132        let print = Args::try_parse_from([
2133            "passless",
2134            "agent",
2135            "mcp",
2136            "--print-config",
2137            "claude-code",
2138            "--with-access-tool",
2139        ])
2140        .unwrap();
2141        assert!(matches!(
2142            print.command,
2143            Some(Commands::Agent {
2144                action: AgentCommand::Mcp {
2145                    with_access_tool: true,
2146                    ..
2147                },
2148                ..
2149            })
2150        ));
2151        assert!(Args::try_parse_from(["passless", "agent", "mcp", "--with-access-tool"]).is_err());
2152    }
2153
2154    #[cfg(feature = "agent")]
2155    #[test]
2156    fn test_agent_browser_parses() {
2157        let args = Args::try_parse_from([
2158            "passless",
2159            "agent",
2160            "--profile",
2161            "p",
2162            "browser",
2163            "--json",
2164            "--wait",
2165            "--headed",
2166        ])
2167        .unwrap();
2168        let Some(Commands::Agent {
2169            profile,
2170            action:
2171                AgentCommand::Browser {
2172                    json,
2173                    env,
2174                    wait,
2175                    headed,
2176                    url,
2177                },
2178            ..
2179        }) = args.command
2180        else {
2181            panic!("not agent browser");
2182        };
2183        assert_eq!(profile.as_deref(), Some("p"));
2184        assert!(json && wait && headed && !env && url.is_none());
2185        // `--profile` after the subcommand works too (it is global), and `--json` excludes `--env`.
2186        let args =
2187            Args::try_parse_from(["passless", "agent", "browser", "--env", "--profile", "p"])
2188                .unwrap();
2189        assert!(matches!(
2190            args.command,
2191            Some(Commands::Agent {
2192                action: AgentCommand::Browser { env: true, .. },
2193                ..
2194            })
2195        ));
2196        assert!(Args::try_parse_from(["passless", "agent", "browser", "--json", "--env"]).is_err());
2197    }
2198
2199    #[cfg(feature = "agent")]
2200    #[test]
2201    fn test_agent_mcp_parses() {
2202        let args = Args::try_parse_from([
2203            "passless",
2204            "agent",
2205            "mcp",
2206            "playwright",
2207            "--profile",
2208            "p",
2209            "--",
2210            "--isolated",
2211        ])
2212        .unwrap();
2213        let Some(Commands::Agent {
2214            action:
2215                AgentCommand::Mcp {
2216                    adapter: Some(McpAdapter::Playwright { extra, .. }),
2217                    print_config: None,
2218                    ..
2219                },
2220            profile,
2221            ..
2222        }) = args.command
2223        else {
2224            panic!("not agent mcp playwright");
2225        };
2226        assert_eq!(profile.as_deref(), Some("p"));
2227        assert_eq!(extra, ["--isolated"]);
2228
2229        let args = Args::try_parse_from(["passless", "agent", "mcp", "chrome-devtools"]).unwrap();
2230        assert!(matches!(
2231            args.command,
2232            Some(Commands::Agent {
2233                action: AgentCommand::Mcp {
2234                    adapter: Some(McpAdapter::ChromeDevtools { .. }),
2235                    ..
2236                },
2237                ..
2238            })
2239        ));
2240
2241        for (name, target) in [
2242            ("claude-code", McpConfigTarget::ClaudeCode),
2243            ("opencode", McpConfigTarget::Opencode),
2244            ("cursor", McpConfigTarget::Cursor),
2245            ("vscode", McpConfigTarget::Vscode),
2246        ] {
2247            let args = Args::try_parse_from([
2248                "passless",
2249                "agent",
2250                "--profile",
2251                "p",
2252                "mcp",
2253                "--print-config",
2254                name,
2255            ])
2256            .unwrap();
2257            assert!(matches!(
2258                args.command,
2259                Some(Commands::Agent {
2260                    action: AgentCommand::Mcp { print_config: Some(t), adapter: None, .. },
2261                    ..
2262                }) if t == target
2263            ));
2264        }
2265        assert!(
2266            Args::try_parse_from(["passless", "agent", "mcp", "--print-config", "emacs"]).is_err()
2267        );
2268        // The same flag on the adapter subcommand, with `--profile` after it.
2269        let args = Args::try_parse_from([
2270            "passless",
2271            "agent",
2272            "mcp",
2273            "playwright",
2274            "--profile",
2275            "coding",
2276            "--print-config",
2277            "claude-code",
2278        ])
2279        .unwrap();
2280        assert!(matches!(
2281            args.command,
2282            Some(Commands::Agent {
2283                profile: Some(ref profile),
2284                action: AgentCommand::Mcp {
2285                    print_config: None,
2286                    adapter: Some(McpAdapter::Playwright {
2287                        print_config: Some(McpConfigTarget::ClaudeCode),
2288                        ..
2289                    }),
2290                    ..
2291                },
2292                ..
2293            }) if profile == "coding"
2294        ));
2295        assert!(
2296            Args::try_parse_from([
2297                "passless",
2298                "agent",
2299                "mcp",
2300                "chrome-devtools",
2301                "--print-config",
2302                "opencode",
2303            ])
2304            .is_ok()
2305        );
2306        // The old name still parses (hidden alias, one release).
2307        assert!(
2308            Args::try_parse_from([
2309                "passless",
2310                "agent",
2311                "playwright-mcp",
2312                "--profile",
2313                "p",
2314                "--",
2315                "/usr/bin/npx",
2316                "x",
2317            ])
2318            .is_ok()
2319        );
2320    }
2321
2322    #[cfg(feature = "agent")]
2323    #[test]
2324    fn test_agent_mcp_install_parses() {
2325        let parse = |extra: &[&str]| {
2326            let mut argv = vec!["passless", "agent", "mcp", "install"];
2327            argv.extend_from_slice(extra);
2328            Args::try_parse_from(argv)
2329        };
2330        // The client is required; everything else is optional and the default is a dry run.
2331        assert!(parse(&[]).is_err());
2332        assert!(parse(&["--client", "emacs"]).is_err());
2333        let args = parse(&["--client", "opencode"]).unwrap();
2334        assert!(matches!(
2335            args.command,
2336            Some(Commands::Agent {
2337                profile: None,
2338                action: AgentCommand::Mcp {
2339                    adapter: Some(McpAdapter::Install {
2340                        client: McpInstallClient::Opencode,
2341                        user: false,
2342                        project: None,
2343                        yes: false,
2344                        skill: false,
2345                        passless_path: None,
2346                        with_access_tool: false,
2347                    }),
2348                    ..
2349                },
2350                ..
2351            })
2352        ));
2353        let args = parse(&[
2354            "--client",
2355            "claude-code",
2356            "--project",
2357            "/work/p",
2358            "--profile",
2359            "agent",
2360            "--yes",
2361            "--skill",
2362        ])
2363        .unwrap();
2364        match args.command {
2365            Some(Commands::Agent {
2366                profile,
2367                action:
2368                    AgentCommand::Mcp {
2369                        adapter:
2370                            Some(McpAdapter::Install {
2371                                client,
2372                                project,
2373                                yes,
2374                                skill,
2375                                ..
2376                            }),
2377                        ..
2378                    },
2379                ..
2380            }) => {
2381                assert_eq!(profile.as_deref(), Some("agent"));
2382                assert_eq!(client, McpInstallClient::ClaudeCode);
2383                assert_eq!(project, Some(std::path::PathBuf::from("/work/p")));
2384                assert!(yes && skill);
2385            }
2386            other => panic!("unexpected: {other:?}"),
2387        }
2388        // `--user` and `--project` exclude each other.
2389        assert!(parse(&["--client", "opencode", "--user", "--project", "/p"]).is_err());
2390        assert!(parse(&["--client", "opencode", "--user"]).is_ok());
2391        let args = parse(&[
2392            "--client",
2393            "opencode",
2394            "--passless-path",
2395            "/usr/bin/passless",
2396        ])
2397        .unwrap();
2398        assert!(matches!(
2399            args.command,
2400            Some(Commands::Agent {
2401                action: AgentCommand::Mcp {
2402                    adapter: Some(McpAdapter::Install { passless_path: Some(ref p), .. }),
2403                    ..
2404                },
2405                ..
2406            }) if p == std::path::Path::new("/usr/bin/passless")
2407        ));
2408    }
2409
2410    #[cfg(feature = "agent")]
2411    #[test]
2412    fn test_doctor_agents_parses() {
2413        let args = Args::try_parse_from(["passless", "doctor", "--agents", "-o", "json"]).unwrap();
2414        assert!(matches!(
2415            args.command,
2416            Some(Commands::Doctor {
2417                agents: true,
2418                output: OutputFormat::Json
2419            })
2420        ));
2421    }
2422
2423    #[cfg(feature = "agent")]
2424    #[test]
2425    fn test_agent_run_with_command() {
2426        let args = Args::try_parse_from([
2427            "passless",
2428            "agent",
2429            "run",
2430            "--profile",
2431            "myprofile",
2432            "--",
2433            "/usr/bin/test",
2434            "arg1",
2435        ])
2436        .unwrap();
2437        match args.command {
2438            Some(Commands::Agent {
2439                action: AgentCommand::Run { profile, command },
2440                ..
2441            }) => {
2442                assert_eq!(profile, "myprofile");
2443                assert_eq!(command.len(), 2);
2444            }
2445            _ => panic!("expected Agent Run command"),
2446        }
2447    }
2448
2449    #[cfg(feature = "agent")]
2450    #[test]
2451    fn test_agent_admin_grants_parse() {
2452        let args = Args::try_parse_from([
2453            "passless",
2454            "agent-admin",
2455            "grants",
2456            "revoke",
2457            "--profile",
2458            "coding",
2459            "--rp",
2460            "example.com",
2461            "--confirm",
2462        ])
2463        .unwrap();
2464        assert!(matches!(
2465            args.command,
2466            Some(Commands::AgentAdmin {
2467                action: AgentAdminAction::Grants {
2468                    action: AdminGrantsAction::Revoke {
2469                        ref profile,
2470                        ref rp_id,
2471                        action: AdminGrantAction::Authenticate,
2472                        confirm: true,
2473                    },
2474                },
2475                ..
2476            }) if profile == "coding" && rp_id == "example.com"
2477        ));
2478        let args = Args::try_parse_from([
2479            "passless",
2480            "agent-admin",
2481            "grants",
2482            "clear",
2483            "--profile",
2484            "p",
2485        ])
2486        .unwrap();
2487        assert!(matches!(
2488            args.command,
2489            Some(Commands::AgentAdmin {
2490                action: AgentAdminAction::Grants {
2491                    action: AdminGrantsAction::Clear { confirm: false, .. },
2492                },
2493                ..
2494            })
2495        ));
2496        assert!(Args::try_parse_from(["passless", "agent-admin", "grants", "list"]).is_ok());
2497    }
2498
2499    #[cfg(feature = "agent")]
2500    #[test]
2501    fn test_agent_admin_renamed_session_commands_keep_hidden_aliases() {
2502        for (spelling, expect_sessions) in [
2503            ("sessions", true),
2504            ("delegation", true),
2505            ("principals", false),
2506            ("session", false),
2507        ] {
2508            let args = Args::try_parse_from(["passless", "agent-admin", spelling, "list"]).unwrap();
2509            let is_sessions = matches!(
2510                args.command,
2511                Some(Commands::AgentAdmin {
2512                    action: AgentAdminAction::Sessions { .. },
2513                    ..
2514                })
2515            );
2516            let is_principals = matches!(
2517                args.command,
2518                Some(Commands::AgentAdmin {
2519                    action: AgentAdminAction::Principals { .. },
2520                    ..
2521                })
2522            );
2523            assert_eq!(is_sessions, expect_sessions, "{spelling}");
2524            assert_eq!(is_principals, !expect_sessions, "{spelling}");
2525        }
2526        assert!(Args::try_parse_from(["passless", "agent", "intent", "show", "x"]).is_err());
2527    }
2528
2529    #[cfg(feature = "agent")]
2530    #[test]
2531    fn test_agent_output_default_json() {
2532        let args = Args::try_parse_from(["passless", "agent", "doctor"]).unwrap();
2533        match args.command {
2534            Some(Commands::Agent { output, .. }) => {
2535                assert_eq!(output, OutputFormat::Json);
2536            }
2537            _ => panic!("expected Agent command"),
2538        }
2539    }
2540
2541    #[cfg(feature = "agent")]
2542    #[test]
2543    fn test_shell_completions_contain_agent_commands() {
2544        use clap::CommandFactory;
2545
2546        let cmd = Args::command();
2547        let mut buf = Vec::new();
2548        clap_complete::generate(
2549            clap_complete::Shell::Bash,
2550            &mut cmd.clone(),
2551            "passless",
2552            &mut buf,
2553        );
2554        let completion = String::from_utf8(buf).unwrap();
2555
2556        for expected in [
2557            "agent-admin",
2558            "agent",
2559            "install",
2560            "browser-control",
2561            "grants",
2562            "sessions",
2563            "principals",
2564            "doctor",
2565            "capabilities",
2566            "instructions",
2567        ] {
2568            assert!(
2569                completion.contains(expected),
2570                "bash completion missing '{}'",
2571                expected
2572            );
2573        }
2574    }
2575
2576    #[cfg(feature = "agent")]
2577    #[test]
2578    fn test_shell_completions_zsh_contain_agent_commands() {
2579        use clap::CommandFactory;
2580
2581        let cmd = Args::command();
2582        let mut buf = Vec::new();
2583        clap_complete::generate(
2584            clap_complete::Shell::Zsh,
2585            &mut cmd.clone(),
2586            "passless",
2587            &mut buf,
2588        );
2589        let completion = String::from_utf8(buf).unwrap();
2590
2591        for expected in ["agent-admin", "agent", "install", "browser-control"] {
2592            assert!(
2593                completion.contains(expected),
2594                "zsh completion missing '{}'",
2595                expected
2596            );
2597        }
2598    }
2599
2600    #[cfg(feature = "agent")]
2601    #[test]
2602    fn test_config_print_includes_agent_fields() {
2603        let mut default_args = Args::parse_from(["passless"]);
2604        let config = AppConfig::from(&mut default_args.config);
2605        let toml_output = config.to_toml_with_comments();
2606
2607        assert!(
2608            toml_output.contains("backend_type"),
2609            "config print missing backend_type"
2610        );
2611        assert!(
2612            toml_output.contains("[security]"),
2613            "config print missing [security] section"
2614        );
2615        assert!(
2616            toml_output.contains("[pin]"),
2617            "config print missing [pin] section"
2618        );
2619        assert!(
2620            toml_output.contains("always_uv"),
2621            "config print missing always_uv"
2622        );
2623        assert!(
2624            toml_output.contains("notification_timeout"),
2625            "config print missing notification_timeout"
2626        );
2627    }
2628
2629    #[test]
2630    fn test_config_print_contains_passless_header() {
2631        let mut default_args = Args::parse_from(["passless"]);
2632        let config = AppConfig::from(&mut default_args.config);
2633        let toml_output = config.to_toml_with_comments();
2634
2635        assert!(toml_output.contains("Passless Configuration File"));
2636        assert!(toml_output.contains("~/.config/passless/config.toml"));
2637    }
2638
2639    #[test]
2640    fn test_config_print_contains_local_backend_section() {
2641        let mut default_args = Args::parse_from(["passless"]);
2642        let config = AppConfig::from(&mut default_args.config);
2643        let toml_output = config.to_toml_with_comments();
2644
2645        assert!(toml_output.contains("[local]"));
2646        assert!(toml_output.contains("path"));
2647    }
2648
2649    #[test]
2650    fn test_config_print_contains_pass_backend_section() {
2651        let mut default_args = Args::parse_from(["passless"]);
2652        let config = AppConfig::from(&mut default_args.config);
2653        let toml_output = config.to_toml_with_comments();
2654
2655        assert!(toml_output.contains("[pass]"));
2656        assert!(toml_output.contains("store_path"));
2657        assert!(toml_output.contains("gpg_backend"));
2658    }
2659
2660    #[test]
2661    fn test_config_print_produces_valid_toml_without_none_literals() {
2662        let mut default_args = Args::parse_from(["passless"]);
2663        let config = AppConfig::from(&mut default_args.config);
2664        let toml_output = config.to_toml_with_comments();
2665
2666        for (line_no, line) in toml_output.lines().enumerate() {
2667            let trimmed = line.trim();
2668            if trimmed.starts_with('#') || trimmed.is_empty() {
2669                continue;
2670            }
2671            assert!(
2672                !trimmed.contains("= None"),
2673                "Line {} contains invalid TOML 'None' literal: {}",
2674                line_no + 1,
2675                line
2676            );
2677        }
2678
2679        let parse_result: Result<toml::Table, _> = toml_output.parse();
2680        assert!(
2681            parse_result.is_ok(),
2682            "Generated TOML is not valid: {:?}",
2683            parse_result.err()
2684        );
2685    }
2686
2687    #[cfg(feature = "agent")]
2688    #[test]
2689    fn test_config_print_comments_out_none_option_fields() {
2690        let mut default_args = Args::parse_from(["passless"]);
2691        let config = AppConfig::from(&mut default_args.config);
2692        let toml_output = config.to_toml_with_comments();
2693
2694        assert!(
2695            toml_output.contains("# audit_path = <not set>"),
2696            "Option::None field 'audit_path' should be commented out, got:\n{}",
2697            toml_output
2698        );
2699    }
2700}