From fba6e5492ab1d0a7efc2267c72732cc272cbd1c5 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 31 Oct 2026 10:23:53 +0100 Subject: [PATCH] [gen] Nickname: draw word and number once, render them for any title (NicknameParts) --- Cargo.lock | 4 +- Cargo.toml | 2 +- crates/custos-gen/src/lib.rs | 115 ++++++++++++++++++--------- crates/custos-gen/tests/mandatory.rs | 14 +++- 4 files changed, 93 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7025ad4..8e0cb1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,7 +142,7 @@ dependencies = [ [[package]] name = "custos-gen" -version = "0.1.0" +version = "0.1.1" dependencies = [ "custos-vault", "rand", @@ -153,7 +153,7 @@ dependencies = [ [[package]] name = "custos-vault" -version = "0.1.0" +version = "0.1.1" dependencies = [ "argon2", "chacha20poly1305", diff --git a/Cargo.toml b/Cargo.toml index 459ed63..5fb3ac0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.1.0" +version = "0.1.1" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-gen/src/lib.rs b/crates/custos-gen/src/lib.rs index ba7b0f9..6feeae7 100644 --- a/crates/custos-gen/src/lib.rs +++ b/crates/custos-gen/src/lib.rs @@ -284,56 +284,95 @@ fn leetify(w: &str) -> String { .collect::() } -/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}` -/// is left out together with the literal separator next to it. -pub fn nickname(title: &str, o: &NicknameOptions) -> Result { - let mut tokens = parse_template(&o.template)?; +/// The random parts of a nickname, drawn once. The title can keep changing afterwards: [`render`] +/// fills it in without drawing new words or numbers (a new web login's nickname follows its title as +/// it is typed). +/// +/// [`render`]: NicknameParts::render +#[derive(Clone, Debug)] +pub struct NicknameParts { + /// One per `{Word}` in the template, capitalised (and leetified if asked). + pub words: Vec, + /// One per `{Number}` in the template. + pub numbers: Vec, + pub entropy_bits: f64, +} + +fn word_pool(kinds: &[WordKind]) -> Vec<&'static str> { + let mut pool: Vec<&'static str> = kinds.iter().flat_map(|k| words(*k).iter().copied()).collect(); + // Overlapping lists: count each word once, so the entropy stays honest. + pool.sort_unstable(); + pool.dedup(); + pool +} + +/// Draws the words and numbers for `o.template`. +pub fn nickname_parts(o: &NicknameOptions) -> Result { + let tokens = parse_template(&o.template)?; if !(1..=4).contains(&o.digits) { return fail("the number must have 1 to 4 digits"); } - let name = normalize_name(title); - if name.is_empty() { - while let Some(i) = tokens.iter().position(|t| *t == Token::Name) { - tokens.remove(i); - if i == 0 { - if matches!(tokens.first(), Some(Token::Literal(_))) { - tokens.remove(0); - } - } else if matches!(tokens.get(i - 1), Some(Token::Literal(_))) { - tokens.remove(i - 1); - } - } - } - let mut pool: Vec<&str> = Vec::new(); - for k in &o.kinds { - if !pool.is_empty() && pool.iter().any(|w| words(*k).contains(w)) { - // Overlapping lists: keep the union without duplicates, so entropy stays honest. - pool.extend(words(*k).iter().filter(|w| !pool.contains(w)).collect::>()); - } else { - pool.extend_from_slice(words(*k)); - } - } - if pool.is_empty() && tokens.contains(&Token::Word) { - return fail("choose at least one kind of word"); - } - let mut out = String::new(); - let mut bits = 0.0; + let pool = word_pool(&o.kinds); + let mut parts = NicknameParts { words: Vec::new(), numbers: Vec::new(), entropy_bits: 0.0 }; for t in &tokens { match t { - Token::Literal(s) => out.push_str(s), - Token::Name => out.push_str(&name), Token::Word => { + if pool.is_empty() { + return fail("choose at least one kind of word"); + } let w = capitalize(pick(&pool)); - out.push_str(&if o.leet { leetify(&w) } else { w }); - bits += (pool.len() as f64).log2(); + parts.words.push(if o.leet { leetify(&w) } else { w }); + parts.entropy_bits += (pool.len() as f64).log2(); } Token::Number => { - (0..o.digits).for_each(|_| out.push(digit())); - bits += o.digits as f64 * 10f64.log2(); + parts.numbers.push((0..o.digits).map(|_| digit()).collect()); + parts.entropy_bits += o.digits as f64 * 10f64.log2(); } + Token::Literal(_) | Token::Name => {} } } - Ok(Generated { value: SecretString::new(out), entropy_bits: bits }) + Ok(parts) +} + +impl NicknameParts { + /// The nickname for `title`. With an empty (normalised) title, `{Name}` is left out together with + /// the literal separator next to it. `template` must be the one the parts were drawn for. + pub fn render(&self, title: &str, template: &str) -> Result { + let mut tokens = parse_template(template)?; + let name = normalize_name(title); + if name.is_empty() { + while let Some(i) = tokens.iter().position(|t| *t == Token::Name) { + tokens.remove(i); + if i == 0 { + if matches!(tokens.first(), Some(Token::Literal(_))) { + tokens.remove(0); + } + } else if matches!(tokens.get(i - 1), Some(Token::Literal(_))) { + tokens.remove(i - 1); + } + } + } + let (mut words, mut numbers) = (self.words.iter(), self.numbers.iter()); + let mismatch = || GenError("the template changed since its words were drawn".into()); + let mut out = String::new(); + for t in &tokens { + match t { + Token::Literal(s) => out.push_str(s), + Token::Name => out.push_str(&name), + Token::Word => out.push_str(words.next().ok_or_else(mismatch)?), + Token::Number => out.push_str(numbers.next().ok_or_else(mismatch)?), + } + } + Ok(out) + } +} + +/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}` +/// is left out together with the literal separator next to it. +pub fn nickname(title: &str, o: &NicknameOptions) -> Result { + let parts = nickname_parts(o)?; + let value = parts.render(title, &o.template)?; + Ok(Generated { value: SecretString::new(value), entropy_bits: parts.entropy_bits }) } // ---------- random, strict site, PIN ---------- diff --git a/crates/custos-gen/tests/mandatory.rs b/crates/custos-gen/tests/mandatory.rs index 32071cb..cb00f71 100644 --- a/crates/custos-gen/tests/mandatory.rs +++ b/crates/custos-gen/tests/mandatory.rs @@ -2,7 +2,7 @@ use custos_gen::{ ClassRule, EFF_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions, WordKind, - memorable, memorable_entropy, nickname, normalize_name, pin, random, strict, + memorable, memorable_entropy, nickname, nickname_parts, normalize_name, pin, random, strict, }; use regex::Regex; use std::collections::HashSet; @@ -140,6 +140,18 @@ fn nickname_options_and_entropy() { assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err()); } +#[test] +fn nickname_parts_keep_word_and_number_while_the_title_changes() { + let o = NicknameOptions::default(); + let parts = nickname_parts(&o).unwrap(); + let typed: Vec = ["", "G", "Gi", "GitHub"].iter().map(|t| parts.render(t, &o.template).unwrap()).collect(); + let tail = typed[0].clone(); // "Lantern.47": no title, so {Name} and its "." are left out + assert!(Regex::new(r"^[A-Z][a-z]+\.[0-9]{2}$").unwrap().is_match(&tail), "{tail}"); + assert_eq!(typed[1], format!("G.{tail}")); + assert_eq!(typed[3], format!("GitHub.{tail}")); + assert!(parts.render("x", "{Word}{Word}").is_err(), "a template with more tokens than parts"); +} + #[test] fn name_normalisation() { assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna");