Compare commits

...

2 Commits

4 changed files with 93 additions and 42 deletions
Generated
+2 -2
View File
@@ -142,7 +142,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-gen" name = "custos-gen"
version = "0.1.0" version = "0.1.1"
dependencies = [ dependencies = [
"custos-vault", "custos-vault",
"rand", "rand",
@@ -153,7 +153,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-vault" name = "custos-vault"
version = "0.1.0" version = "0.1.1"
dependencies = [ dependencies = [
"argon2", "argon2",
"chacha20poly1305", "chacha20poly1305",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"] members = ["crates/*"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.1.1"
edition = "2024" edition = "2024"
license = "MPL-2.0" license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
+77 -38
View File
@@ -284,56 +284,95 @@ fn leetify(w: &str) -> String {
.collect::<String>() .collect::<String>()
} }
/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}` /// The random parts of a nickname, drawn once. The title can keep changing afterwards: [`render`]
/// is left out together with the literal separator next to it. /// fills it in without drawing new words or numbers (a new web login's nickname follows its title as
pub fn nickname(title: &str, o: &NicknameOptions) -> Result<Generated, GenError> { /// it is typed).
let mut tokens = parse_template(&o.template)?; ///
/// [`render`]: NicknameParts::render
#[derive(Clone, Debug)]
pub struct NicknameParts {
/// One per `{Word}` in the template, capitalised (and leetified if asked).
pub words: Vec<String>,
/// One per `{Number}` in the template.
pub numbers: Vec<String>,
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<NicknameParts, GenError> {
let tokens = parse_template(&o.template)?;
if !(1..=4).contains(&o.digits) { if !(1..=4).contains(&o.digits) {
return fail("the number must have 1 to 4 digits"); return fail("the number must have 1 to 4 digits");
} }
let name = normalize_name(title); let pool = word_pool(&o.kinds);
if name.is_empty() { let mut parts = NicknameParts { words: Vec::new(), numbers: Vec::new(), entropy_bits: 0.0 };
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::<Vec<_>>());
} 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;
for t in &tokens { for t in &tokens {
match t { match t {
Token::Literal(s) => out.push_str(s),
Token::Name => out.push_str(&name),
Token::Word => { Token::Word => {
if pool.is_empty() {
return fail("choose at least one kind of word");
}
let w = capitalize(pick(&pool)); let w = capitalize(pick(&pool));
out.push_str(&if o.leet { leetify(&w) } else { w }); parts.words.push(if o.leet { leetify(&w) } else { w });
bits += (pool.len() as f64).log2(); parts.entropy_bits += (pool.len() as f64).log2();
} }
Token::Number => { Token::Number => {
(0..o.digits).for_each(|_| out.push(digit())); parts.numbers.push((0..o.digits).map(|_| digit()).collect());
bits += o.digits as f64 * 10f64.log2(); 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<String, GenError> {
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<Generated, GenError> {
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 ---------- // ---------- random, strict site, PIN ----------
+13 -1
View File
@@ -2,7 +2,7 @@
use custos_gen::{ use custos_gen::{
ClassRule, EFF_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions, WordKind, 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 regex::Regex;
use std::collections::HashSet; use std::collections::HashSet;
@@ -140,6 +140,18 @@ fn nickname_options_and_entropy() {
assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err()); 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<String> = ["", "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] #[test]
fn name_normalisation() { fn name_normalisation() {
assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna"); assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna");