1use std::collections::{HashMap, HashSet};
4
5use num_bigint::BigUint;
6
7use crate::basen::pow_biguint;
8use crate::error::{BasehError, ErrorCode};
9
10#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Permutation {
13 Disabled,
14 FeistelV1 {
17 key_id: String,
18 key_bytes: Vec<u8>,
19 rounds: u32,
20 },
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum Mode {
28 #[default]
30 Fixed,
31 Expandable,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ProfanityMode {
38 None,
40 NoVowels,
43 Blocklist,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Profanity {
52 pub mode: ProfanityMode,
53 pub words: Option<Vec<String>>,
55 pub extra_words: Vec<String>,
57}
58
59pub(crate) fn effective_checksum_length(profile: &PreparedProfile, length: usize) -> usize {
65 let p = &profile.profile;
66 if p.mode == Mode::Expandable && p.short_checksum_until > 0 && length <= p.short_checksum_until
67 {
68 return p.short_checksum_length;
69 }
70 p.checksum_length
71}
72
73pub const DEFAULT_BLOCKLIST: [&str; 12] = [
75 "CRAP", "TWAT", "SHAG", "DAMN", "FCK", "FUC", "SHT", "CNT", "TWT", "DCK", "AZZ", "BCH",
76];
77
78#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct Profile {
86 pub profile_id: String,
87 pub mode: Mode,
90 pub body_alphabet: String,
91 pub body_length: usize,
93 pub min_length: Option<usize>,
96 pub checksum_alphabet: String,
97 pub checksum_length: usize,
98 pub short_checksum_length: usize,
103 pub short_checksum_until: usize,
108 pub case_sensitive: bool,
109 pub separator: String,
110 pub separator_min_length: usize,
113 pub grouping: Vec<usize>,
114 pub aliases: Vec<(char, char)>,
115 pub permutation: Permutation,
116 pub profanity: Option<Profanity>,
117 pub max_repetition: usize,
121}
122
123pub(crate) struct PreparedProfile {
125 pub profile: Profile,
126 pub min_length: usize,
127 pub separator_min_length: usize,
128 pub body_alphabet_norm: Vec<char>,
129 pub checksum_alphabet_norm: Vec<char>,
130 pub aliases_norm: HashMap<char, char>,
131 pub checksum_modulus: BigUint,
132 pub capacity: BigUint,
133 pub body_index: HashMap<char, u32>,
134 pub blocklist: Vec<String>,
136}
137
138fn fail(reason: impl Into<String>) -> BasehError {
139 BasehError::new(
140 ErrorCode::InvalidProfile,
141 format!("Invalid baseH profile: {}", reason.into()),
142 false,
143 )
144}
145
146fn is_ascii_char(c: char) -> bool {
148 c.is_ascii() && !c.is_ascii_control()
149}
150
151fn norm_char(case_sensitive: bool, c: char) -> char {
152 if case_sensitive {
153 c
154 } else {
155 c.to_ascii_uppercase()
156 }
157}
158
159fn effective_blocklist(profanity: &Profanity) -> Result<Vec<String>, BasehError> {
162 let mut list: Vec<String> = match &profanity.words {
163 Some(words) => words.clone(),
164 None => DEFAULT_BLOCKLIST.iter().map(|w| (*w).to_string()).collect(),
165 };
166 list.extend(profanity.extra_words.iter().cloned());
167 let mut out: Vec<String> = Vec::new();
168 for word in list {
169 let len = word.chars().count();
170 if !(2..=32).contains(&len) || !word.chars().all(|c| c.is_ascii_alphabetic()) {
171 return Err(fail("blocklist entries must be 2 through 32 ASCII letters"));
172 }
173 let upper = word.to_ascii_uppercase();
174 if !out.contains(&upper) {
175 out.push(upper);
176 }
177 }
178 Ok(out)
179}
180
181fn strip_vowels(alphabet_norm: &[char]) -> Vec<char> {
184 alphabet_norm
185 .iter()
186 .copied()
187 .filter(|c| !matches!(c, 'A' | 'E' | 'I' | 'O' | 'U'))
188 .collect()
189}
190
191pub(crate) fn prepare_profile(profile: Profile) -> Result<PreparedProfile, BasehError> {
194 if profile.profile_id.is_empty() {
195 return Err(fail("profileId must be non-empty"));
196 }
197 if !profile.profile_id.chars().all(is_ascii_char) {
198 return Err(fail("profileId must be ASCII"));
199 }
200
201 let case_sensitive = profile.case_sensitive;
202 let mode = profile.mode;
203
204 if profile.body_alphabet.chars().count() < 2 {
205 return Err(fail("bodyAlphabet needs at least two symbols"));
206 }
207 if !profile.body_alphabet.chars().all(is_ascii_char) {
208 return Err(fail("body alphabet symbol is not single ASCII"));
209 }
210 let mut body_norm: Vec<char> = profile
211 .body_alphabet
212 .chars()
213 .map(|c| norm_char(case_sensitive, c))
214 .collect();
215 if mode == Mode::Expandable {
219 body_norm.retain(|c| *c != '0' && *c != 'O');
220 }
221 let body_set: HashSet<char> = body_norm.iter().copied().collect();
222 if body_set.len() != body_norm.len() {
223 return Err(fail(
224 "body alphabet symbols must be unique after case normalization",
225 ));
226 }
227
228 if mode == Mode::Fixed && (profile.body_length == 0 || profile.body_length > 32) {
229 return Err(fail("bodyLength must be an integer from 1 through 32"));
230 }
231 let min_length = match profile.min_length {
232 Some(0) => return Err(fail("minLength must be a positive integer")),
234 Some(value) => value,
235 None => 4,
236 };
237 let separator_min_length = profile.separator_min_length;
238 if mode == Mode::Fixed && separator_min_length != 0 {
239 return Err(fail("separatorMinLength must be 0 in fixed mode"));
240 }
241 if profile.checksum_length > 8 {
242 return Err(fail("checksumLength must be an integer from 0 through 8"));
243 }
244 if mode == Mode::Expandable && min_length <= profile.checksum_length {
245 return Err(fail("minLength must be greater than checksumLength"));
246 }
247
248 let short_checksum_length = profile.short_checksum_length;
253 let short_checksum_until = profile.short_checksum_until;
254 if mode == Mode::Fixed {
255 if short_checksum_length != 0 || short_checksum_until != 0 {
256 return Err(fail(
257 "shortChecksumLength and shortChecksumUntil are expandable-mode only",
258 ));
259 }
260 } else if short_checksum_until != 0 {
261 if short_checksum_until < min_length {
262 return Err(fail(
263 "shortChecksumUntil must be an integer of at least minLength",
264 ));
265 }
266 if short_checksum_until > 8 {
269 return Err(fail("shortChecksumUntil must be at most 8"));
270 }
271 if short_checksum_length >= profile.checksum_length {
272 return Err(fail(
273 "shortChecksumLength must be an integer from 0 through checksumLength - 1",
274 ));
275 }
276 if min_length <= short_checksum_length {
277 return Err(fail("minLength must be greater than shortChecksumLength"));
278 }
279 } else if short_checksum_length != 0 {
280 return Err(fail("shortChecksumLength requires shortChecksumUntil"));
281 }
282
283 if mode == Mode::Fixed && profile.checksum_length > 0 {
284 if profile.checksum_alphabet.chars().count() < 2 {
285 return Err(fail(
286 "checksumAlphabet needs at least two symbols when checksumLength is positive",
287 ));
288 }
289 if !profile.checksum_alphabet.chars().all(is_ascii_char) {
290 return Err(fail("checksum alphabet symbol is not single ASCII"));
291 }
292 }
293 let mut checksum_norm: Vec<char> = if mode == Mode::Expandable {
297 Vec::new()
298 } else {
299 profile
300 .checksum_alphabet
301 .chars()
302 .map(|c| norm_char(case_sensitive, c))
303 .collect()
304 };
305 if mode == Mode::Fixed {
306 let checksum_set: HashSet<char> = checksum_norm.iter().copied().collect();
307 if checksum_set.len() != checksum_norm.len() {
308 return Err(fail(
309 "checksum alphabet symbols must be unique after case normalization",
310 ));
311 }
312 }
313
314 let profanity_mode = profile
317 .profanity
318 .as_ref()
319 .map(|p| p.mode)
320 .unwrap_or(ProfanityMode::None);
321 if profanity_mode == ProfanityMode::NoVowels {
322 body_norm = strip_vowels(&body_norm);
323 checksum_norm = strip_vowels(&checksum_norm);
324 if body_norm.len() < 2 {
325 return Err(fail(
326 "no-vowels mode leaves the body alphabet with fewer than two symbols",
327 ));
328 }
329 if mode == Mode::Fixed && profile.checksum_length > 0 && checksum_norm.len() < 2 {
330 return Err(fail(
331 "no-vowels mode leaves the checksum alphabet with fewer than two symbols",
332 ));
333 }
334 }
335 if mode == Mode::Expandable {
336 checksum_norm = std::iter::once('0')
340 .chain(body_norm.iter().copied())
341 .collect();
342 }
343 if body_norm.len() < 2 {
344 return Err(fail(
345 "body alphabet needs at least two symbols after preparation",
346 ));
347 }
348 let blocklist = match &profile.profanity {
349 Some(p) if p.mode == ProfanityMode::Blocklist => effective_blocklist(p)?,
350 _ => Vec::new(),
351 };
352
353 if profile.max_repetition == 1 || profile.max_repetition == 2 {
356 return Err(fail(
357 "maxRepetition must be 0 (off) or an integer of at least 3",
358 ));
359 }
360
361 for ch in profile.separator.chars() {
362 if body_norm.contains(&ch) || checksum_norm.contains(&ch) {
363 return Err(fail("separator must not occur in either alphabet"));
364 }
365 }
366
367 let mut aliases_norm: HashMap<char, char> = HashMap::new();
368 let canonical_set: HashSet<char> = body_norm
369 .iter()
370 .chain(checksum_norm.iter())
371 .copied()
372 .collect();
373 for (src, tgt) in &profile.aliases {
374 if !is_ascii_char(*src) || !is_ascii_char(*tgt) {
375 return Err(fail("alias entries must be single ASCII characters"));
376 }
377 let s_norm = norm_char(case_sensitive, *src);
378 let t_norm = norm_char(case_sensitive, *tgt);
379 if mode == Mode::Fixed && canonical_set.contains(&s_norm) {
386 return Err(fail("alias source is already a canonical symbol"));
387 }
388 if !canonical_set.contains(&t_norm) {
389 return Err(fail("alias target is not a canonical symbol"));
390 }
391 if aliases_norm.contains_key(&s_norm) {
392 return Err(fail("duplicate alias source after case normalization"));
393 }
394 if profile
398 .aliases
399 .iter()
400 .any(|(k, _)| norm_char(case_sensitive, *k) == t_norm)
401 {
402 return Err(fail("alias chain forbidden: target is also a source"));
403 }
404 aliases_norm.insert(s_norm, t_norm);
405 }
406
407 if profile.separator.is_empty() {
408 if !profile.grouping.is_empty() {
409 return Err(fail("grouping must be empty when separator is empty"));
410 }
411 } else if mode == Mode::Expandable {
412 if !profile.grouping.is_empty() {
416 return Err(fail("grouping must be empty in expandable mode"));
417 }
418 } else {
419 let total = profile.grouping.iter().try_fold(0usize, |acc, g| {
420 if *g == 0 {
421 None
422 } else {
423 acc.checked_add(*g)
424 }
425 });
426 let Some(total) = total else {
427 return Err(fail("group sizes must sum to bodyLength + checksumLength"));
428 };
429 if total != profile.body_length + profile.checksum_length {
430 return Err(fail("group sizes must sum to bodyLength + checksumLength"));
431 }
432 }
433
434 if let Permutation::FeistelV1 {
435 key_id,
436 key_bytes,
437 rounds,
438 } = &profile.permutation
439 {
440 if key_id.is_empty() {
441 return Err(fail("permutation requires a keyId"));
442 }
443 if key_bytes.is_empty() {
444 return Err(fail("permutation requires key material"));
445 }
446 if !(4..=16).contains(rounds) || rounds % 2 != 0 {
447 return Err(fail(
448 "Feistel rounds must be an even integer from 4 through 16",
449 ));
450 }
451 }
452
453 let modulus_base = BigUint::from(if checksum_norm.is_empty() {
454 1u64
455 } else {
456 checksum_norm.len() as u64
457 });
458 let body_index: HashMap<char, u32> = body_norm
459 .iter()
460 .enumerate()
461 .map(|(i, c)| (*c, i as u32))
462 .collect();
463
464 Ok(PreparedProfile {
465 checksum_modulus: pow_biguint(modulus_base, profile.checksum_length),
466 capacity: pow_biguint(BigUint::from(body_norm.len() as u64), profile.body_length),
468 min_length,
469 separator_min_length,
470 blocklist,
471 body_alphabet_norm: body_norm,
472 checksum_alphabet_norm: checksum_norm,
473 aliases_norm,
474 body_index,
475 profile,
476 })
477}