rusty-pwgen 0.2.0

Generate pronounceable or random passwords from the OS CSPRNG — a Rust port of Theodore Ts'o's `pwgen` with strict-compat mode, deterministic `-H` reproducible mode (SHA256 + ChaCha20), and a typed library API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! # rusty-pwgen
//!
//! A Rust port of Theodore Ts'o's `pwgen` utility: generate pronounceable or
//! random passwords from the OS CSPRNG.
//!
//! ## Quick start
//!
//! ```no_run
//! use rusty_pwgen::{PwgenBuilder, CompatibilityMode};
//!
//! let mut pwgen = PwgenBuilder::new()
//!     .length(12)
//!     .count(5)
//!     .compat(CompatibilityMode::Default)
//!     .build()?;
//!
//! let passwords: Vec<String> = pwgen.generate_n(5);
//! # Ok::<(), rusty_pwgen::Error>(())
//! ```
//!
//! ## Stability (lockstep SemVer)
//!
//! Library and binary share a single crate version. The `-H` reproducible-mode
//! contract (SHA256 + ChaCha20Rng chain) is **locked at v0.1.0** — any change
//! is a MAJOR bump.

pub mod charset;
pub mod error;
pub mod phoneme;
pub mod rng;
pub mod secure;

pub use error::Error;

/// Whether to apply Default-mode ergonomic extensions or Strict upstream parity.
///
/// # Examples
///
/// ```
/// use rusty_pwgen::CompatibilityMode;
///
/// assert_eq!(CompatibilityMode::default(), CompatibilityMode::Default);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CompatibilityMode {
    /// Default mode: ergonomic surface; rejects conflicting flag pairs at parse time.
    #[default]
    Default,
    /// Strict mode: byte-equal upstream pwgen behavior; last-wins conflict resolution.
    Strict,
}

/// Default password length per upstream pwgen.
pub const DEFAULT_LENGTH: usize = 8;

/// Default count when stdout is not a TTY (matches upstream's 1-password behavior).
pub const DEFAULT_COUNT_PIPED: usize = 1;

/// Default count multiplier per row when stdout IS a TTY (matches upstream's `20 * cols_per_row`).
pub const DEFAULT_TTY_ROWS: usize = 20;

/// Runtime engine for one pwgen invocation. Constructed via [`PwgenBuilder`].
#[non_exhaustive]
pub struct Pwgen {
    length: usize,
    count: usize,
    secure: bool,
    capitalize: bool,
    numerals: bool,
    symbols: bool,
    ambiguous_filter: bool,
    no_vowels: bool,
    remove_chars: Vec<u8>,
    rng: Box<dyn rng::RngSource + Send>,
    /// Cached active charset for secure mode.
    charset: Vec<u8>,
    #[allow(dead_code)]
    compat: CompatibilityMode,
}

impl std::fmt::Debug for Pwgen {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Pwgen")
            .field("length", &self.length)
            .field("count", &self.count)
            .field("secure", &self.secure)
            .field("capitalize", &self.capitalize)
            .field("numerals", &self.numerals)
            .field("symbols", &self.symbols)
            .field("ambiguous_filter", &self.ambiguous_filter)
            .field("no_vowels", &self.no_vowels)
            .field("compat", &self.compat)
            .finish()
    }
}

/// Builder for [`Pwgen`]. All chain methods are `#[must_use]`.
///
/// # Examples
///
/// ```
/// use rusty_pwgen::PwgenBuilder;
///
/// let pwgen = PwgenBuilder::new()
///     .length(16)
///     .secure(true)
///     .build()
///     .expect("valid configuration");
/// # let _ = pwgen;
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct PwgenBuilder {
    length: usize,
    count: usize,
    secure: bool,
    capitalize: bool,
    numerals: bool,
    symbols: bool,
    ambiguous_filter: bool,
    no_vowels: bool,
    remove_chars: Vec<u8>,
    reproducible_seed: Option<Vec<u8>>,
    compat: CompatibilityMode,
}

impl Default for PwgenBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl PwgenBuilder {
    /// Construct a new builder with upstream-pwgen defaults: length 8, count 1,
    /// pronounceable, capitals + numerals on, no symbols.
    #[must_use]
    pub fn new() -> Self {
        Self {
            length: DEFAULT_LENGTH,
            count: DEFAULT_COUNT_PIPED,
            secure: false,
            capitalize: true,
            numerals: true,
            symbols: false,
            ambiguous_filter: false,
            no_vowels: false,
            remove_chars: Vec::new(),
            reproducible_seed: None,
            compat: CompatibilityMode::Default,
        }
    }

