Skip to main content

baseh/
profile.rs

1//! Profile data model and validation (spec sections 2 and 18).
2
3use std::collections::{HashMap, HashSet};
4
5use num_bigint::BigUint;
6
7use crate::basen::pow_biguint;
8use crate::error::{BasehError, ErrorCode};
9
10/// Reversible permutation configuration for a profile.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Permutation {
13    Disabled,
14    /// The only algorithm in version 1: a balanced Feistel network with
15    /// cycle walking over the domain `0 .. capacity - 1`.
16    FeistelV1 {
17        key_id: String,
18        key_bytes: Vec<u8>,
19        rounds: u32,
20    },
21}
22
23/// Codec mode (spec 2.1/19.9). Profiles that predate the mode field are
24/// fixed: the shared frozen vectors pin their byte-for-byte behaviour, so a
25/// missing mode is prepared as fixed.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum Mode {
28    /// The classic constant-width behaviour.
29    #[default]
30    Fixed,
31    /// Variable-length codes driven by id magnitude (spec 19).
32    Expandable,
33}
34
35/// Profanity handling mode (spec 18.1).
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ProfanityMode {
38    /// No filtering (the default; used by the frozen profiles).
39    None,
40    /// Vowels are stripped from both alphabets before any other
41    /// profile-derived computation.
42    NoVowels,
43    /// The encoder rejects codes containing a blocked substring.
44    Blocklist,
45}
46
47/// Optional profanity safety configuration (spec 18). It never changes
48/// decode behavior for issued codes and never changes identifier capacity
49/// accounting: blocked codes are simply never issued by the encoder.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Profanity {
52    pub mode: ProfanityMode,
53    /// Replaces the default list when present (mode Blocklist only).
54    pub words: Option<Vec<String>>,
55    /// Appended to the effective list in either case.
56    pub extra_words: Vec<String>,
57}
58
59/// Spec 22. The checksum length that applies to a generation of the given
60/// total length: `short_checksum_length` at or below `short_checksum_until`,
61/// `checksum_length` above it (and always in fixed mode). The feature is on
62/// exactly when `short_checksum_until` is non-zero; a `short_checksum_length`
63/// of 0 then means the window's generations carry no checksum symbols at all.
64pub(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
73/// Spec 18.2 default list. Deliberately small; applications extend it.
74pub const DEFAULT_BLOCKLIST: [&str; 12] = [
75    "CRAP", "TWAT", "SHAG", "DAMN", "FCK", "FUC", "SHT", "CNT", "TWT", "DCK", "AZZ", "BCH",
76];
77
78/// A baseH profile. Construct one, pass it to [`crate::Baseh::new`] and keep
79/// the resulting codec. Profiles are validated at construction per spec 2.2.
80///
81/// `aliases` is a list of `(source, target)` pairs rather than a map so that
82/// duplicate sources (including duplicates that only collide after case
83/// normalization) can be detected during validation.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct Profile {
86    pub profile_id: String,
87    /// Fixed keeps the classic constant-width behaviour; expandable gives
88    /// variable-length codes driven by id magnitude (spec 19).
89    pub mode: Mode,
90    pub body_alphabet: String,
91    /// Fixed mode only; ignored in expandable mode.
92    pub body_length: usize,
93    /// Expandable mode only; `None` selects the default of 4. When set it
94    /// must be a positive integer exceeding `checksum_length`.
95    pub min_length: Option<usize>,
96    pub checksum_alphabet: String,
97    pub checksum_length: usize,
98    /// Spec 22. Expandable mode only. The checksum width used by generations
99    /// at or below `short_checksum_until`; may be 0 (a zero-checksum window:
100    /// those generations carry no checksum symbols and no typo detection).
101    /// Without a window (`short_checksum_until` of 0) this must be 0.
102    pub short_checksum_length: usize,
103    /// Spec 22. The last generation (total length) that uses the short
104    /// checksum; `0` (the default) turns the feature off (the codebase
105    /// convention, like max_repetition). When set it must be an integer from
106    /// `min_length` through 8.
107    pub short_checksum_until: usize,
108    pub case_sensitive: bool,
109    pub separator: String,
110    /// Expandable mode only; `0` (the default) means the separator always
111    /// applies. Must be `0` in fixed mode.
112    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    /// Spec 21. Maximum allowed run of the same symbol in a raw code. `0`
118    /// (the default) disables the filter; otherwise it must be at least 3. A
119    /// value above the code length is a legal no-op.
120    pub max_repetition: usize,
121}
122
123/// A profile after validation, with derived values computed once.
124pub(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    /// Effective blocklist (spec 18.2). Empty unless the mode is Blocklist.
135    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
146/// Printable ASCII per the reference implementation (\x20 through \x7e).
147fn 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
159/// Spec 18.2: replacement semantics first, then augmentation, uppercased
160/// and deduplicated.
161fn 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
181/// Spec 18.1: vowels removed for no-vowels mode, applied after case
182/// normalization.
183fn 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
191/// Validates a profile per spec sections 2.2 and 18 and returns it with
192/// derived, pre-computed values.
193pub(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    // Spec 19.2: in expandable mode the zero ban strips 0 and O from the body
216    // alphabet silently, before any other validation, exactly like the
217    // no-vowels strip of section 18.1.
218    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        // JS parity: an explicit 0 is rejected, not coerced to the default.
233        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    // Spec 22. The short checksum is expandable-only. The window field is the
249    // switch: `short_checksum_until` of 0 turns the feature off (the codebase
250    // convention, like max_repetition), and the length field without a window
251    // is INVALID_PROFILE.
252    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        // Beyond 8 the window would swallow nearly every practical code, and
267        // long codes genuinely want two checksum symbols.
268        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    // Spec 19.3: in expandable mode the checksum alphabet is derived, "0"
294    // followed by the body alphabet in order. The configured checksumAlphabet
295    // is not consulted.
296    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    // Spec 18. no-vowels strips vowels before every downstream rule;
315    // blocklist only arms the encode-time scan.
316    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        // Derived after every body strip (zero ban, no-vowels) so all
337        // downstream rules — modulus, separator collision, alias targets —
338        // see the final alphabets.
339        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    // Spec 21: 0 disables the filter; an active filter needs a floor of 3 —
354    // banning pairs (2) would destroy roughly 9% of every generation.
355    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        // Spec 3.2: an alias must never map two distinct canonical symbols
380        // into one value. Fixed mode rejects a canonical alias source
381        // outright. In expandable mode the frozen tier (spec 17.1) carries
382        // aliases whose sources are canonical body symbols (T, N, W stay in
383        // the body alphabet); the canonical symbol wins at normalization,
384        // making those entries inert instead of destructive.
385        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        // Alias chains (and therefore cycles) are forbidden: no target may
395        // itself be a source. Checked against the full list, so detection
396        // does not depend on iteration order.
397        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        // Spec 19.5: the balanced grouping rule is a pure function of the
413        // total length, so a configurable grouping is meaningless in
414        // expandable mode.
415        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        // Fixed-mode capacity A^bodyLength. Meaningless in expandable mode.
467        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}