    #[must_use]
    pub fn length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

    #[must_use]
    pub fn count(mut self, count: usize) -> Self {
        self.count = count;
        self
    }

    #[must_use]
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self
    }

    #[must_use]
    pub fn capitalize(mut self, capitalize: bool) -> Self {
        self.capitalize = capitalize;
        self
    }

    #[must_use]
    pub fn numerals(mut self, numerals: bool) -> Self {
        self.numerals = numerals;
        self
    }

    #[must_use]
    pub fn symbols(mut self, symbols: bool) -> Self {
        self.symbols = symbols;
        self
    }

    #[must_use]
    pub fn ambiguous_filter(mut self, ambiguous_filter: bool) -> Self {
        self.ambiguous_filter = ambiguous_filter;
        self
    }

    #[must_use]
    pub fn no_vowels(mut self, no_vowels: bool) -> Self {
        self.no_vowels = no_vowels;
        self
    }

    #[must_use]
    pub fn remove_chars(mut self, chars: impl Into<String>) -> Self {
        self.remove_chars = chars.into().into_bytes();
        self
    }

    #[must_use]
    pub fn reproducible_seed(mut self, seed: impl Into<Vec<u8>>) -> Self {
        self.reproducible_seed = Some(seed.into());
        self
    }

    #[must_use]
    pub fn compat(mut self, compat: CompatibilityMode) -> Self {
        self.compat = compat;
        self
    }

    /// Validate and build a [`Pwgen`].
    ///
    /// Per FR-008/FR-009: `no_vowels(true)` and a non-empty `remove_chars`
    /// each silently engage secure mode (matches upstream pwgen).
    /// Per FR-032: `length < 5` in pronounceable mode silently switches to
    /// secure mode (matches upstream).
    pub fn build(mut self) -> Result<Pwgen, Error> {
        // Silent implications per FR-008, FR-009, FR-032.
        if self.no_vowels || !self.remove_chars.is_empty() || self.length < 5 {
            self.secure = true;
        }

        let charset = charset::build(
            charset::CharSetFlags {
                capitalize: self.capitalize,
                numerals: self.numerals,
                symbols: self.symbols,
                ambiguous_filter: self.ambiguous_filter,
                no_vowels: self.no_vowels,
            },
            &self.remove_chars,
        );

        if charset.is_empty() && self.length > 0 {
            return Err(Error::InvalidBuilderConfiguration(
                "empty character set after applying filters",
            ));
        }

        let rng: Box<dyn rng::RngSource + Send> = if let Some(seed_bytes) = self.reproducible_seed {
            // Per FR-028: SHA256 of the seed bytes → 32-byte ChaCha20 seed.
            use sha2::Digest;
            let digest = sha2::Sha256::digest(&seed_bytes);
            let mut seed = [0u8; 32];
            seed.copy_from_slice(&digest);
            Box::new(rng::SeededSource::from_seed(seed))
        } else {
            Box::new(rng::OsRngSource::new())
        };

        Ok(Pwgen {
            length: self.length,
            count: self.count,
            secure: self.secure,
            capitalize: self.capitalize,
            numerals: self.numerals,
            symbols: self.symbols,
            ambiguous_filter: self.ambiguous_filter,
            no_vowels: self.no_vowels,
            remove_chars: self.remove_chars,
            rng,
            charset,
            compat: self.compat,
        })
    }
}

impl Pwgen {
    /// Generate one password.
    pub fn generate_one(&mut self) -> String {
        if self.secure {
            secure::generate(&mut *self.rng, &self.charset, self.length)
        } else {
            phoneme::generate(&mut *self.rng, self.length, self.capitalize, self.numerals)
        }
    }

    /// Generate `n` passwords. Pre-allocates the `Vec`.
    pub fn generate_n(&mut self, n: usize) -> Vec<String> {
        let mut out = Vec::with_capacity(n);
        for _ in 0..n {
            out.push(self.generate_one());
        }
        out
    }

    /// Iterator over generated passwords (streaming, no per-iteration allocation
    /// beyond the password itself).
    pub fn iter(&mut self) -> impl Iterator<Item = String> + '_ {
        std::iter::from_fn(move || Some(self.generate_one()))
    }

    /// Per-builder `count` (the count the binary would emit at default settings).
    pub fn count(&self) -> usize {
        self.count
    }

    /// Filters that affect output character set (for diagnostics + tests).
    #[allow(dead_code)]
    pub(crate) fn debug_charset(&self) -> &[u8] {
        &self.charset
    }

    /// Debug helper — not part of stable API.
    #[allow(dead_code)]
    pub(crate) fn debug_filters(&self) -> (bool, bool, bool, bool, bool, &[u8]) {
        (
            self.capitalize,
            self.numerals,
            self.symbols,
            self.ambiguous_filter,
            self.no_vowels,
            &self.remove_chars,
        )
    }
}

// CLI-only modules.
#[cfg(feature = "cli")]
pub mod cli;
#[cfg(feature = "cli")]
pub mod mode;
#[cfg(feature = "cli")]
pub mod output;
#[cfg(feature = "cli")]
pub mod seed;
#[cfg(feature = "cli")]
pub mod strict;

/// Binary entry-point helper used by `src/main.rs` and `src/bin/pwgen.rs`.
#[cfg(feature = "cli")]
pub fn run() -> std::process::ExitCode {
    use clap::Parser;
    use std::ffi::OsString;
    use std::process::ExitCode;

    let raw_argv: Vec<OsString> = std::env::args_os().collect();
    let pre_strict = strict::pre_scan_strict_flag(&raw_argv);
    let env_strict = std::env::var_os("RUSTY_PWGEN_STRICT");
    let argv0 = raw_argv.first().cloned();
    let resolved_mode = mode::resolve(pre_strict, env_strict.as_deref(), argv0.as_deref());

    if resolved_mode == CompatibilityMode::Strict {
        return strict::run(&raw_argv);
    }

    let cli_args = match cli::Cli::try_parse() {
        Ok(args) => args,
        Err(e) => {
            e.print().ok();
            return match e.kind() {
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => {
                    ExitCode::SUCCESS
                }
                _ => ExitCode::from(2),
            };
        }
    };

    // Completions subcommand.
    if let Some(cli::Subcommand::Completions { shell }) = cli_args.command {
        use clap::CommandFactory;
        let mut cmd = cli::Cli::command();
        let name = cmd.get_name().to_string();
        clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
        return ExitCode::SUCCESS;
    }

    // Resolve seed bytes if `-H` was set.
    let seed_bytes = match cli_args.sha1.as_deref() {
        Some(spec) => match seed::resolve_seed_input(spec) {
            Ok(b) => Some(b),
            Err(Error::SeedSourceUnavailable(path)) => {
                eprintln!("rusty-pwgen: seed file '{path}' not found");
                return ExitCode::from(1);
            }
            Err(e) => {
                eprintln!("rusty-pwgen: {e}");
                return ExitCode::from(1);
            }
        },
        None => None,
    };

    // FR-032 warning: pronounceable mode with length < 5 falls back to secure.
    if !cli_args.secure
        && cli_args.length < 5
        && !cli_args.no_vowels
        && cli_args.remove_chars.is_none()
    {
        eprintln!(
            "rusty-pwgen: pronounceable mode requires length >= 5; using secure mode for length {}",
            cli_args.length
        );
    }

    // FR-011 / FR-019: count resolution = explicit `-N` > positional count > TTY default.
    let resolved_count = cli_args.resolved_count(output::is_tty());

    let mut builder = PwgenBuilder::new()
        .length(cli_args.length)
        .count(resolved_count)
        .secure(cli_args.secure)
        .capitalize(cli_args.capitalize_effective())
        .numerals(cli_args.numerals_effective())
        .symbols(cli_args.symbols)
        .ambiguous_filter(cli_args.ambiguous_filter)
        .no_vowels(cli_args.no_vowels);
    if let Some(rc) = &cli_args.remove_chars {
        builder = builder.remove_chars(rc.clone());
    }
    if let Some(bytes) = seed_bytes {
        builder = builder.reproducible_seed(bytes);
    }

    let mut pwgen = match builder.build() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("rusty-pwgen: {e}");
            return ExitCode::from(1);
        }
    };

    output::emit_passwords(
        &mut pwgen,
        resolved_count,
        cli_args.one_column,
        cli_args.columnar,
    );
    ExitCode::SUCCESS
}