Skip to main content

vault_core/
recipe.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Password recipes (R41): a template such as `{prefix}-{list:food}-{random:12:base62}` that makes
4//! an ordinary password.
5//!
6//! A recipe is configuration, not a scheme. It runs once, at generation, and the result is stored
7//! like any other password, so redaction, history, `exec`, `render` and an older desktop keep
8//! working with no change. Nothing here reads the clock or the vault: the caller passes the date,
9//! the entry's facts, the lists and a source of randomness, so a recipe with the same template and
10//! the same draws renders the same string.
11//!
12//! The token list is data (`data/recipe-tokens.json`). Every id in it has an implementation in this
13//! file and every implementation has a descriptor; a test fails when either side is missing one.
14//!
15//! Strength is counted honestly: only the random draws add bits. A lengthener adds length and no
16//! bits, so the figure never rises above what was drawn.
17
18use hmac::{Hmac, KeyInit, Mac};
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21use sha2::{Digest, Sha256};
22use std::collections::{BTreeMap, BTreeSet};
23
24type HmacSha256 = Hmac<Sha256>;
25
26/// Label of the lengthener derivation. The salt is its SHA-256, so a new label is a new version:
27/// results of `v1` never change.
28const EXPAND_LABEL: &[u8] = b"unv/recipe/expand/v1";
29/// Salt label of `stretch` (Argon2id, m=19456 KiB, t=2, p=1). Never changes; a new cost is a `v2`.
30const STRETCH_LABEL: &str = "unv/recipe/stretch/v1";
31/// The longest single part a token may ask for.
32const MAX_PART: usize = 256;
33/// The default floor under the random bits of a result.
34pub const DEFAULT_FLOOR_BITS: f64 = 64.0;
35
36const REGISTRY: &str = include_str!("../data/recipe-tokens.json");
37const BUILTIN_LISTS: &str = include_str!("../data/recipe-lists.json");
38
39/// Tokens that produce a value.
40pub const TOKEN_IDS: &[&str] = &[
41    "random",
42    "digits",
43    "letters",
44    "hex",
45    "base32",
46    "base36",
47    "base62",
48    "symbols",
49    "pin",
50    "number",
51    "year",
52    "syllables",
53    "mask",
54    "dice",
55    "one_of",
56    "uuid_chunk",
57    "list",
58    "prefix",
59    "suffix",
60    "divider",
61    "adj",
62    "noun",
63    "verb",
64    "color",
65    "animal",
66    "food",
67    "city",
68    "country",
69    "name",
70    "element",
71    "planet",
72    "month",
73    "weekday",
74    "bip39",
75    "provider",
76    "provider_short",
77    "host",
78    "host_label",
79    "tld",
80    "url",
81    "user",
82    "email_local",
83    "project",
84    "type",
85    "id",
86    "key_id",
87    "created",
88    "now",
89    "date",
90    "counter",
91    "var",
92    "fixed",
93    "typed",
94];
95
96/// Transforms and lengtheners, used after a `|`.
97pub const TRANSFORM_IDS: &[&str] = &[
98    "lower",
99    "upper",
100    "title",
101    "sentence",
102    "camel",
103    "snake",
104    "alt",
105    "toggle",
106    "first",
107    "last",
108    "skip",
109    "take",
110    "trim",
111    "reverse",
112    "repeat",
113    "dedupe",
114    "remove",
115    "keep",
116    "replace",
117    "leet",
118    "drop_vowels",
119    "pad",
120    "initials",
121    "join",
122    "add",
123    "mul",
124    "mod",
125    "roman",
126    "spell",
127    "to_hex",
128    "hash",
129    "check_tail",
130    "ensure",
131    "class_fill",
132    "expand",
133    "expand_words",
134    "expand_groups",
135    "site_bound",
136    "family_bound",
137    "rotate_by_counter",
138    "stretch",
139    "keyed_case",
140];
141
142/// The registry as JSON (descriptors for every token): what the settings forms are drawn from.
143pub fn registry() -> Value {
144    serde_json::from_str(REGISTRY).unwrap_or(Value::Null)
145}
146
147/// The built-in lists by name.
148pub fn builtin_lists() -> BTreeMap<String, Vec<String>> {
149    let v: Value = serde_json::from_str(BUILTIN_LISTS).unwrap_or(Value::Null);
150    let mut out = BTreeMap::new();
151    if let Some(map) = v.get("lists").and_then(Value::as_object) {
152        for (k, list) in map {
153            let words = list
154                .as_array()
155                .map(|a| {
156                    a.iter()
157                        .filter_map(|w| w.as_str().map(String::from))
158                        .collect()
159                })
160                .unwrap_or_default();
161            out.insert(k.clone(), words);
162        }
163    }
164    out
165}
166
167// ── Randomness ────────────────────────────────────────────────────────────────────────────────
168
169/// A source of uniform draws. The recipe never asks for more than `below`.
170pub trait Draw {
171    fn next_u64(&mut self) -> u64;
172
173    /// A uniform number in `0..n` (rejection sampling, so no modulo bias). `n` must be above 0.
174    fn below(&mut self, n: u64) -> u64 {
175        let zone = (u64::MAX / n) * n;
176        loop {
177            let r = self.next_u64();
178            if r < zone {
179                return r % n;
180            }
181        }
182    }
183
184    /// An error the source met (an external device failing); `generate` returns it.
185    fn failure(&self) -> Option<String> {
186        None
187    }
188}
189
190/// The operating system's generator.
191pub struct SysDraw;
192
193impl Draw for SysDraw {
194    fn next_u64(&mut self) -> u64 {
195        use rand::Rng as _;
196        let mut b = [0u8; 8];
197        rand::rng().fill_bytes(&mut b);
198        u64::from_le_bytes(b)
199    }
200}
201
202/// Draws from a pool filled by `entropy::fill`, so a chosen entropy source is honoured and an
203/// external device is read once per refill and not once per character.
204pub struct PoolDraw {
205    source: crate::entropy::Source,
206    pool: Vec<u8>,
207    at: usize,
208    error: Option<String>,
209}
210
211impl PoolDraw {
212    pub fn new(source: crate::entropy::Source) -> Self {
213        Self {
214            source,
215            pool: Vec::new(),
216            at: 0,
217            error: None,
218        }
219    }
220}
221
222impl Draw for PoolDraw {
223    fn next_u64(&mut self) -> u64 {
224        if self.at + 8 > self.pool.len() {
225            let mut fresh = vec![0u8; 4096];
226            match crate::entropy::fill(&self.source, "recipe", &mut fresh) {
227                Ok(()) => {
228                    self.pool = fresh;
229                    self.at = 0;
230                }
231                Err(e) => {
232                    self.error = Some(e);
233                    return 0;
234                }
235            }
236        }
237        let mut b = [0u8; 8];
238        b.copy_from_slice(&self.pool[self.at..self.at + 8]);
239        self.at += 8;
240        u64::from_le_bytes(b)
241    }
242
243    fn failure(&self) -> Option<String> {
244        self.error.clone()
245    }
246}
247
248/// A fixed sequence for tests and goldens (xorshift64*). Never used for a real password.
249pub struct SeqDraw(pub u64);
250
251impl Draw for SeqDraw {
252    fn next_u64(&mut self) -> u64 {
253        let mut x = self.0.max(1);
254        x ^= x >> 12;
255        x ^= x << 25;
256        x ^= x >> 27;
257        self.0 = x;
258        x.wrapping_mul(0x2545_F491_4F6C_DD1D)
259    }
260}
261
262// ── The template ──────────────────────────────────────────────────────────────────────────────
263
264/// One argument of a token: literal text, or `$name` (a fact or entry datum).
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub struct Arg {
267    pub text: String,
268    pub quoted: bool,
269}
270
271/// `{kind:arg:arg|transform:arg}`, optionally marked droppable with `?N`.
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct Token {
274    pub kind: String,
275    pub args: Vec<Arg>,
276    pub pipes: Vec<(String, Vec<Arg>)>,
277    /// Priority to drop this token when a site's rules force a shorter password; highest first.
278    pub droppable: Option<u32>,
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
282pub enum Seg {
283    Lit(String),
284    Tok(Token),
285}
286
287#[derive(Debug, Clone, PartialEq, Eq)]
288pub struct Template {
289    pub segs: Vec<Seg>,
290}
291
292/// Splits on `sep` outside double quotes (a backslash escapes inside quotes).
293fn split_top(s: &str, sep: char) -> Vec<String> {
294    let mut out = vec![String::new()];
295    let (mut quoted, mut escaped) = (false, false);
296    for c in s.chars() {
297        let cur = out.last_mut().expect("never empty");
298        if quoted {
299            cur.push(c);
300            if escaped {
301                escaped = false;
302            } else if c == '\\' {
303                escaped = true;
304            } else if c == '"' {
305                quoted = false;
306            }
307        } else if c == '"' {
308            quoted = true;
309            cur.push(c);
310        } else if c == sep {
311            out.push(String::new());
312        } else {
313            cur.push(c);
314        }
315    }
316    out
317}
318
319fn parse_arg(raw: &str) -> Arg {
320    let t = raw.trim();
321    if t.len() >= 2 && t.starts_with('"') && t.ends_with('"') {
322        let mut text = String::new();
323        let mut esc = false;
324        for c in t[1..t.len() - 1].chars() {
325            if esc {
326                text.push(c);
327                esc = false;
328            } else if c == '\\' {
329                esc = true;
330            } else {
331                text.push(c);
332            }
333        }
334        return Arg { text, quoted: true };
335    }
336    Arg {
337        text: t.to_string(),
338        quoted: false,
339    }
340}
341
342fn parse_call(piece: &str) -> (String, Vec<Arg>) {
343    let parts = split_top(piece.trim(), ':');
344    let name = parts[0].trim().to_string();
345    let args = parts[1..].iter().map(|a| parse_arg(a)).collect();
346    (name, args)
347}
348
349fn parse_token(body: &str) -> Result<Token, String> {
350    let pieces = split_top(body, '|');
351    let mut head = pieces[0].trim().to_string();
352    let mut droppable = None;
353    if let Some(at) = head.rfind('?') {
354        let tail = &head[at + 1..];
355        if !tail.is_empty() && tail.bytes().all(|b| b.is_ascii_digit()) {
356            droppable = Some(
357                tail.parse::<u32>()
358                    .map_err(|_| "the drop priority is too large")?,
359            );
360            head.truncate(at);
361        }
362    }
363    let (kind, args) = parse_call(&head);
364    if kind.is_empty() {
365        return Err("a token needs a name, such as {random:12}".into());
366    }
367    if !TOKEN_IDS.contains(&kind.as_str()) {
368        return Err(format!(
369            "`{{{kind}}}` is not a token (see `unv recipe tokens` for the list)"
370        ));
371    }
372    let mut pipes = Vec::new();
373    for p in &pieces[1..] {
374        let (name, a) = parse_call(p);
375        if !TRANSFORM_IDS.contains(&name.as_str()) {
376            return Err(format!(
377                "`|{name}` is not a transform (see `unv recipe tokens` for the list)"
378            ));
379        }
380        pipes.push((name, a));
381    }
382    Ok(Token {
383        kind,
384        args,
385        pipes,
386        droppable,
387    })
388}
389
390/// Parses a template. Text outside braces is literal; `{{` and `}}` are literal braces.
391pub fn parse(template: &str) -> Result<Template, String> {
392    let chars: Vec<char> = template.chars().collect();
393    let mut segs = Vec::new();
394    let mut lit = String::new();
395    let mut i = 0;
396    while i < chars.len() {
397        let c = chars[i];
398        if c == '{' && chars.get(i + 1) == Some(&'{') {
399            lit.push('{');
400            i += 2;
401        } else if c == '}' && chars.get(i + 1) == Some(&'}') {
402            lit.push('}');
403            i += 2;
404        } else if c == '}' {
405            return Err(format!(
406                "a stray `}}` at position {}; write `}}}}` for a literal one",
407                i + 1
408            ));
409        } else if c == '{' {
410            let (mut j, mut quoted, mut esc) = (i + 1, false, false);
411            let mut body = String::new();
412            let mut closed = false;
413            while j < chars.len() {
414                let d = chars[j];
415                if quoted {
416                    if esc {
417                        esc = false;
418                    } else if d == '\\' {
419                        esc = true;
420                    } else if d == '"' {
421                        quoted = false;
422                    }
423                } else if d == '"' {
424                    quoted = true;
425                } else if d == '}' {
426                    closed = true;
427                    break;
428                }
429                body.push(d);
430                j += 1;
431            }
432            if !closed {
433                return Err(format!("the `{{` at position {} is never closed", i + 1));
434            }
435            if !lit.is_empty() {
436                segs.push(Seg::Lit(std::mem::take(&mut lit)));
437            }
438            segs.push(Seg::Tok(parse_token(&body)?));
439            i = j + 1;
440        } else {
441            lit.push(c);
442            i += 1;
443        }
444    }
445    if !lit.is_empty() {
446        segs.push(Seg::Lit(lit));
447    }
448    if segs.is_empty() {
449        return Err("the template is empty".into());
450    }
451    Ok(Template { segs })
452}
453
454// ── Context ───────────────────────────────────────────────────────────────────────────────────
455
456/// What a recipe may read: the entry's public facts, the person's facts and lists, and the date.
457#[derive(Debug, Clone, Default)]
458pub struct Ctx {
459    pub provider: String,
460    pub host: String,
461    pub url: String,
462    pub user: String,
463    pub email: String,
464    pub id: String,
465    pub key_id: String,
466    pub project: String,
467    pub secret_type: String,
468    pub family: String,
469    /// `YYYY-MM-DD` of creation; empty means "today".
470    pub created: String,
471    /// `YYYY-MM-DD` of today, passed in so nothing reads the clock here.
472    pub now: String,
473    pub counter: u64,
474    pub vars: BTreeMap<String, String>,
475    /// Your own lists; a name here wins over the built-in list of that name.
476    pub lists: BTreeMap<String, Vec<String>>,
477    /// Lists whose words are private (they hide which list and which words).
478    pub private_lists: BTreeSet<String>,
479    pub typed: Option<String>,
480    /// Values the result must never equal (current and past values of the entry).
481    pub avoid: Vec<String>,
482}
483
484// ── Values and parts ──────────────────────────────────────────────────────────────────────────
485
486#[derive(Debug, Clone)]
487struct Val {
488    text: String,
489    bits: f64,
490    private: bool,
491}
492
493impl Val {
494    fn fixed(text: impl Into<String>) -> Self {
495        Self {
496            text: text.into(),
497            bits: 0.0,
498            private: false,
499        }
500    }
501}
502
503/// One token's share of a result, for the preview table.
504#[derive(Debug, Clone, PartialEq, Serialize)]
505pub struct Part {
506    pub token: String,
507    pub kind: String,
508    pub bits: f64,
509    pub private: bool,
510}
511
512struct Args<'a> {
513    list: &'a [Arg],
514    ctx: &'a Ctx,
515    name: &'a str,
516}
517
518impl Args<'_> {
519    fn text(&self, i: usize) -> Result<Option<String>, String> {
520        let Some(a) = self.list.get(i) else {
521            return Ok(None);
522        };
523        if !a.quoted && a.text.starts_with('$') {
524            let n = &a.text[1..];
525            return self.ctx.var(n).map(Some).ok_or_else(|| {
526                format!(
527                    "`{}`: no fact named {n}; add it under Your facts",
528                    self.name
529                )
530            });
531        }
532        Ok(Some(a.text.clone()))
533    }
534
535    fn text_or(&self, i: usize, default: &str) -> Result<String, String> {
536        Ok(self
537            .text(i)?
538            .filter(|t| !t.is_empty())
539            .unwrap_or_else(|| default.into()))
540    }
541
542    fn int(&self, i: usize, default: i64) -> Result<i64, String> {
543        match self.text(i)? {
544            None => Ok(default),
545            Some(t) if t.is_empty() => Ok(default),
546            Some(t) => t
547                .trim()
548                .parse::<i64>()
549                .map_err(|_| format!("`{}`: `{t}` is not a whole number", self.name)),
550        }
551    }
552
553    fn count(&self, i: usize, default: i64) -> Result<usize, String> {
554        let n = self.int(i, default)?;
555        if n < 0 || n as usize > MAX_PART {
556            return Err(format!(
557                "`{}`: the length must be 0 to {MAX_PART}, not {n}",
558                self.name
559            ));
560        }
561        Ok(n as usize)
562    }
563}
564
565impl Ctx {
566    fn var(&self, name: &str) -> Option<String> {
567        let own = match name {
568            "provider" => Some(&self.provider),
569            "host" => Some(&self.host),
570            "user" => Some(&self.user),
571            "id" => Some(&self.id),
572            "project" => Some(&self.project),
573            _ => None,
574        };
575        match own {
576            Some(v) if !v.is_empty() => Some(v.clone()),
577            _ => self.vars.get(name).cloned(),
578        }
579    }
580
581    fn list(&self, name: &str) -> Result<(Vec<String>, bool), String> {
582        if let Some(l) = self.lists.get(name) {
583            if !l.is_empty() {
584                return Ok((l.clone(), self.private_lists.contains(name)));
585            }
586        }
587        let built = builtin_lists();
588        match built.get(name) {
589            Some(l) => Ok((l.clone(), false)),
590            None => {
591                let mut have: Vec<String> = built.keys().cloned().collect();
592                have.extend(self.lists.keys().cloned());
593                have.sort();
594                have.dedup();
595                Err(format!(
596                    "no list named {name}; lists you have: {}",
597                    have.join(", ")
598                ))
599            }
600        }
601    }
602}
603
604// ── Alphabets ─────────────────────────────────────────────────────────────────────────────────
605
606const SAFE: &str = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
607const LOWER: &str = "abcdefghijklmnopqrstuvwxyz";
608const UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
609const DIGITS: &str = "0123456789";
610const SYMBOLS: &str = "!@#$%^&*-_=+?";
611const CONSONANTS: &str = "bdfgklmnprstvz";
612const VOWELS: &str = "aeiou";
613
614fn alphabet(name: &str) -> Result<Vec<char>, String> {
615    let s: String = match name {
616        "safe" => SAFE.into(),
617        "base62" => format!("{UPPER}{LOWER}{DIGITS}"),
618        "base36" => format!("{LOWER}{DIGITS}"),
619        "base32" => "0123456789ABCDEFGHJKMNPQRSTVWXYZ".into(),
620        "hex" => "0123456789abcdef".into(),
621        "digits" => DIGITS.into(),
622        "letters" => format!("{UPPER}{LOWER}"),
623        "lower" => LOWER.into(),
624        "upper" => UPPER.into(),
625        "symbols" => SYMBOLS.into(),
626        other => other.into(),
627    };
628    let mut seen = Vec::new();
629    for c in s.chars() {
630        if !seen.contains(&c) {
631            seen.push(c);
632        }
633    }
634    if seen.len() < 2 {
635        return Err(format!(
636            "the alphabet `{name}` needs at least 2 different characters"
637        ));
638    }
639    Ok(seen)
640}
641
642fn pick(rng: &mut dyn Draw, alpha: &[char], n: usize) -> Val {
643    let text: String = (0..n)
644        .map(|_| alpha[rng.below(alpha.len() as u64) as usize])
645        .collect();
646    Val {
647        text,
648        bits: n as f64 * (alpha.len() as f64).log2(),
649        private: false,
650    }
651}
652
653// ── Dates ─────────────────────────────────────────────────────────────────────────────────────
654
655const MONTHS: [&str; 12] = [
656    "January",
657    "February",
658    "March",
659    "April",
660    "May",
661    "June",
662    "July",
663    "August",
664    "September",
665    "October",
666    "November",
667    "December",
668];
669const DOWS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
670
671fn parse_date(s: &str) -> Result<(i64, i64, i64), String> {
672    let head = s.get(..10).unwrap_or(s);
673    let mut it = head.split('-');
674    let (y, m, d) = (it.next(), it.next(), it.next());
675    let num = |x: Option<&str>| x.and_then(|v| v.parse::<i64>().ok());
676    match (num(y), num(m), num(d)) {
677        (Some(y), Some(m), Some(d)) if (1..=12).contains(&m) && (1..=31).contains(&d) && y > 0 => {
678            Ok((y, m, d))
679        }
680        _ => Err(format!("`{s}` is not a date like 2018-11-11")),
681    }
682}
683
684fn weekday(y: i64, m: i64, d: i64) -> usize {
685    const T: [i64; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
686    let y = if m < 3 { y - 1 } else { y };
687    ((y + y / 4 - y / 100 + y / 400 + T[(m - 1) as usize] + d).rem_euclid(7)) as usize
688}
689
690fn format_date(fmt: &str, date: &str) -> Result<String, String> {
691    let (y, m, d) = parse_date(date)?;
692    let mut out = String::new();
693    let mut rest = fmt;
694    'outer: while !rest.is_empty() {
695        for (tok, f) in [
696            ("Month", MONTHS[(m - 1) as usize].to_string()),
697            ("Mon", MONTHS[(m - 1) as usize][..3].to_string()),
698            ("DOW", DOWS[weekday(y, m, d)].to_string()),
699            ("YYYY", format!("{y:04}")),
700            ("YY", format!("{:02}", y % 100)),
701            ("MM", format!("{m:02}")),
702            ("DD", format!("{d:02}")),
703            ("M", m.to_string()),
704            ("D", d.to_string()),
705        ] {
706            if let Some(r) = rest.strip_prefix(tok) {
707                out.push_str(&f);
708                rest = r;
709                continue 'outer;
710            }
711        }
712        let c = rest.chars().next().expect("not empty");
713        out.push(c);
714        rest = &rest[c.len_utf8()..];
715    }
716    Ok(out)
717}
718
719// ── Tokens ────────────────────────────────────────────────────────────────────────────────────
720
721fn need(value: &str, token: &str, what: &str) -> Result<Val, String> {
722    if value.is_empty() {
723        Err(format!(
724            "`{{{token}}}` needs {what}, and this entry has none"
725        ))
726    } else {
727        Ok(Val::fixed(value))
728    }
729}
730
731fn range_arg(a: &Args, i: usize, default: &str) -> Result<(i64, i64), String> {
732    let text = a.text_or(i, default)?;
733    let (lo, hi) = text
734        .split_once("..")
735        .ok_or_else(|| format!("`{}`: write the range as MIN..MAX", a.name))?;
736    let num = |s: &str| {
737        s.trim()
738            .parse::<i64>()
739            .map_err(|_| format!("`{}`: `{s}` is not a whole number", a.name))
740    };
741    let (lo, hi) = (num(lo)?, num(hi)?);
742    if hi < lo {
743        return Err(format!("`{}`: the range {lo}..{hi} is backwards", a.name));
744    }
745    Ok((lo, hi))
746}
747
748fn eval_token(tok: &Token, ctx: &Ctx, rng: &mut dyn Draw) -> Result<Val, String> {
749    let a = Args {
750        list: &tok.args,
751        ctx,
752        name: &tok.kind,
753    };
754    let k = tok.kind.as_str();
755    let mut v = match k {
756        "random" => {
757            let n = a.count(0, 16)?;
758            pick(rng, &alphabet(&a.text_or(1, "safe")?)?, n)
759        }
760        "digits" | "pin" => pick(
761            rng,
762            &alphabet("digits")?,
763            a.count(0, if k == "pin" { 6 } else { 4 })?,
764        ),
765        "letters" => pick(rng, &alphabet("letters")?, a.count(0, 8)?),
766        "hex" | "uuid_chunk" => pick(rng, &alphabet("hex")?, a.count(0, 8)?),
767        "base32" => pick(rng, &alphabet("base32")?, a.count(0, 8)?),
768        "base36" => pick(rng, &alphabet("base36")?, a.count(0, 10)?),
769        "base62" => pick(rng, &alphabet("base62")?, a.count(0, 12)?),
770        "symbols" => {
771            let n = a.count(0, 2)?;
772            pick(rng, &alphabet(&a.text_or(1, SYMBOLS)?)?, n)
773        }
774        "number" | "year" => {
775            let (lo, hi) = range_arg(
776                &a,
777                0,
778                if k == "year" {
779                    "1990..2010"
780                } else {
781                    "100..999"
782                },
783            )?;
784            let span = (hi - lo + 1) as u64;
785            Val {
786                text: (lo + rng.below(span) as i64).to_string(),
787                bits: (span as f64).log2(),
788                private: false,
789            }
790        }
791        "syllables" => {
792            let n = a.count(0, 3)?;
793            let (c, vw): (Vec<char>, Vec<char>) =
794                (CONSONANTS.chars().collect(), VOWELS.chars().collect());
795            let mut text = String::new();
796            for _ in 0..n {
797                text.push(c[rng.below(c.len() as u64) as usize]);
798                text.push(vw[rng.below(vw.len() as u64) as usize]);
799            }
800            Val {
801                text,
802                bits: n as f64 * ((c.len() * vw.len()) as f64).log2(),
803                private: false,
804            }
805        }
806        "mask" => {
807            let mask = a.text_or(0, "CvcvCvcv99#")?;
808            let mut out = Val::fixed("");
809            for ch in mask.chars() {
810                let set: Option<String> = match ch {
811                    'c' => Some(CONSONANTS.into()),
812                    'C' => Some(CONSONANTS.to_uppercase()),
813                    'v' => Some(VOWELS.into()),
814                    'V' => Some(VOWELS.to_uppercase()),
815                    'a' => Some(LOWER.into()),
816                    'A' => Some(UPPER.into()),
817                    '9' => Some(DIGITS.into()),
818                    '#' => Some(SYMBOLS.into()),
819                    '?' => Some(SAFE.into()),
820                    _ => None,
821                };
822                match set {
823                    Some(s) => {
824                        let p = pick(rng, &s.chars().collect::<Vec<_>>(), 1);
825                        out.text.push_str(&p.text);
826                        out.bits += p.bits;
827                    }
828                    None => out.text.push(ch),
829                }
830            }
831            out
832        }
833        "dice" | "bip39" => {
834            let words = crate::type_emit::bip39_words();
835            let n = a.count(0, if k == "dice" { 4 } else { 1 })?;
836            let joiner = if k == "dice" {
837                "-".to_string()
838            } else {
839                a.text_or(1, "")?
840            };
841            let picked: Vec<&str> = (0..n)
842                .map(|_| words[rng.below(words.len() as u64) as usize])
843                .collect();
844            Val {
845                text: picked.join(&joiner),
846                bits: n as f64 * (words.len() as f64).log2(),
847                private: false,
848            }
849        }
850        "one_of" => {
851            let opts: Vec<String> = (0..tok.args.len())
852                .map(|i| a.text(i))
853                .collect::<Result<Vec<_>, _>>()?
854                .into_iter()
855                .flatten()
856                .collect();
857            if opts.len() < 2 {
858                return Err("`one_of` needs at least two options, as in {one_of:red:green}".into());
859            }
860            Val {
861                text: opts[rng.below(opts.len() as u64) as usize].clone(),
862                bits: (opts.len() as f64).log2(),
863                private: false,
864            }
865        }
866        "list" | "prefix" | "suffix" | "divider" | "adj" | "noun" | "verb" | "color" | "animal"
867        | "food" | "city" | "country" | "name" | "element" | "planet" | "month" | "weekday" => {
868            let (name, off) = if k == "list" {
869                (a.text_or(0, "food")?, 1)
870            } else {
871                (k.to_string(), 0)
872            };
873            let n = a.count(off, 1)?;
874            let joiner = a.text_or(off + 1, "")?;
875            let (words, private) = ctx.list(&name)?;
876            if words.is_empty() {
877                return Err(format!("the list {name} is empty"));
878            }
879            let picked: Vec<&str> = (0..n)
880                .map(|_| words[rng.below(words.len() as u64) as usize].as_str())
881                .collect();
882            Val {
883                text: picked.join(&joiner),
884                bits: n as f64 * (words.len() as f64).log2(),
885                private,
886            }
887        }
888        "provider" => need(&ctx.provider, k, "a provider name")?,
889        "provider_short" => {
890            let s: String = ctx
891                .provider
892                .chars()
893                .filter(|c| c.is_ascii_alphanumeric())
894                .take(12)
895                .collect::<String>()
896                .to_lowercase();
897            need(&s, k, "a provider name")?
898        }
899        "host" => need(&ctx.host, k, "an address")?,
900        "host_label" => {
901            let h = ctx.host.strip_prefix("www.").unwrap_or(&ctx.host);
902            need(h.split('.').next().unwrap_or(""), k, "an address")?
903        }
904        "tld" => need(
905            ctx.host
906                .rsplit('.')
907                .next()
908                .filter(|t| *t != ctx.host)
909                .unwrap_or(""),
910            k,
911            "an address with a domain",
912        )?,
913        "url" => need(&ctx.url, k, "an address")?,
914        "user" => need(&ctx.user, k, "a user name")?,
915        "email_local" => need(
916            ctx.email
917                .split('@')
918                .next()
919                .filter(|_| ctx.email.contains('@'))
920                .unwrap_or(""),
921            k,
922            "an email",
923        )?,
924        "project" => need(&ctx.project, k, "a project")?,
925        "type" => need(&ctx.secret_type, k, "a secret type")?,
926        "key_id" => need(&ctx.key_id, k, "a key id")?,
927        "id" => {
928            let n = a.count(0, 0)?;
929            let id = if n == 0 {
930                ctx.id.clone()
931            } else {
932                ctx.id.chars().take(n).collect()
933            };
934            need(&id, k, "an id")?
935        }
936        "created" => {
937            let date = if ctx.created.is_empty() {
938                &ctx.now
939            } else {
940                &ctx.created
941            };
942            Val::fixed(format_date(&a.text_or(0, "YYYY-MM-DD")?, date)?)
943        }
944        "now" => Val::fixed(format_date(&a.text_or(0, "YYYY-MM-DD")?, &ctx.now)?),
945        "date" => Val::fixed(format_date(
946            &a.text_or(1, "YYYY-MM-DD")?,
947            &a.text_or(0, "2018-11-11")?,
948        )?),
949        "counter" => {
950            let w = a.count(0, 1)?;
951            Val::fixed(format!("{:0w$}", ctx.counter.max(1), w = w))
952        }
953        "var" => {
954            let n = a.text_or(0, "")?;
955            let value = ctx
956                .vars
957                .get(&n)
958                .cloned()
959                .ok_or_else(|| format!("`var`: no fact named {n}; add it under Your facts"))?;
960            Val {
961                text: value,
962                bits: 0.0,
963                private: true,
964            }
965        }
966        "fixed" => Val::fixed(a.text_or(0, "")?),
967        "typed" => {
968            let t = ctx
969                .typed
970                .clone()
971                .ok_or("`typed` needs a value you type; none was given")?;
972            Val {
973                bits: estimate_bits(&t),
974                text: t,
975                private: true,
976            }
977        }
978        other => return Err(format!("`{other}` has no implementation")),
979    };
980    for (name, args) in &tok.pipes {
981        let pa = Args {
982            list: args,
983            ctx,
984            name,
985        };
986        v = apply_transform(v, name, &pa)?;
987    }
988    Ok(v)
989}
990
991/// A rough strength for text the person typed: length times the size of the character pool it
992/// draws on. An estimate, labelled as one, never a promise.
993pub fn estimate_bits(s: &str) -> f64 {
994    let pool = [
995        (s.chars().any(|c| c.is_ascii_lowercase()), 26.0),
996        (s.chars().any(|c| c.is_ascii_uppercase()), 26.0),
997        (s.chars().any(|c| c.is_ascii_digit()), 10.0),
998        (s.chars().any(|c| !c.is_ascii_alphanumeric()), 33.0),
999    ]
1000    .iter()
1001    .filter(|(on, _)| *on)
1002    .map(|(_, n)| n)
1003    .sum::<f64>();
1004    if pool < 2.0 {
1005        0.0
1006    } else {
1007        s.chars().count() as f64 * pool.log2() * 0.5
1008    }
1009}
1010
1011// ── Transforms and lengtheners ────────────────────────────────────────────────────────────────
1012
1013fn words_of(s: &str) -> Vec<String> {
1014    s.split(|c: char| !c.is_alphanumeric())
1015        .filter(|w| !w.is_empty())
1016        .map(String::from)
1017        .collect()
1018}
1019
1020fn cap(w: &str) -> String {
1021    let mut ch = w.chars();
1022    match ch.next() {
1023        Some(f) => f.to_uppercase().collect::<String>() + &ch.as_str().to_lowercase(),
1024        None => String::new(),
1025    }
1026}
1027
1028fn scale(v: &mut Val, kept: usize, of: usize) {
1029    if of > 0 && kept < of {
1030        v.bits *= kept as f64 / of as f64;
1031    }
1032}
1033
1034fn roman(mut n: i64) -> Result<String, String> {
1035    if !(1..=3999).contains(&n) {
1036        return Err("`roman` takes a number from 1 to 3999".into());
1037    }
1038    let mut out = String::new();
1039    for (v, s) in [
1040        (1000, "M"),
1041        (900, "CM"),
1042        (500, "D"),
1043        (400, "CD"),
1044        (100, "C"),
1045        (90, "XC"),
1046        (50, "L"),
1047        (40, "XL"),
1048        (10, "X"),
1049        (9, "IX"),
1050        (5, "V"),
1051        (4, "IV"),
1052        (1, "I"),
1053    ] {
1054        while n >= v {
1055            out.push_str(s);
1056            n -= v;
1057        }
1058    }
1059    Ok(out)
1060}
1061
1062fn spell(n: u64) -> String {
1063    const ONES: [&str; 20] = [
1064        "zero",
1065        "one",
1066        "two",
1067        "three",
1068        "four",
1069        "five",
1070        "six",
1071        "seven",
1072        "eight",
1073        "nine",
1074        "ten",
1075        "eleven",
1076        "twelve",
1077        "thirteen",
1078        "fourteen",
1079        "fifteen",
1080        "sixteen",
1081        "seventeen",
1082        "eighteen",
1083        "nineteen",
1084    ];
1085    const TENS: [&str; 10] = [
1086        "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
1087    ];
1088    match n {
1089        0..=19 => ONES[n as usize].into(),
1090        20..=99 => {
1091            let t = TENS[(n / 10) as usize];
1092            if n.is_multiple_of(10) {
1093                t.into()
1094            } else {
1095                format!("{t}-{}", ONES[(n % 10) as usize])
1096            }
1097        }
1098        100..=999 => {
1099            let h = format!("{} hundred", ONES[(n / 100) as usize]);
1100            if n.is_multiple_of(100) {
1101                h
1102            } else {
1103                format!("{h} {}", spell(n % 100))
1104            }
1105        }
1106        1000..=999_999 => {
1107            let t = format!("{} thousand", spell(n / 1000));
1108            if n.is_multiple_of(1000) {
1109                t
1110            } else {
1111                format!("{t} {}", spell(n % 1000))
1112            }
1113        }
1114        _ => {
1115            let m = format!("{} million", spell(n / 1_000_000));
1116            if n.is_multiple_of(1_000_000) {
1117                m
1118            } else {
1119                format!("{m} {}", spell(n % 1_000_000))
1120            }
1121        }
1122    }
1123}
1124
1125fn expand_context(name: &str, ctx: &Ctx) -> Result<String, String> {
1126    match name {
1127        "none" => Ok(String::new()),
1128        "entry" => need(&ctx.id, "expand", "an entry id").map(|v| v.text),
1129        "provider" => need(&ctx.provider.to_lowercase(), "expand", "a provider").map(|v| v.text),
1130        "family" => need(&ctx.family, "family_bound", "a site family").map(|v| v.text),
1131        "host" => need(&ctx.host, "site_bound", "an address").map(|v| v.text),
1132        "counter" => Ok(ctx.counter.max(1).to_string()),
1133        other => Err(format!(
1134            "the context `{other}` is none, entry, provider, family, host or counter"
1135        )),
1136    }
1137}
1138
1139/// HKDF-SHA256 with the fixed lengthener salt. Pinned by golden vectors: `v1` never changes.
1140fn derive(value: &str, context: &str, len: usize) -> Result<Vec<u8>, String> {
1141    let mut mac =
1142        HmacSha256::new_from_slice(&Sha256::digest(EXPAND_LABEL)).map_err(|e| e.to_string())?;
1143    mac.update(value.as_bytes());
1144    let prk = mac.finalize().into_bytes();
1145    let info = format!("v1|{context}");
1146    let (mut out, mut t, mut counter) = (Vec::with_capacity(len), Vec::<u8>::new(), 1u8);
1147    while out.len() < len {
1148        let mut mac = HmacSha256::new_from_slice(&prk).map_err(|e| e.to_string())?;
1149        mac.update(&t);
1150        mac.update(info.as_bytes());
1151        mac.update(&[counter]);
1152        t = mac.finalize().into_bytes().to_vec();
1153        out.extend_from_slice(&t);
1154        counter = counter
1155            .checked_add(1)
1156            .ok_or("the derived length is too long")?;
1157    }
1158    out.truncate(len);
1159    Ok(out)
1160}
1161
1162fn derive_chars(value: &str, context: &str, alpha: &[char], n: usize) -> Result<String, String> {
1163    let stream = derive(value, context, n * 8 + 64)?;
1164    let limit = 65536 - 65536 % alpha.len();
1165    let mut out = String::new();
1166    for pair in stream.chunks(2) {
1167        if out.chars().count() == n {
1168            break;
1169        }
1170        if pair.len() < 2 {
1171            break;
1172        }
1173        let r = u16::from_be_bytes([pair[0], pair[1]]) as usize;
1174        if r < limit {
1175            out.push(alpha[r % alpha.len()]);
1176        }
1177    }
1178    if out.chars().count() < n {
1179        return Err("the derived stream ran out; ask for fewer characters".into());
1180    }
1181    Ok(out)
1182}
1183
1184fn expanded(v: &Val, text: String, alpha_len: usize) -> Val {
1185    let n = text.chars().count();
1186    Val {
1187        bits: v.bits.min(n as f64 * (alpha_len as f64).log2()),
1188        text,
1189        private: v.private,
1190    }
1191}
1192
1193fn hash_chars(text: &str, n: usize, alpha: &[char]) -> String {
1194    let d = Sha256::digest(text.as_bytes());
1195    (0..n)
1196        .map(|i| alpha[d[i % d.len()] as usize % alpha.len()])
1197        .collect()
1198}
1199
1200fn apply_transform(mut v: Val, name: &str, a: &Args) -> Result<Val, String> {
1201    match name {
1202        "lower" => v.text = v.text.to_lowercase(),
1203        "upper" => v.text = v.text.to_uppercase(),
1204        "title" => {
1205            let mut out = String::new();
1206            let mut start = true;
1207            for c in v.text.chars() {
1208                if c.is_alphanumeric() {
1209                    out.extend(if start {
1210                        c.to_uppercase().collect::<Vec<_>>()
1211                    } else {
1212                        c.to_lowercase().collect()
1213                    });
1214                    start = false;
1215                } else {
1216                    out.push(c);
1217                    start = true;
1218                }
1219            }
1220            v.text = out;
1221        }
1222        "sentence" => v.text = cap(&v.text),
1223        "camel" => {
1224            let w = words_of(&v.text);
1225            v.text = w
1226                .iter()
1227                .enumerate()
1228                .map(|(i, w)| if i == 0 { w.to_lowercase() } else { cap(w) })
1229                .collect();
1230        }
1231        "snake" => v.text = words_of(&v.text).join("_").to_lowercase(),
1232        "alt" => {
1233            v.text = v
1234                .text
1235                .chars()
1236                .enumerate()
1237                .map(|(i, c)| {
1238                    if i % 2 == 0 {
1239                        c.to_ascii_lowercase()
1240                    } else {
1241                        c.to_ascii_uppercase()
1242                    }
1243                })
1244                .collect()
1245        }
1246        "toggle" => {
1247            v.text = v
1248                .text
1249                .chars()
1250                .map(|c| {
1251                    if c.is_ascii_lowercase() {
1252                        c.to_ascii_uppercase()
1253                    } else {
1254                        c.to_ascii_lowercase()
1255                    }
1256                })
1257                .collect()
1258        }
1259        "first" | "last" | "skip" => {
1260            let n = a.count(0, if name == "skip" { 1 } else { 4 })?;
1261            let all: Vec<char> = v.text.chars().collect();
1262            let kept: Vec<char> = match name {
1263                "first" => all.iter().copied().take(n).collect(),
1264                "last" => all
1265                    .iter()
1266                    .copied()
1267                    .skip(all.len().saturating_sub(n))
1268                    .collect(),
1269                _ => all.iter().copied().skip(n).collect(),
1270            };
1271            scale(&mut v, kept.len(), all.len());
1272            v.text = kept.into_iter().collect();
1273        }
1274        "take" => {
1275            let (lo, hi) = range_arg(a, 0, "0..4")?;
1276            let all: Vec<char> = v.text.chars().collect();
1277            let kept: Vec<char> = all
1278                .iter()
1279                .copied()
1280                .skip(lo as usize)
1281                .take((hi - lo) as usize)
1282                .collect();
1283            scale(&mut v, kept.len(), all.len());
1284            v.text = kept.into_iter().collect();
1285        }
1286        "trim" => v.text = v.text.trim().to_string(),
1287        "reverse" => v.text = v.text.chars().rev().collect(),
1288        "repeat" => {
1289            let n = a.count(0, 2)?;
1290            if v.text.len().saturating_mul(n) > MAX_PART * 4 {
1291                return Err("`repeat` would make the part too long".into());
1292            }
1293            v.text = v.text.repeat(n);
1294        }
1295        "dedupe" => {
1296            let mut out = String::new();
1297            for c in v.text.chars() {
1298                if !out.ends_with(c) {
1299                    out.push(c);
1300                }
1301            }
1302            v.text = out;
1303        }
1304        "remove" => {
1305            let set = a.text_or(0, "aeiou")?;
1306            v.text = v.text.chars().filter(|c| !set.contains(*c)).collect();
1307        }
1308        "keep" => {
1309            let class = a.text_or(0, "alnum")?;
1310            let ok: fn(char) -> bool = match class.as_str() {
1311                "digits" => |c| c.is_ascii_digit(),
1312                "letters" => |c| c.is_ascii_alphabetic(),
1313                "upper" => |c| c.is_ascii_uppercase(),
1314                "lower" => |c| c.is_ascii_lowercase(),
1315                "alnum" => |c| c.is_ascii_alphanumeric(),
1316                other => {
1317                    return Err(format!(
1318                        "`keep`: `{other}` is digits, letters, upper, lower or alnum"
1319                    ))
1320                }
1321            };
1322            let all = v.text.chars().count();
1323            v.text = v.text.chars().filter(|c| ok(*c)).collect();
1324            let now = v.text.chars().count();
1325            scale(&mut v, now, all);
1326        }
1327        "replace" => {
1328            v.text = v
1329                .text
1330                .replace(&a.text_or(0, "a")?, &a.text(1)?.unwrap_or_default())
1331        }
1332        "leet" => {
1333            let level = a.int(0, 1)?.clamp(1, 3);
1334            v.text = v
1335                .text
1336                .chars()
1337                .map(|c| match (c.to_ascii_lowercase(), level) {
1338                    ('a', _) => '4',
1339                    ('e', _) => '3',
1340                    ('o', _) => '0',
1341                    ('i', 2..) => '1',
1342                    ('s', 2..) => '5',
1343                    ('t', 3) => '7',
1344                    ('l', 3) => '1',
1345                    ('b', 3) => '8',
1346                    _ => c,
1347                })
1348                .collect()
1349        }
1350        "drop_vowels" => {
1351            v.text = v
1352                .text
1353                .chars()
1354                .filter(|c| !"aeiouAEIOU".contains(*c))
1355                .collect()
1356        }
1357        "pad" => {
1358            let n = a.count(0, 12)?;
1359            let ch = a.text_or(1, "x")?.chars().next().unwrap_or('x');
1360            let missing = n.saturating_sub(v.text.chars().count());
1361            let fill: String = std::iter::repeat_n(ch, missing).collect();
1362            v.text = if a.text_or(2, "right")? == "left" {
1363                fill + &v.text
1364            } else {
1365                v.text + &fill
1366            };
1367        }
1368        "initials" => {
1369            v.text = words_of(&v.text)
1370                .iter()
1371                .filter_map(|w| w.chars().next())
1372                .collect()
1373        }
1374        "join" => v.text = words_of(&v.text).join(&a.text_or(0, "-")?),
1375        "add" | "mul" | "mod" => {
1376            let n = v
1377                .text
1378                .trim()
1379                .parse::<i64>()
1380                .map_err(|_| format!("`{name}` needs a number, not `{}`", v.text))?;
1381            let m = a.int(
1382                0,
1383                if name == "mul" {
1384                    2
1385                } else if name == "mod" {
1386                    100
1387                } else {
1388                    1
1389                },
1390            )?;
1391            v.text = match name {
1392                "add" => n.checked_add(m),
1393                "mul" => n.checked_mul(m),
1394                _ if m == 0 => return Err("`mod` by zero".into()),
1395                _ => Some(n.rem_euclid(m)),
1396            }
1397            .ok_or("the number is too large")?
1398            .to_string();
1399        }
1400        "roman" => {
1401            v.text = roman(
1402                v.text
1403                    .trim()
1404                    .parse::<i64>()
1405                    .map_err(|_| "`roman` needs a number")?,
1406            )?
1407        }
1408        "spell" => {
1409            v.text = spell(
1410                v.text
1411                    .trim()
1412                    .parse::<u64>()
1413                    .map_err(|_| "`spell` needs a whole number")?,
1414            )
1415        }
1416        "to_hex" => v.text = hex::encode(v.text.as_bytes()),
1417        "hash" => {
1418            let n = a.count(0, 8)?;
1419            v.text = hash_chars(&v.text, n, &alphabet("hex")?);
1420            v.bits = v.bits.min(n as f64 * 4.0);
1421        }
1422        "check_tail" => {
1423            let n = a.count(0, 2)?;
1424            let tail = hash_chars(&v.text, n, &alphabet("base32")?);
1425            v.text.push_str(&tail);
1426        }
1427        "ensure" | "class_fill" => {
1428            let classes = if name == "class_fill" {
1429                "upper+lower+digit+symbol".to_string()
1430            } else {
1431                a.text_or(0, "upper+lower+digit+symbol")?
1432            };
1433            for class in classes.split('+') {
1434                let (has, set): (fn(char) -> bool, &str) = match class {
1435                    "upper" => (|c| c.is_ascii_uppercase(), UPPER),
1436                    "lower" => (|c| c.is_ascii_lowercase(), LOWER),
1437                    "digit" => (|c| c.is_ascii_digit(), DIGITS),
1438                    "symbol" => (|c| !c.is_ascii_alphanumeric(), SYMBOLS),
1439                    other => {
1440                        return Err(format!(
1441                            "`{name}`: `{other}` is upper, lower, digit or symbol"
1442                        ))
1443                    }
1444                };
1445                if !v.text.chars().any(has) {
1446                    let alpha: Vec<char> = set.chars().collect();
1447                    v.text.push(
1448                        hash_chars(&format!("{}{class}", v.text), 1, &alpha)
1449                            .chars()
1450                            .next()
1451                            .unwrap_or('x'),
1452                    );
1453                }
1454            }
1455        }
1456        "expand" | "site_bound" | "family_bound" | "rotate_by_counter" => {
1457            let n = a.count(0, 22)?;
1458            let alpha_name = a.text_or(1, "base36")?;
1459            let alpha = alphabet(&alpha_name)?;
1460            let context = match name {
1461                "site_bound" => "host".to_string(),
1462                "family_bound" => "family".to_string(),
1463                "rotate_by_counter" => "counter".to_string(),
1464                _ => a.text_or(2, "none")?,
1465            };
1466            let ctx_text = expand_context(&context, a.ctx)?;
1467            let text = derive_chars(&v.text, &ctx_text, &alpha, n)?;
1468            v = expanded(&v, text, alpha.len());
1469        }
1470        // Argon2id over the value, then the same derivation as `expand`: each guess at the result
1471        // costs a memory-hard hash. It adds length and cost, never bits (`expanded` caps them).
1472        "stretch" => {
1473            let n = a.count(0, 22)?;
1474            let alpha = alphabet(&a.text_or(1, "base36")?)?;
1475            let ctx_text = expand_context(&a.text_or(2, "none")?, a.ctx)?;
1476            let salt = Sha256::digest(format!("{STRETCH_LABEL}|{ctx_text}"));
1477            let params = argon2::Params::new(19456, 2, 1, Some(32)).map_err(|e| e.to_string())?;
1478            let mut key = [0u8; 32];
1479            argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params)
1480                .hash_password_into(v.text.as_bytes(), &salt, &mut key)
1481                .map_err(|e| e.to_string())?;
1482            let hex: String = key.iter().map(|b| format!("{b:02x}")).collect();
1483            let text = derive_chars(&hex, &ctx_text, &alpha, n)?;
1484            v = expanded(&v, text, alpha.len());
1485        }
1486        "expand_words" => {
1487            let n = a.count(0, 4)?;
1488            let words = crate::type_emit::bip39_words();
1489            let alpha: Vec<char> = (0..words.len() as u32)
1490                .filter_map(|i| char::from_u32(0x100 + i))
1491                .collect();
1492            let idx = derive_chars(
1493                &v.text,
1494                &expand_context(&a.text_or(1, "none")?, a.ctx)?,
1495                &alpha,
1496                n,
1497            )?;
1498            let picked: Vec<&str> = idx
1499                .chars()
1500                .map(|c| words[(c as u32 - 0x100) as usize])
1501                .collect();
1502            v = Val {
1503                bits: v.bits.min(n as f64 * (words.len() as f64).log2()),
1504                text: picked.join("-"),
1505                private: v.private,
1506            };
1507        }
1508        "expand_groups" => {
1509            let (groups, size) = (a.count(0, 3)?, a.count(1, 5)?);
1510            let alpha = alphabet(&a.text_or(2, "base36")?)?;
1511            let flat = derive_chars(
1512                &v.text,
1513                &expand_context(&a.text_or(3, "none")?, a.ctx)?,
1514                &alpha,
1515                groups * size,
1516            )?;
1517            let chars: Vec<char> = flat.chars().collect();
1518            let text = chars
1519                .chunks(size.max(1))
1520                .map(|c| c.iter().collect::<String>())
1521                .collect::<Vec<_>>()
1522                .join("-");
1523            v = Val {
1524                bits: v
1525                    .bits
1526                    .min((groups * size) as f64 * (alpha.len() as f64).log2()),
1527                text,
1528                private: v.private,
1529            };
1530        }
1531        "keyed_case" => {
1532            let stream = derive(&v.text, "case", v.text.len().max(1))?;
1533            v.text = v
1534                .text
1535                .chars()
1536                .zip(stream)
1537                .map(|(c, b)| {
1538                    if b & 1 == 1 {
1539                        c.to_ascii_uppercase()
1540                    } else {
1541                        c.to_ascii_lowercase()
1542                    }
1543                })
1544                .collect();
1545        }
1546        other => return Err(format!("`|{other}` has no implementation")),
1547    }
1548    Ok(v)
1549}
1550
1551// ── Options, fitting and generation ───────────────────────────────────────────────────────────
1552
1553/// Recipe-level settings, applied after the tokens render.
1554#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1555#[serde(default)]
1556pub struct Options {
1557    pub min_len: Option<usize>,
1558    pub max_len: Option<usize>,
1559    /// `fit` (default: drop droppable parts when too long, pad when too short) or `refuse`.
1560    pub policy: String,
1561    pub require_upper: usize,
1562    pub require_lower: usize,
1563    pub require_digit: usize,
1564    pub require_symbol: usize,
1565    pub avoid_ambiguous: bool,
1566    pub forbid: String,
1567    pub allow: String,
1568    /// No run of the same character longer than this (0 means no limit).
1569    pub max_run: usize,
1570    pub no_sequences: bool,
1571    pub start_letter: bool,
1572    pub no_edge_symbol: bool,
1573    /// Group the result with `chunk_sep` every this many characters (0 means none).
1574    pub chunk: usize,
1575    pub chunk_sep: String,
1576    /// The least random bits a result may have; 64 when unset.
1577    pub floor_bits: Option<f64>,
1578}
1579
1580impl Options {
1581    pub fn from_value(v: &Value) -> Result<Self, String> {
1582        if v.is_null() {
1583            return Ok(Self::default());
1584        }
1585        serde_json::from_value(v.clone()).map_err(|e| format!("the options are not valid: {e}"))
1586    }
1587
1588    pub fn floor(&self) -> f64 {
1589        self.floor_bits.unwrap_or(DEFAULT_FLOOR_BITS)
1590    }
1591}
1592
1593/// The finished password and how it was made. Nothing in it but `text` is secret.
1594#[derive(Debug, Clone, Serialize)]
1595pub struct Generated {
1596    pub text: String,
1597    /// Bits from the random draws, the figure the floor applies to.
1598    pub bits: f64,
1599    /// Bits that stay hidden even from someone who knows the scheme (private lists and facts).
1600    pub private_bits: f64,
1601    pub parts: Vec<Part>,
1602    pub dropped: Vec<String>,
1603    pub warnings: Vec<String>,
1604    /// True when no part is random and nothing is derived: a person could rebuild it from memory.
1605    pub rebuildable_from_memory: bool,
1606}
1607
1608fn render(
1609    t: &Template,
1610    ctx: &Ctx,
1611    rng: &mut dyn Draw,
1612    dropped: &BTreeSet<usize>,
1613) -> Result<(String, Vec<Part>), String> {
1614    let mut text = String::new();
1615    let mut parts = Vec::new();
1616    for (i, seg) in t.segs.iter().enumerate() {
1617        match seg {
1618            Seg::Lit(l) => text.push_str(l),
1619            Seg::Tok(tok) => {
1620                if dropped.contains(&i) {
1621                    continue;
1622                }
1623                let v = eval_token(tok, ctx, rng)?;
1624                text.push_str(&v.text);
1625                parts.push(Part {
1626                    token: tok.kind.clone(),
1627                    kind: token_kind(tok),
1628                    bits: v.bits,
1629                    private: v.private,
1630                });
1631            }
1632        }
1633    }
1634    Ok((text, parts))
1635}
1636
1637fn token_kind(tok: &Token) -> String {
1638    if tok.pipes.iter().any(|(n, _)| {
1639        matches!(
1640            n.as_str(),
1641            "expand"
1642                | "expand_words"
1643                | "expand_groups"
1644                | "site_bound"
1645                | "family_bound"
1646                | "rotate_by_counter"
1647                | "stretch"
1648                | "keyed_case"
1649        )
1650    }) {
1651        return "derive".into();
1652    }
1653    match tok.kind.as_str() {
1654        "random" | "digits" | "letters" | "hex" | "base32" | "base36" | "base62" | "symbols"
1655        | "pin" | "number" | "year" | "syllables" | "mask" | "dice" | "one_of" | "uuid_chunk" => {
1656            "random"
1657        }
1658        "list" | "prefix" | "suffix" | "divider" | "adj" | "noun" | "verb" | "color" | "animal"
1659        | "food" | "city" | "country" | "name" | "element" | "planet" | "month" | "weekday"
1660        | "bip39" => "list",
1661        "var" | "typed" | "fixed" => "typed",
1662        "created" | "now" | "date" | "counter" => "date",
1663        _ => "data",
1664    }
1665    .into()
1666}
1667
1668fn is_ambiguous(c: char) -> bool {
1669    "0O1lI".contains(c)
1670}
1671
1672fn sequence_at(chars: &[char]) -> bool {
1673    chars.windows(3).any(|w| {
1674        let (a, b, c) = (w[0] as i32, w[1] as i32, w[2] as i32);
1675        w.iter().all(|x| x.is_ascii_alphanumeric())
1676            && ((b - a == 1 && c - b == 1) || (a - b == 1 && b - c == 1))
1677    })
1678}
1679
1680/// Why `text` breaks the options, or `None` when it keeps them. Length is judged by the caller.
1681fn violation(text: &str, o: &Options) -> Option<&'static str> {
1682    let chars: Vec<char> = text.chars().collect();
1683    if !o.allow.is_empty() && chars.iter().any(|c| !o.allow.contains(*c)) {
1684        return Some("a character outside the allowed set");
1685    }
1686    if chars.iter().any(|c| o.forbid.contains(*c)) {
1687        return Some("a forbidden character");
1688    }
1689    if o.avoid_ambiguous && chars.iter().any(|c| is_ambiguous(*c)) {
1690        return Some("an ambiguous character");
1691    }
1692    let count = |f: fn(&char) -> bool| chars.iter().filter(|c| f(c)).count();
1693    if count(char::is_ascii_uppercase) < o.require_upper {
1694        return Some("too few upper-case letters");
1695    }
1696    if count(char::is_ascii_lowercase) < o.require_lower {
1697        return Some("too few lower-case letters");
1698    }
1699    if count(char::is_ascii_digit) < o.require_digit {
1700        return Some("too few digits");
1701    }
1702    if chars.iter().filter(|c| !c.is_ascii_alphanumeric()).count() < o.require_symbol {
1703        return Some("too few symbols");
1704    }
1705    if o.max_run > 0 {
1706        let mut run = 1;
1707        for w in chars.windows(2) {
1708            run = if w[0] == w[1] { run + 1 } else { 1 };
1709            if run > o.max_run {
1710                return Some("a run of one character");
1711            }
1712        }
1713    }
1714    if o.no_sequences && sequence_at(&chars) {
1715        return Some("a sequence such as abc or 123");
1716    }
1717    if o.start_letter && !chars.first().is_some_and(|c| c.is_alphabetic()) {
1718        return Some("it does not start with a letter");
1719    }
1720    if o.no_edge_symbol
1721        && (chars.first().is_some_and(|c| !c.is_alphanumeric())
1722            || chars.last().is_some_and(|c| !c.is_alphanumeric()))
1723    {
1724        return Some("a symbol at the start or end");
1725    }
1726    None
1727}
1728
1729fn chunked(text: &str, o: &Options) -> String {
1730    if o.chunk == 0 {
1731        return text.to_string();
1732    }
1733    let sep = if o.chunk_sep.is_empty() {
1734        "-"
1735    } else {
1736        &o.chunk_sep
1737    };
1738    text.chars()
1739        .collect::<Vec<_>>()
1740        .chunks(o.chunk)
1741        .map(|c| c.iter().collect::<String>())
1742        .collect::<Vec<_>>()
1743        .join(sep)
1744}
1745
1746/// Makes a password from `t`. The random draws come from `rng`; everything else from `ctx`.
1747///
1748/// Constraints are met by rejection sampling, so every accepted draw stays uniform. A droppable
1749/// token is removed (highest priority number first) when a maximum length cannot otherwise be met.
1750/// If the random bits fall below the floor, nothing is generated: a hostile page that declares a
1751/// short maximum cannot steer the result to a weak password.
1752pub fn generate(
1753    t: &Template,
1754    o: &Options,
1755    ctx: &Ctx,
1756    rng: &mut dyn Draw,
1757) -> Result<Generated, String> {
1758    let mut droppable: Vec<(u32, usize)> = t
1759        .segs
1760        .iter()
1761        .enumerate()
1762        .filter_map(|(i, s)| match s {
1763            Seg::Tok(tok) => tok.droppable.map(|p| (p, i)),
1764            Seg::Lit(_) => None,
1765        })
1766        .collect();
1767    droppable.sort_by(|a, b| b.cmp(a));
1768    let mut dropped: BTreeSet<usize> = BTreeSet::new();
1769    let refuse = o.policy == "refuse";
1770    let mut last = "the constraints";
1771    for _ in 0..=droppable.len() {
1772        let mut too_long = false;
1773        for _ in 0..500 {
1774            let (text, mut parts) = render(t, ctx, rng, &dropped)?;
1775            if let Some(e) = rng.failure() {
1776                return Err(e);
1777            }
1778            let mut text = text;
1779            let mut warnings = Vec::new();
1780            if let Some(min) = o.min_len {
1781                if text.chars().count() < min {
1782                    if refuse {
1783                        return Err(format!(
1784                            "the recipe makes {} characters, below the minimum of {min}",
1785                            text.chars().count()
1786                        ));
1787                    }
1788                    let extra = pick(rng, &alphabet("safe")?, min - text.chars().count());
1789                    text.push_str(&extra.text);
1790                    parts.push(Part {
1791                        token: "pad".into(),
1792                        kind: "random".into(),
1793                        bits: extra.bits,
1794                        private: false,
1795                    });
1796                    warnings.push(format!(
1797                        "padded with {} random characters to reach the minimum of {min}",
1798                        extra.text.chars().count()
1799                    ));
1800                }
1801            }
1802            if let Some(why) = violation(&text, o) {
1803                last = why;
1804                continue;
1805            }
1806            let shown = chunked(&text, o);
1807            if let Some(max) = o.max_len {
1808                if shown.chars().count() > max {
1809                    too_long = true;
1810                    break;
1811                }
1812            }
1813            if ctx.avoid.contains(&shown) {
1814                last = "a value this entry already used";
1815                continue;
1816            }
1817            let bits: f64 = parts.iter().map(|p| p.bits).sum();
1818            if bits + 1e-9 < o.floor() {
1819                return Err(format!(
1820                    "cannot fit: the random parts give {bits:.0} bits, below the floor of {:.0}",
1821                    o.floor()
1822                ));
1823            }
1824            let names: Vec<String> = dropped
1825                .iter()
1826                .filter_map(|i| match &t.segs[*i] {
1827                    Seg::Tok(k) => Some(k.kind.clone()),
1828                    Seg::Lit(_) => None,
1829                })
1830                .collect();
1831            let expands = parts.iter().any(|p| p.kind == "derive");
1832            if parts
1833                .iter()
1834                .any(|p| p.kind == "list" && p.bits > 0.0 && p.bits < 6.0)
1835            {
1836                warnings.push(
1837                    "a list pick adds under 6 bits; a longer list or more picks is stronger".into(),
1838                );
1839            }
1840            let private_bits = parts.iter().filter(|p| p.private).map(|p| p.bits).sum();
1841            return Ok(Generated {
1842                text: shown,
1843                bits,
1844                private_bits,
1845                dropped: names,
1846                warnings,
1847                rebuildable_from_memory: bits == 0.0 && !expands,
1848                parts,
1849            });
1850        }
1851        if !too_long {
1852            return Err(format!("cannot fit: no result without {last} in 500 tries"));
1853        }
1854        if refuse {
1855            return Err(
1856                "cannot fit: the recipe is longer than the maximum and the policy is refuse".into(),
1857            );
1858        }
1859        match droppable.first().copied() {
1860            Some((_, i)) => {
1861                droppable.remove(0);
1862                dropped.insert(i);
1863            }
1864            None => {
1865                return Err("cannot fit: the recipe is longer than the maximum and has no droppable part (mark one with ?1, as in {suffix?1})".into())
1866            }
1867        }
1868    }
1869    Err("cannot fit: dropping every droppable part is still too long".into())
1870}
1871
1872/// Parses `template` and generates in one call.
1873pub fn make(
1874    template: &str,
1875    o: &Options,
1876    ctx: &Ctx,
1877    rng: &mut dyn Draw,
1878) -> Result<Generated, String> {
1879    generate(&parse(template)?, o, ctx, rng)
1880}
1881
1882/// The random bits a template would give, without drawing: the strength figure for the editor.
1883/// Errors from missing facts surface here too, so the editor shows them while the person types.
1884pub fn analyse(template: &str, o: &Options, ctx: &Ctx) -> Result<Generated, String> {
1885    let mut o = o.clone();
1886    o.max_len = None;
1887    generate(
1888        &parse(template)?,
1889        &Options {
1890            floor_bits: Some(0.0),
1891            ..o
1892        },
1893        ctx,
1894        &mut SeqDraw(0x5eed),
1895    )
1896}
1897
1898// ── The vault side: saved recipes, lists, facts and rules ────────────────────────────────────
1899//
1900// Kept at the top level of the vault document: `recipes`, `recipe_lists`, `recipe_vars`,
1901// `recipe_rules` and `recipe_default`. An entry only carries `generated_by` (public metadata of how
1902// its password was made, never a draw) and, when the person picked one there, `recipe`.
1903
1904/// A saved recipe.
1905#[derive(Debug, Clone, PartialEq)]
1906pub struct Saved {
1907    pub name: String,
1908    pub template: String,
1909    pub options: Options,
1910}
1911
1912fn text_of<'a>(v: &'a Value, k: &str) -> &'a str {
1913    v.get(k).and_then(Value::as_str).unwrap_or("")
1914}
1915
1916/// The saved recipes of a vault.
1917pub fn saved(vault: &Value) -> Vec<Saved> {
1918    vault
1919        .get("recipes")
1920        .and_then(Value::as_array)
1921        .map(|list| {
1922            list.iter()
1923                .filter(|r| !text_of(r, "name").is_empty())
1924                .map(|r| Saved {
1925                    name: text_of(r, "name").into(),
1926                    template: text_of(r, "template").into(),
1927                    options: r
1928                        .get("options")
1929                        .and_then(|o| Options::from_value(o).ok())
1930                        .unwrap_or_default(),
1931                })
1932                .collect()
1933        })
1934        .unwrap_or_default()
1935}
1936
1937/// Stores a recipe by name (replacing one of that name when `replace`). The template must parse.
1938pub fn save(
1939    vault: &mut Value,
1940    name: &str,
1941    template: &str,
1942    options: &Options,
1943    replace: bool,
1944) -> Result<(), String> {
1945    let name = name.trim();
1946    if name.is_empty() || name.len() > 64 || name.chars().any(|c| c.is_control()) {
1947        return Err("a recipe name is 1 to 64 characters".into());
1948    }
1949    parse(template)?;
1950    if vault.get("recipes").and_then(Value::as_array).is_none() {
1951        vault["recipes"] = serde_json::json!([]);
1952    }
1953    let list = vault["recipes"].as_array_mut().expect("just made");
1954    let row = serde_json::json!({
1955        "name": name,
1956        "template": template,
1957        "options": serde_json::to_value(options).map_err(|e| e.to_string())?,
1958    });
1959    match list.iter().position(|r| text_of(r, "name") == name) {
1960        Some(_) if !replace => Err(format!("a recipe named {name} exists; use --replace")),
1961        Some(i) => {
1962            list[i] = row;
1963            Ok(())
1964        }
1965        None => {
1966            list.push(row);
1967            Ok(())
1968        }
1969    }
1970}
1971
1972/// Removes a recipe and every rule and default that named it. Returns whether it existed.
1973pub fn remove(vault: &mut Value, name: &str) -> bool {
1974    let mut found = false;
1975    if let Some(list) = vault.get_mut("recipes").and_then(Value::as_array_mut) {
1976        let before = list.len();
1977        list.retain(|r| text_of(r, "name") != name);
1978        found = list.len() != before;
1979    }
1980    if let Some(rules) = vault.get_mut("recipe_rules").and_then(Value::as_array_mut) {
1981        rules.retain(|r| text_of(r, "recipe") != name);
1982    }
1983    if vault.get("recipe_default").and_then(Value::as_str) == Some(name) {
1984        if let Some(o) = vault.as_object_mut() {
1985            o.remove("recipe_default");
1986        }
1987    }
1988    found
1989}
1990
1991/// Your own lists: `(name, words, private)`.
1992pub fn custom_lists(vault: &Value) -> Vec<(String, Vec<String>, bool)> {
1993    vault
1994        .get("recipe_lists")
1995        .and_then(Value::as_array)
1996        .map(|l| {
1997            l.iter()
1998                .map(|x| {
1999                    let words = x
2000                        .get("words")
2001                        .and_then(Value::as_array)
2002                        .map(|w| {
2003                            w.iter()
2004                                .filter_map(|s| s.as_str().map(String::from))
2005                                .collect()
2006                        })
2007                        .unwrap_or_default();
2008                    (
2009                        text_of(x, "name").to_string(),
2010                        words,
2011                        x.get("private").and_then(Value::as_bool).unwrap_or(false),
2012                    )
2013                })
2014                .filter(|(n, _, _)| !n.is_empty())
2015                .collect()
2016        })
2017        .unwrap_or_default()
2018}
2019
2020/// Stores one of your lists. Words are trimmed and deduplicated; fewer than 2 is refused.
2021pub fn save_list(
2022    vault: &mut Value,
2023    name: &str,
2024    words: &[String],
2025    private: bool,
2026) -> Result<usize, String> {
2027    let name = name.trim();
2028    if name.is_empty()
2029        || name.len() > 32
2030        || !name
2031            .chars()
2032            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
2033    {
2034        return Err("a list name is 1 to 32 letters, digits, - or _".into());
2035    }
2036    let mut clean: Vec<String> = Vec::new();
2037    for w in words {
2038        let w = w.trim();
2039        if !w.is_empty() && !clean.iter().any(|c| c == w) {
2040            clean.push(w.to_string());
2041        }
2042    }
2043    if clean.len() < 2 {
2044        return Err("a list needs at least 2 different words".into());
2045    }
2046    if vault
2047        .get("recipe_lists")
2048        .and_then(Value::as_array)
2049        .is_none()
2050    {
2051        vault["recipe_lists"] = serde_json::json!([]);
2052    }
2053    let list = vault["recipe_lists"].as_array_mut().expect("just made");
2054    let row = serde_json::json!({ "name": name, "private": private, "words": clean });
2055    match list.iter().position(|r| text_of(r, "name") == name) {
2056        Some(i) => list[i] = row,
2057        None => list.push(row),
2058    }
2059    Ok(clean.len())
2060}
2061
2062/// Removes a list of yours. Returns whether it existed.
2063pub fn remove_list(vault: &mut Value, name: &str) -> bool {
2064    let Some(list) = vault.get_mut("recipe_lists").and_then(Value::as_array_mut) else {
2065        return false;
2066    };
2067    let before = list.len();
2068    list.retain(|r| text_of(r, "name") != name);
2069    list.len() != before
2070}
2071
2072/// Your facts: `(name, value, private)`.
2073pub fn facts(vault: &Value) -> Vec<(String, String, bool)> {
2074    vault
2075        .get("recipe_vars")
2076        .and_then(Value::as_array)
2077        .map(|l| {
2078            l.iter()
2079                .map(|x| {
2080                    (
2081                        text_of(x, "name").to_string(),
2082                        text_of(x, "value").to_string(),
2083                        x.get("private").and_then(Value::as_bool).unwrap_or(true),
2084                    )
2085                })
2086                .filter(|(n, _, _)| !n.is_empty())
2087                .collect()
2088        })
2089        .unwrap_or_default()
2090}
2091
2092/// Sets a fact. Names are lower-case words so `{var:pet}` and `$pet` are never ambiguous.
2093pub fn set_fact(vault: &mut Value, name: &str, value: &str, private: bool) -> Result<(), String> {
2094    let name = name.trim();
2095    if name.is_empty()
2096        || name.len() > 32
2097        || !name
2098            .chars()
2099            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
2100    {
2101        return Err("a fact name is 1 to 32 lower-case letters, digits or _".into());
2102    }
2103    if value.is_empty() || value.len() > 256 {
2104        return Err("a fact value is 1 to 256 characters".into());
2105    }
2106    if vault.get("recipe_vars").and_then(Value::as_array).is_none() {
2107        vault["recipe_vars"] = serde_json::json!([]);
2108    }
2109    let list = vault["recipe_vars"].as_array_mut().expect("just made");
2110    let row = serde_json::json!({ "name": name, "value": value, "private": private });
2111    match list.iter().position(|r| text_of(r, "name") == name) {
2112        Some(i) => list[i] = row,
2113        None => list.push(row),
2114    }
2115    Ok(())
2116}
2117
2118/// Removes a fact. Returns whether it existed.
2119pub fn remove_fact(vault: &mut Value, name: &str) -> bool {
2120    let Some(list) = vault.get_mut("recipe_vars").and_then(Value::as_array_mut) else {
2121        return false;
2122    };
2123    let before = list.len();
2124    list.retain(|r| text_of(r, "name") != name);
2125    list.len() != before
2126}
2127
2128/// What an assignment rule matches on.
2129pub const RULE_KINDS: [&str; 6] = ["provider", "family", "host", "type", "project", "tag"];
2130
2131/// The assignment rules, in order: `(kind, value, recipe)`.
2132pub fn rules(vault: &Value) -> Vec<(String, String, String)> {
2133    vault
2134        .get("recipe_rules")
2135        .and_then(Value::as_array)
2136        .map(|l| {
2137            l.iter()
2138                .map(|r| {
2139                    (
2140                        text_of(r, "kind").into(),
2141                        text_of(r, "value").into(),
2142                        text_of(r, "recipe").into(),
2143                    )
2144                })
2145                .collect()
2146        })
2147        .unwrap_or_default()
2148}
2149
2150/// Appends a rule. The recipe must exist.
2151pub fn add_rule(vault: &mut Value, kind: &str, value: &str, recipe: &str) -> Result<(), String> {
2152    if !RULE_KINDS.contains(&kind) {
2153        return Err(format!("a rule matches on {}", RULE_KINDS.join(", ")));
2154    }
2155    if value.trim().is_empty() {
2156        return Err("a rule needs a value to match".into());
2157    }
2158    if !saved(vault).iter().any(|r| r.name == recipe) && recipe != "none" {
2159        return Err(format!(
2160            "no recipe named {recipe} (use `none` to switch recipes off for a match)"
2161        ));
2162    }
2163    if vault
2164        .get("recipe_rules")
2165        .and_then(Value::as_array)
2166        .is_none()
2167    {
2168        vault["recipe_rules"] = serde_json::json!([]);
2169    }
2170    vault["recipe_rules"]
2171        .as_array_mut()
2172        .expect("just made")
2173        .push(serde_json::json!({ "kind": kind, "value": value.trim(), "recipe": recipe }));
2174    Ok(())
2175}
2176
2177/// Removes the rule at 1-based `n`. Returns whether it existed.
2178pub fn remove_rule(vault: &mut Value, n: usize) -> bool {
2179    match vault.get_mut("recipe_rules").and_then(Value::as_array_mut) {
2180        Some(l) if n >= 1 && n <= l.len() => {
2181            l.remove(n - 1);
2182            true
2183        }
2184        _ => false,
2185    }
2186}
2187
2188fn first_host(entry: &Value) -> String {
2189    crate::sites::entry_sites(entry)
2190        .into_iter()
2191        .next()
2192        .map(|s| s.site.host)
2193        .unwrap_or_default()
2194}
2195
2196fn rule_matches(kind: &str, value: &str, entry: &Value, vault: &Value) -> bool {
2197    let eq = |a: &str| a.eq_ignore_ascii_case(value);
2198    match kind {
2199        "provider" => eq(text_of(entry, "provider")),
2200        "type" => eq(match text_of(entry, "secretType") {
2201            "" => "api_key",
2202            t => t,
2203        }),
2204        "family" => eq(text_of(entry, "site_family")),
2205        "host" => crate::sites::entry_sites(entry).iter().any(|s| {
2206            s.site.host.eq_ignore_ascii_case(value)
2207                || s.site
2208                    .host
2209                    .ends_with(&format!(".{}", value.to_ascii_lowercase()))
2210        }),
2211        "tag" => entry
2212            .get("tags")
2213            .and_then(Value::as_array)
2214            .is_some_and(|t| t.iter().any(|x| x.as_str().is_some_and(eq))),
2215        "project" => entry
2216            .get("projectIds")
2217            .and_then(Value::as_array)
2218            .is_some_and(|ids| {
2219                ids.iter().filter_map(Value::as_str).any(|id| {
2220                    eq(id)
2221                        || vault
2222                            .get("projects")
2223                            .and_then(Value::as_array)
2224                            .is_some_and(|ps| {
2225                                ps.iter()
2226                                    .any(|p| text_of(p, "id") == id && eq(text_of(p, "name")))
2227                            })
2228                })
2229            }),
2230        _ => false,
2231    }
2232}
2233
2234/// Which saved recipe applies to `entry`, and why: the entry's own pick, the first matching rule,
2235/// then the vault default; `None` means plain random, as before recipes existed.
2236pub fn resolve(vault: &Value, entry: &Value) -> Option<(Saved, String)> {
2237    let all = saved(vault);
2238    let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
2239    let own = text_of(entry, "recipe");
2240    if own == "none" {
2241        return None;
2242    }
2243    if !own.is_empty() {
2244        return find(own).map(|r| (r, "this entry".into()));
2245    }
2246    for (kind, value, recipe) in rules(vault) {
2247        if rule_matches(&kind, &value, entry, vault) {
2248            return if recipe == "none" {
2249                None
2250            } else {
2251                find(&recipe).map(|r| (r, format!("rule: {kind} {value}")))
2252            };
2253        }
2254    }
2255    vault
2256        .get("recipe_default")
2257        .and_then(Value::as_str)
2258        .and_then(find)
2259        .map(|r| (r, "vault default".into()))
2260}
2261
2262/// The context for generating a password for `entry` (or for no entry at all, when testing).
2263/// `now` is `YYYY-MM-DD`, passed in so nothing here reads the clock.
2264pub fn context(vault: &Value, entry: Option<&Value>, now: &str) -> Ctx {
2265    let mut c = Ctx {
2266        now: now.into(),
2267        counter: 1,
2268        ..Ctx::default()
2269    };
2270    for (n, v, _) in facts(vault) {
2271        c.vars.insert(n, v);
2272    }
2273    for (n, words, private) in custom_lists(vault) {
2274        if private {
2275            c.private_lists.insert(n.clone());
2276        }
2277        c.lists.insert(n, words);
2278    }
2279    let Some(e) = entry else {
2280        return c;
2281    };
2282    let t = |k: &str| text_of(e, k).to_string();
2283    c.provider = t("provider");
2284    c.host = first_host(e);
2285    c.url = e
2286        .get("sites")
2287        .and_then(Value::as_array)
2288        .and_then(|s| s.first())
2289        .map(|s| text_of(s, "url").to_string())
2290        .filter(|u| !u.is_empty())
2291        .unwrap_or_else(|| t("api_url"));
2292    c.user = t("username");
2293    c.email = t("email");
2294    c.id = t("id");
2295    c.key_id = t("key_id");
2296    c.family = t("site_family");
2297    c.secret_type = match t("secretType").as_str() {
2298        "" => "api_key".into(),
2299        other => other.into(),
2300    };
2301    c.created = t("created_at").chars().take(10).collect();
2302    c.project = e
2303        .get("projectIds")
2304        .and_then(Value::as_array)
2305        .and_then(|ids| {
2306            ids.iter()
2307                .filter_map(Value::as_str)
2308                .find(|i| *i != "Universal")
2309        })
2310        .map(|id| {
2311            vault
2312                .get("projects")
2313                .and_then(Value::as_array)
2314                .and_then(|ps| ps.iter().find(|p| text_of(p, "id") == id))
2315                .map(|p| text_of(p, "name").to_string())
2316                .unwrap_or_else(|| id.to_string())
2317        })
2318        .unwrap_or_default();
2319    c.counter = e
2320        .get("generated_by")
2321        .and_then(|g| g.get("counter"))
2322        .and_then(Value::as_u64)
2323        .unwrap_or(0)
2324        + 1;
2325    // Never repeat what this entry holds now, or held before.
2326    if let Some(k) = e
2327        .get("api_key")
2328        .and_then(Value::as_str)
2329        .filter(|k| !k.is_empty())
2330    {
2331        c.avoid.push(k.to_string());
2332    }
2333    if let Some(h) = e.get("version_history").and_then(Value::as_array) {
2334        for old in h {
2335            if let Some(k) = old
2336                .get("api_key")
2337                .and_then(Value::as_str)
2338                .filter(|k| !k.is_empty())
2339            {
2340                c.avoid.push(k.to_string());
2341            }
2342        }
2343    }
2344    c
2345}
2346
2347/// The public record of how a password was made: the recipe name, the counter and the date. It
2348/// holds no secret and no draw, so it is safe in every listing.
2349pub fn generated_by(recipe: &str, counter: u64, now: &str) -> Value {
2350    serde_json::json!({ "recipe": recipe, "version": 1, "counter": counter, "at": now })
2351}
2352
2353#[cfg(test)]
2354mod tests {
2355    use super::*;
2356
2357    fn ctx() -> Ctx {
2358        let mut c = Ctx {
2359            provider: "Instagram".into(),
2360            host: "www.instagram.com".into(),
2361            url: "https://www.instagram.com".into(),
2362            user: "joy".into(),
2363            email: "joy@example.org".into(),
2364            id: "0a1b2c3d-1111".into(),
2365            key_id: "k1".into(),
2366            project: "Social".into(),
2367            secret_type: "password".into(),
2368            family: "meta".into(),
2369            created: "2018-11-11".into(),
2370            now: "2026-11-15".into(),
2371            counter: 3,
2372            ..Ctx::default()
2373        };
2374        c.vars.insert("pet".into(), "rex".into());
2375        c
2376    }
2377
2378    fn open() -> Options {
2379        Options {
2380            floor_bits: Some(0.0),
2381            ..Options::default()
2382        }
2383    }
2384
2385    fn run(t: &str) -> Result<Generated, String> {
2386        make(t, &open(), &ctx(), &mut SeqDraw(7))
2387    }
2388
2389    fn text(t: &str) -> String {
2390        run(t).unwrap().text
2391    }
2392
2393    #[test]
2394    fn literals_braces_and_errors_in_the_grammar() {
2395        assert_eq!(text("a{{b}}c-{fixed:\"x y:z\"}"), "a{b}c-x y:z");
2396        for (bad, want) in [
2397            ("{random:4", "never closed"),
2398            ("a}b", "stray"),
2399            ("{nope}", "not a token"),
2400            ("{random:4|nope}", "not a transform"),
2401            ("{}", "needs a name"),
2402            ("", "empty"),
2403            ("{random:x}", "not a whole number"),
2404            ("{random:4:a}", "at least 2"),
2405            ("{number:5..1}", "backwards"),
2406            ("{number:5}", "MIN..MAX"),
2407            ("{list:nope}", "no list named nope"),
2408            ("{var:ghost}", "no fact named ghost"),
2409            ("{typed}", "typed"),
2410            ("{created:YYYY}{date:2018-13-40}", "not a date"),
2411            ("{random:999}", "0 to 256"),
2412        ] {
2413            let err = run(bad).unwrap_err();
2414            assert!(err.contains(want), "{bad}: {err}");
2415        }
2416    }
2417
2418    #[test]
2419    fn the_registry_and_the_implementation_list_each_other() {
2420        let reg = registry();
2421        let tokens = reg["tokens"].as_array().unwrap();
2422        let mut seen = BTreeSet::new();
2423        for t in tokens {
2424            let id = t["id"].as_str().unwrap();
2425            assert!(seen.insert(id.to_string()), "{id} is listed twice");
2426            let kind = t["kind"].as_str().unwrap();
2427            let implemented = if matches!(kind, "transform" | "derive") {
2428                TRANSFORM_IDS.contains(&id)
2429            } else {
2430                TOKEN_IDS.contains(&id)
2431            };
2432            assert!(implemented, "{id} has a descriptor and no implementation");
2433            for f in ["label", "summary", "group", "bits", "example"] {
2434                assert!(!t[f].as_str().unwrap_or("").is_empty(), "{id}.{f}");
2435            }
2436        }
2437        for id in TOKEN_IDS.iter().chain(TRANSFORM_IDS) {
2438            assert!(
2439                seen.contains(*id),
2440                "{id} has an implementation and no descriptor"
2441            );
2442        }
2443        assert_eq!(seen.len(), TOKEN_IDS.len() + TRANSFORM_IDS.len());
2444    }
2445
2446    #[test]
2447    fn every_documented_example_renders() {
2448        for t in registry()["tokens"].as_array().unwrap() {
2449            let ex = t["example"].as_str().unwrap();
2450            let mut c = ctx();
2451            c.typed = Some("Typed-123".into());
2452            make(ex, &open(), &c, &mut SeqDraw(11)).unwrap_or_else(|e| panic!("{ex}: {e}"));
2453        }
2454    }
2455
2456    #[test]
2457    fn the_same_draws_give_the_same_password_and_other_draws_differ() {
2458        let t = "{prefix}-{list:food:2:+}-{random:12:base62}";
2459        let a = make(t, &open(), &ctx(), &mut SeqDraw(5)).unwrap();
2460        let b = make(t, &open(), &ctx(), &mut SeqDraw(5)).unwrap();
2461        assert_eq!(a.text, b.text);
2462        assert_ne!(
2463            a.text,
2464            make(t, &open(), &ctx(), &mut SeqDraw(6)).unwrap().text
2465        );
2466    }
2467
2468    #[test]
2469    fn random_tokens_have_the_right_shape_and_the_bits_the_formula_says() {
2470        let g = run("{random:20:safe}").unwrap();
2471        assert_eq!(g.text.chars().count(), 20);
2472        assert!((g.bits - 20.0 * (alphabet("safe").unwrap().len() as f64).log2()).abs() < 1e-9);
2473        assert_eq!(text("{digits:6}").len(), 6);
2474        assert!(text("{digits:6}").chars().all(|c| c.is_ascii_digit()));
2475        assert!(text("{hex:9}").chars().all(|c| c.is_ascii_hexdigit()));
2476        assert!(text("{base32:9}").chars().all(|c| !"ILOU".contains(c)));
2477        assert!(text("{base36:9}")
2478            .chars()
2479            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
2480        assert_eq!(
2481            text("{base62:9}|{letters:5}|{pin:4}|{uuid_chunk:4}").len(),
2482            9 + 1 + 5 + 1 + 4 + 1 + 4
2483        );
2484        assert!(text("{symbols:3}").chars().all(|c| SYMBOLS.contains(c)));
2485        let n: i64 = text("{number:100..102}").parse().unwrap();
2486        assert!((100..=102).contains(&n));
2487        assert!((1990..=2010).contains(&text("{year:1990..2010}").parse::<i64>().unwrap()));
2488        let s = text("{syllables:3}");
2489        assert_eq!(s.len(), 6);
2490        assert!(s.chars().step_by(2).all(|c| CONSONANTS.contains(c)));
2491        let m = text("{mask:\"CvcV-99#\"}");
2492        assert_eq!(m.chars().count(), 8);
2493        assert!(m.chars().nth(4) == Some('-'));
2494        let d = run("{dice:4}").unwrap();
2495        assert_eq!(d.text.split('-').count(), 4);
2496        assert!((d.bits - 44.0).abs() < 1e-9);
2497        assert!(["red", "green"].contains(&text("{one_of:red:green}").as_str()));
2498        assert!(run("{one_of:red}").is_err());
2499    }
2500
2501    #[test]
2502    fn lists_prefer_your_own_and_report_their_size_in_bits() {
2503        let mut c = ctx();
2504        c.lists
2505            .insert("food".into(), vec!["kimchi".into(), "naan".into()]);
2506        c.private_lists.insert("food".into());
2507        let g = make("{list:food:3:/}", &open(), &c, &mut SeqDraw(2)).unwrap();
2508        assert_eq!(g.text.split('/').count(), 3);
2509        assert!((g.bits - 3.0).abs() < 1e-9);
2510        assert!(g.parts[0].private && g.private_bits == 3.0);
2511        assert!(g.warnings.iter().any(|w| w.contains("under 6 bits")));
2512        let built = run("{prefix}{divider}{adj}{noun}{verb}{color}{animal}{city}{country}{name}{element}{planet}{month}{weekday}{bip39:2: }").unwrap();
2513        assert!(built.bits > 30.0);
2514    }
2515
2516    #[test]
2517    fn entry_data_dates_counters_and_facts_come_from_the_context() {
2518        assert_eq!(
2519            text("{provider}|{provider_short}|{host}|{host_label}|{tld}"),
2520            "Instagram|instagram|www.instagram.com|instagram|com"
2521        );
2522        assert_eq!(
2523            text("{url}|{user}|{email_local}|{project}|{type}|{key_id}|{id:4}"),
2524            "https://www.instagram.com|joy|joy|Social|password|k1|0a1b"
2525        );
2526        assert_eq!(text("{created:D_M_YYYY}"), "11_11_2018");
2527        assert_eq!(
2528            text("{created:DD/MM/YY Month Mon DOW}"),
2529            "11/11/18 November Nov Sun"
2530        );
2531        assert_eq!(
2532            text("{now:YYYY-MM-DD}|{date:2018-11-11:D_Mon_YY}|{counter:3}|{var:pet}"),
2533            "2026-11-15|11_Nov_18|003|rex"
2534        );
2535        assert_eq!(text("{fixed:$pet}{random:2:digits|first:0}"), "rex");
2536        // The maintainer's arrangement from the plan.
2537        let g =
2538            run("{provider}_{created:D_M_YYYY}_Password_{random:22:base36}_11_Nov_18_{digits:3}")
2539                .unwrap();
2540        assert!(g.text.starts_with("Instagram_11_11_2018_Password_"));
2541        assert!(g.text.contains("_11_Nov_18_"));
2542        // No data: the error says what is missing.
2543        let bare = Ctx::default();
2544        let e = make("{host}", &open(), &bare, &mut SeqDraw(1)).unwrap_err();
2545        assert!(e.contains("needs an address"), "{e}");
2546        let mut c = ctx();
2547        c.created.clear();
2548        assert_eq!(
2549            make("{created:YYYY}", &open(), &c, &mut SeqDraw(1))
2550                .unwrap()
2551                .text,
2552            "2026"
2553        );
2554        let mut typed = ctx();
2555        typed.typed = Some("Correct-Horse-9".into());
2556        let g = make("{typed}", &open(), &typed, &mut SeqDraw(1)).unwrap();
2557        assert!(g.text == "Correct-Horse-9" && g.bits > 20.0 && g.parts[0].private);
2558    }
2559
2560    #[test]
2561    fn transforms_do_what_their_names_say() {
2562        for (t, want) in [
2563            ("{fixed:\"hello world\"|upper}", "HELLO WORLD"),
2564            ("{fixed:\"HELLO\"|lower}", "hello"),
2565            ("{fixed:\"hello big world\"|title}", "Hello Big World"),
2566            ("{fixed:\"hELLO\"|sentence}", "Hello"),
2567            ("{fixed:\"hello big world\"|camel}", "helloBigWorld"),
2568            ("{fixed:\"Hello Big World\"|snake}", "hello_big_world"),
2569            ("{fixed:\"abcd\"|alt}", "aBcD"),
2570            ("{fixed:\"aBc\"|toggle}", "AbC"),
2571            ("{fixed:\"abcdef\"|first:2}", "ab"),
2572            ("{fixed:\"abcdef\"|last:2}", "ef"),
2573            ("{fixed:\"abcdef\"|skip:4}", "ef"),
2574            ("{fixed:\"abcdef\"|take:1..3}", "bc"),
2575            ("{fixed:\"  x \"|trim}", "x"),
2576            ("{fixed:\"abc\"|reverse}", "cba"),
2577            ("{fixed:\"ab\"|repeat:3}", "ababab"),
2578            ("{fixed:\"aabbcc\"|dedupe}", "abc"),
2579            ("{fixed:\"banana\"|remove:an}", "b"),
2580            ("{fixed:\"a1b2\"|keep:digits}", "12"),
2581            ("{fixed:\"a-b\"|replace:\"-\":\"+\"}", "a+b"),
2582            ("{fixed:\"aeios\"|leet:2}", "43105"),
2583            ("{fixed:\"education\"|drop_vowels}", "dctn"),
2584            ("{fixed:\"ab\"|pad:5:x:left}", "xxxab"),
2585            ("{fixed:\"ab\"|pad:4:\"-\"}", "ab--"),
2586            ("{fixed:\"Hello Big World\"|initials}", "HBW"),
2587            ("{fixed:\"a b c\"|join:\"-\"}", "a-b-c"),
2588            ("{number:7..7|add:5}", "12"),
2589            ("{number:7..7|mul:3}", "21"),
2590            ("{number:7..7|mod:4}", "3"),
2591            ("{number:2018..2018|roman}", "MMXVIII"),
2592            ("{number:42..42|spell}", "forty-two"),
2593            (
2594                "{number:1234..1234|spell}",
2595                "one thousand two hundred thirty-four",
2596            ),
2597            ("{fixed:\"ab\"|to_hex}", "6162"),
2598        ] {
2599            assert_eq!(text(t), want, "{t}");
2600        }
2601        assert!(run("{fixed:\"x\"|add:1}").is_err());
2602        assert!(run("{number:5000..5000|roman}").is_err());
2603        assert!(run("{number:5..5|mod:0}").is_err());
2604        assert!(run("{fixed:\"x\"|keep:blue}").is_err());
2605        assert_eq!(text("{fixed:\"abc\"|hash:6}").len(), 6);
2606        assert_eq!(text("{fixed:\"abc\"|check_tail:2}").len(), 5);
2607        assert_eq!(
2608            text("{fixed:\"abc\"|check_tail:2}"),
2609            text("{fixed:\"abc\"|check_tail:2}")
2610        );
2611        let e = text("{fixed:\"abc\"|ensure:upper+digit+symbol}");
2612        assert!(e.chars().any(|c| c.is_ascii_uppercase()) && e.chars().any(|c| c.is_ascii_digit()));
2613        let all = text("{fixed:\"abc\"|class_fill}");
2614        assert!(
2615            all.chars().any(|c| c.is_ascii_uppercase())
2616                && all.chars().any(|c| !c.is_ascii_alphanumeric())
2617        );
2618        assert!(run("{fixed:\"abc\"|ensure:blue}").is_err());
2619        let keyed = text("{fixed:\"abcdefgh\"|keyed_case}");
2620        assert_eq!(keyed.to_lowercase(), "abcdefgh");
2621        assert_eq!(keyed, text("{fixed:\"abcdefgh\"|keyed_case}"));
2622    }
2623
2624    #[test]
2625    fn a_slice_keeps_its_share_of_the_bits() {
2626        let g = run("{random:20:base36|first:10}").unwrap();
2627        assert!((g.bits - 10.0 * 36f64.log2()).abs() < 1e-9);
2628    }
2629
2630    #[test]
2631    fn lengtheners_add_length_and_no_bits_and_never_change_between_versions() {
2632        // Golden vectors for `v1`: computed outside this file from the stated construction (HKDF-SHA256,
2633        // salt SHA-256("unv/recipe/expand/v1"), info "v1|" + context, 16-bit draws with rejection). Never regenerated.
2634        let e =
2635            |ctx: &str| derive_chars("abcdefgh", ctx, &alphabet("base36").unwrap(), 22).unwrap();
2636        assert_eq!(e(""), "3v68o4p9q8zt8jt1u8dk2j");
2637        assert_eq!(e("sonarr.home.lan"), "jnqpoppoozsmowaa0x9xdj");
2638        assert_eq!(
2639            derive_chars("abcdefgh", "", &alphabet("base36").unwrap(), 10).unwrap(),
2640            "3v68o4p9q8"
2641        );
2642        let g = run("{fixed:\"abcdefgh\"|expand:22:base36}").unwrap();
2643        assert_eq!(g.text, "3v68o4p9q8zt8jt1u8dk2j");
2644        assert_eq!(g.bits, 0.0);
2645        // A random part keeps the bits it was drawn with, however long the expansion.
2646        let r = run("{random:8:base36|expand:40:base36}").unwrap();
2647        assert_eq!(r.text.len(), 40);
2648        assert!((r.bits - 8.0 * 36f64.log2()).abs() < 1e-9);
2649        assert_eq!(r.parts[0].kind, "derive");
2650        // The context decides what is shared.
2651        let host = |h: &str, f: &str| {
2652            let mut c = ctx();
2653            c.host = h.into();
2654            c.family = f.into();
2655            make(
2656                "{fixed:\"abcdefgh\"|site_bound:12}|{fixed:\"abcdefgh\"|family_bound:12}",
2657                &open(),
2658                &c,
2659                &mut SeqDraw(1),
2660            )
2661            .unwrap()
2662            .text
2663        };
2664        let (a, b) = (host("a.example.org", "meta"), host("b.example.org", "meta"));
2665        let (a1, a2) = a.split_once('|').unwrap();
2666        let (b1, b2) = b.split_once('|').unwrap();
2667        assert_ne!(a1, b1, "a different host gives a different result");
2668        assert_eq!(a2, b2, "one family shares one result");
2669        assert_ne!(text("{fixed:\"abcdefgh\"|rotate_by_counter:12}"), {
2670            let mut c = ctx();
2671            c.counter = 4;
2672            make(
2673                "{fixed:\"abcdefgh\"|rotate_by_counter:12}",
2674                &open(),
2675                &c,
2676                &mut SeqDraw(1),
2677            )
2678            .unwrap()
2679            .text
2680        });
2681        let words = text("{fixed:\"abcdefgh\"|expand_words:3}");
2682        assert_eq!(words.split('-').count(), 3);
2683        assert_eq!(words, text("{fixed:\"abcdefgh\"|expand_words:3}"));
2684        // stretch: deterministic, the asked length, a different result per context and per value,
2685        // and no more strength than the value it came from. The Argon2id primitive itself is
2686        // pinned by vault-core's own golden test; here the construction (salt label, hex of the key
2687        // fed to the same derivation as `expand`) is pinned by a vector computed once from it.
2688        let st = text("{fixed:\"abcdefgh\"|stretch:16:base36}");
2689        assert_eq!(st.len(), 16);
2690        assert_eq!(st, text("{fixed:\"abcdefgh\"|stretch:16:base36}"));
2691        assert_ne!(st, text("{fixed:\"abcdefgi\"|stretch:16:base36}"));
2692        assert_ne!(st, text("{fixed:\"abcdefgh\"|stretch:16:base36:entry}"));
2693        assert_ne!(st, text("{fixed:\"abcdefgh\"|expand:16:base36}"));
2694        let groups = text("{fixed:\"abcdefgh\"|expand_groups:2:5:hex}");
2695        assert_eq!(groups.len(), 11);
2696        assert!(groups.chars().nth(5) == Some('-'));
2697        for bad in [
2698            "{fixed:\"a\"|expand:5:base36:nowhere}",
2699            "{fixed:\"a\"|expand:5:base36:family}",
2700            "{fixed:\"a\"|expand:5:x}",
2701        ] {
2702            let mut c = Ctx::default();
2703            c.family.clear();
2704            assert!(make(bad, &open(), &c, &mut SeqDraw(1)).is_err(), "{bad}");
2705        }
2706        for ctxname in ["entry", "provider", "counter"] {
2707            run(&format!("{{fixed:\"a\"|expand:6:base36:{ctxname}}}")).unwrap();
2708        }
2709    }
2710
2711    #[test]
2712    fn the_floor_refuses_a_password_that_is_too_weak() {
2713        let strict = Options::default();
2714        let weak = make("{prefix}-{digits:3}", &strict, &ctx(), &mut SeqDraw(1)).unwrap_err();
2715        assert!(weak.contains("below the floor of 64"), "{weak}");
2716        assert!(make("{random:16:safe}", &strict, &ctx(), &mut SeqDraw(1)).is_ok());
2717        let low = Options {
2718            floor_bits: Some(8.0),
2719            ..Options::default()
2720        };
2721        assert!(make("{digits:3}", &low, &ctx(), &mut SeqDraw(1)).is_ok());
2722    }
2723
2724    #[test]
2725    fn options_are_met_by_drawing_again_and_unmeetable_ones_say_so() {
2726        let o = Options {
2727            floor_bits: Some(0.0),
2728            require_upper: 2,
2729            require_digit: 2,
2730            require_symbol: 1,
2731            avoid_ambiguous: true,
2732            forbid: "x".into(),
2733            max_run: 2,
2734            no_sequences: true,
2735            start_letter: true,
2736            no_edge_symbol: true,
2737            ..Options::default()
2738        };
2739        for seed in 1..40 {
2740            let g = make(
2741                "{random:14:safe}{symbols:1}{random:3:safe}",
2742                &o,
2743                &ctx(),
2744                &mut SeqDraw(seed),
2745            );
2746            let g = g.unwrap();
2747            assert!(g.text.chars().next().unwrap().is_alphabetic());
2748            assert!(g.text.chars().filter(|c| c.is_ascii_uppercase()).count() >= 2);
2749            assert!(!g.text.contains(['x', '0', 'O', '1', 'l', 'I']));
2750        }
2751        let impossible = Options {
2752            floor_bits: Some(0.0),
2753            require_digit: 5,
2754            ..Options::default()
2755        };
2756        let e = make("{letters:6}", &impossible, &ctx(), &mut SeqDraw(1)).unwrap_err();
2757        assert!(e.contains("too few digits"), "{e}");
2758        let only = Options {
2759            floor_bits: Some(0.0),
2760            allow: "ab".into(),
2761            ..Options::default()
2762        };
2763        assert!(make("{fixed:\"abc\"}", &only, &ctx(), &mut SeqDraw(1)).is_err());
2764        assert!(make(
2765            "{fixed:\"aab\"}",
2766            &Options {
2767                floor_bits: Some(0.0),
2768                allow: "ab".into(),
2769                ..Options::default()
2770            },
2771            &ctx(),
2772            &mut SeqDraw(1)
2773        )
2774        .is_ok());
2775    }
2776
2777    #[test]
2778    fn length_is_fitted_by_dropping_the_marked_parts_then_refused_if_still_long() {
2779        let o = Options {
2780            floor_bits: Some(40.0),
2781            max_len: Some(16),
2782            ..Options::default()
2783        };
2784        let t = "{random:14:base62}{suffix?1}{counter?2}{divider?3}";
2785        let g = make(t, &o, &ctx(), &mut SeqDraw(3)).unwrap();
2786        assert!(g.text.chars().count() <= 16);
2787        assert!(g.dropped.contains(&"divider".to_string()));
2788        let e = make("{random:20:base62}", &o, &ctx(), &mut SeqDraw(3)).unwrap_err();
2789        assert!(e.contains("no droppable part"), "{e}");
2790        // A hostile maximum cannot steer the result below the floor.
2791        let hostile = Options {
2792            floor_bits: Some(64.0),
2793            max_len: Some(6),
2794            ..Options::default()
2795        };
2796        let e = make(
2797            "{random:16:base62}{suffix?1}",
2798            &hostile,
2799            &ctx(),
2800            &mut SeqDraw(3),
2801        )
2802        .unwrap_err();
2803        assert!(e.contains("cannot fit"), "{e}");
2804        let refuse = Options {
2805            floor_bits: Some(0.0),
2806            max_len: Some(3),
2807            policy: "refuse".into(),
2808            ..Options::default()
2809        };
2810        assert!(
2811            make("{random:9}{suffix?1}", &refuse, &ctx(), &mut SeqDraw(3))
2812                .unwrap_err()
2813                .contains("refuse")
2814        );
2815        let nothing_left = Options {
2816            floor_bits: Some(0.0),
2817            max_len: Some(2),
2818            ..Options::default()
2819        };
2820        assert!(
2821            make("abcdefgh{suffix?1}", &nothing_left, &ctx(), &mut SeqDraw(3))
2822                .unwrap_err()
2823                .contains("no droppable part")
2824        );
2825    }
2826
2827    #[test]
2828    fn a_short_result_is_padded_or_refused_and_the_padding_counts_its_bits() {
2829        let o = Options {
2830            floor_bits: Some(0.0),
2831            min_len: Some(12),
2832            ..Options::default()
2833        };
2834        let g = make("{fixed:\"abc\"}", &o, &ctx(), &mut SeqDraw(1)).unwrap();
2835        assert_eq!(g.text.chars().count(), 12);
2836        assert!(g.bits > 40.0 && g.warnings[0].contains("padded"));
2837        let refuse = Options {
2838            policy: "refuse".into(),
2839            ..o
2840        };
2841        assert!(make("{fixed:\"abc\"}", &refuse, &ctx(), &mut SeqDraw(1))
2842            .unwrap_err()
2843            .contains("below the minimum"));
2844    }
2845
2846    #[test]
2847    fn chunking_and_the_reuse_check_and_memory_rebuildability() {
2848        let o = Options {
2849            floor_bits: Some(0.0),
2850            chunk: 4,
2851            chunk_sep: "_".into(),
2852            ..Options::default()
2853        };
2854        let g = make("{random:8:hex}", &o, &ctx(), &mut SeqDraw(1)).unwrap();
2855        assert_eq!(g.text.matches('_').count(), 1);
2856        let dash = Options {
2857            floor_bits: Some(0.0),
2858            chunk: 2,
2859            ..Options::default()
2860        };
2861        assert_eq!(
2862            make("{fixed:\"abcd\"}", &dash, &ctx(), &mut SeqDraw(1))
2863                .unwrap()
2864                .text,
2865            "ab-cd"
2866        );
2867        let mut c = ctx();
2868        let first = make("{digits:1}", &open(), &c, &mut SeqDraw(1))
2869            .unwrap()
2870            .text;
2871        c.avoid = vec![first.clone()];
2872        for seed in 1..20 {
2873            assert_ne!(
2874                make("{digits:1}", &open(), &c, &mut SeqDraw(seed))
2875                    .unwrap()
2876                    .text,
2877                first
2878            );
2879        }
2880        c.avoid = (0..10).map(|d| d.to_string()).collect();
2881        assert!(make("{digits:1}", &open(), &c, &mut SeqDraw(1))
2882            .unwrap_err()
2883            .contains("already used"));
2884        assert!(
2885            run("{provider}{created:YYYY}")
2886                .unwrap()
2887                .rebuildable_from_memory
2888        );
2889        assert!(!run("{provider}{random:4}").unwrap().rebuildable_from_memory);
2890        assert!(
2891            !run("{fixed:\"a\"|expand:6}")
2892                .unwrap()
2893                .rebuildable_from_memory
2894        );
2895        assert!(
2896            analyse("{provider}-{random:10:base62}", &Options::default(), &ctx())
2897                .unwrap()
2898                .bits
2899                > 50.0
2900        );
2901        assert!(analyse("{nope}", &Options::default(), &ctx()).is_err());
2902    }
2903
2904    #[test]
2905    fn the_generated_part_table_never_carries_a_value() {
2906        let g = run("{prefix}{random:12:base62}").unwrap();
2907        let shown = serde_json::to_string(&g.parts).unwrap();
2908        assert!(!shown.contains(&g.text));
2909        assert_eq!(g.parts.len(), 2);
2910        assert_eq!(g.parts[0].kind, "list");
2911    }
2912
2913    #[test]
2914    fn draws_are_uniform_enough_and_failures_surface() {
2915        let mut d = SeqDraw(9);
2916        let mut hits = [0u32; 6];
2917        for _ in 0..6000 {
2918            hits[d.below(6) as usize] += 1;
2919        }
2920        assert!(hits.iter().all(|h| (800..1200).contains(h)), "{hits:?}");
2921        struct Failing;
2922        impl Draw for Failing {
2923            fn next_u64(&mut self) -> u64 {
2924                0
2925            }
2926            fn failure(&self) -> Option<String> {
2927                Some("device failed".into())
2928            }
2929        }
2930        assert_eq!(
2931            make("{random:4}", &open(), &ctx(), &mut Failing).unwrap_err(),
2932            "device failed"
2933        );
2934        let mut sys = SysDraw;
2935        assert_ne!(sys.next_u64(), sys.next_u64());
2936        let mut pool = PoolDraw::new(crate::entropy::Source::Os);
2937        assert_ne!(pool.next_u64(), pool.next_u64());
2938        assert!(pool.failure().is_none());
2939    }
2940
2941    #[test]
2942    fn options_read_from_json_and_reject_nonsense() {
2943        let o = Options::from_value(
2944            &serde_json::json!({ "max_len": 12, "require_digit": 2, "floor_bits": 32.0 }),
2945        )
2946        .unwrap();
2947        assert_eq!((o.max_len, o.require_digit, o.floor()), (Some(12), 2, 32.0));
2948        assert_eq!(
2949            Options::from_value(&Value::Null).unwrap().floor(),
2950            DEFAULT_FLOOR_BITS
2951        );
2952        assert!(Options::from_value(&serde_json::json!({ "max_len": "long" })).is_err());
2953        assert!(builtin_lists().contains_key("prefix"));
2954    }
2955
2956    #[test]
2957    fn the_syntax_helpers_handle_quotes_and_escapes() {
2958        assert_eq!(split_top("a:\"b:c\":d", ':'), ["a", "\"b:c\"", "d"]);
2959        assert_eq!(parse_arg("\"a\\\"b\"").text, "a\"b");
2960        assert!(parse_arg("$pet").text.starts_with('$') && !parse_arg("$pet").quoted);
2961        assert!(parse_arg("\"$pet\"").quoted);
2962        let t = parse("{suffix?2}{random:4?1}x").unwrap();
2963        assert_eq!(t.segs.len(), 3);
2964        assert!(matches!(&t.segs[0], Seg::Tok(k) if k.droppable == Some(2)));
2965        assert_eq!(format_date("Y D", "2026-11-15").unwrap(), "Y 15");
2966        assert_eq!(weekday(2026, 11, 15), 0);
2967    }
2968
2969    fn vault() -> Value {
2970        serde_json::json!({
2971            "projects": [{ "id": "p1", "name": "Social" }],
2972            "api_keys": []
2973        })
2974    }
2975
2976    fn entry() -> Value {
2977        serde_json::json!({
2978            "id": "e1", "provider": "Instagram", "secretType": "password", "api_key": "old-1",
2979            "username": "joy", "email": "joy@example.org", "created_at": "2018-11-11T10:00:00Z",
2980            "projectIds": ["Universal", "p1"], "tags": ["social"], "site_family": "meta",
2981            "sites": [{ "url": "https://www.instagram.com", "kind": "web" }],
2982            "version_history": [{ "api_key": "old-0" }],
2983            "generated_by": { "recipe": "x", "counter": 4 }
2984        })
2985    }
2986
2987    #[test]
2988    fn recipes_are_saved_replaced_and_removed_with_their_rules() {
2989        let mut v = vault();
2990        save(&mut v, "social", "{random:16}", &Options::default(), false).unwrap();
2991        assert!(
2992            save(&mut v, "social", "{random:20}", &Options::default(), false)
2993                .unwrap_err()
2994                .contains("--replace")
2995        );
2996        save(
2997            &mut v,
2998            "social",
2999            "{random:20}",
3000            &Options {
3001                max_len: Some(30),
3002                ..Options::default()
3003            },
3004            true,
3005        )
3006        .unwrap();
3007        assert!(save(&mut v, "bad", "{nope}", &Options::default(), false).is_err());
3008        assert!(save(&mut v, "", "{random:4}", &Options::default(), false).is_err());
3009        let all = saved(&v);
3010        assert_eq!(
3011            (all.len(), all[0].template.as_str(), all[0].options.max_len),
3012            (1, "{random:20}", Some(30))
3013        );
3014        add_rule(&mut v, "provider", "Instagram", "social").unwrap();
3015        v["recipe_default"] = serde_json::json!("social");
3016        assert!(add_rule(&mut v, "colour", "x", "social").is_err());
3017        assert!(add_rule(&mut v, "provider", " ", "social").is_err());
3018        assert!(add_rule(&mut v, "provider", "x", "ghost").is_err());
3019        assert!(remove(&mut v, "social"));
3020        assert!(!remove(&mut v, "social"));
3021        assert!(rules(&v).is_empty() && v.get("recipe_default").is_none() && saved(&v).is_empty());
3022    }
3023
3024    #[test]
3025    fn lists_and_facts_are_validated_and_replaced_by_name() {
3026        let mut v = vault();
3027        assert_eq!(
3028            save_list(
3029                &mut v,
3030                "pets",
3031                &["rex".into(), " rex ".into(), "tom".into(), "".into()],
3032                true
3033            )
3034            .unwrap(),
3035            2
3036        );
3037        assert!(save_list(&mut v, "pets", &["only".into()], false).is_err());
3038        assert!(save_list(&mut v, "bad name", &["a".into(), "b".into()], false).is_err());
3039        save_list(&mut v, "pets", &["a".into(), "b".into(), "c".into()], false).unwrap();
3040        let l = custom_lists(&v);
3041        assert_eq!((l.len(), l[0].1.len(), l[0].2), (1, 3, false));
3042        assert!(remove_list(&mut v, "pets") && !remove_list(&mut v, "pets"));
3043        assert!(!remove_list(&mut serde_json::json!({}), "x"));
3044        set_fact(&mut v, "pet", "rex", true).unwrap();
3045        set_fact(&mut v, "pet", "tom", false).unwrap();
3046        assert_eq!(
3047            facts(&v),
3048            vec![("pet".to_string(), "tom".to_string(), false)]
3049        );
3050        assert!(set_fact(&mut v, "Pet", "x", true).is_err());
3051        assert!(set_fact(&mut v, "pet", "", true).is_err());
3052        assert!(remove_fact(&mut v, "pet") && !remove_fact(&mut v, "pet"));
3053        assert!(!remove_fact(&mut serde_json::json!({}), "x"));
3054    }
3055
3056    #[test]
3057    fn the_entrys_own_recipe_beats_a_rule_which_beats_the_vault_default() {
3058        let mut v = vault();
3059        for n in ["own", "ruled", "default"] {
3060            save(&mut v, n, "{random:16}", &Options::default(), false).unwrap();
3061        }
3062        v["recipe_default"] = serde_json::json!("default");
3063        let mut e = entry();
3064        assert_eq!(resolve(&v, &e).unwrap().1, "vault default");
3065        add_rule(&mut v, "type", "ssh_key", "none").unwrap();
3066        add_rule(&mut v, "host", "instagram.com", "ruled").unwrap();
3067        assert_eq!(resolve(&v, &e).unwrap().0.name, "ruled");
3068        e["recipe"] = serde_json::json!("own");
3069        assert_eq!(resolve(&v, &e).unwrap().1, "this entry");
3070        e["recipe"] = serde_json::json!("none");
3071        assert!(resolve(&v, &e).is_none());
3072        e["recipe"] = serde_json::json!("ghost");
3073        assert!(resolve(&v, &e).is_none());
3074        // Every rule kind matches what it says; `none` switches recipes off for a match.
3075        e.as_object_mut().unwrap().remove("recipe");
3076        for (kind, value) in [
3077            ("provider", "instagram"),
3078            ("family", "meta"),
3079            ("tag", "social"),
3080            ("project", "Social"),
3081            ("project", "p1"),
3082            ("type", "password"),
3083        ] {
3084            let mut w = v.clone();
3085            w["recipe_rules"] = serde_json::json!([]);
3086            add_rule(&mut w, kind, value, "ruled").unwrap();
3087            assert_eq!(resolve(&w, &e).unwrap().1, format!("rule: {kind} {value}"));
3088        }
3089        let mut w = v.clone();
3090        w["recipe_rules"] = serde_json::json!([]);
3091        add_rule(&mut w, "provider", "Instagram", "none").unwrap();
3092        assert!(resolve(&w, &e).is_none());
3093        add_rule(&mut w, "host", "other.org", "ruled").unwrap();
3094        assert!(!rule_matches("host", "other.org", &e, &w) && !rule_matches("bogus", "x", &e, &w));
3095        assert!(
3096            remove_rule(&mut v, 1)
3097                && !remove_rule(&mut v, 9)
3098                && !remove_rule(&mut serde_json::json!({}), 1)
3099        );
3100    }
3101
3102    #[test]
3103    fn the_context_is_built_from_the_entry_the_facts_and_the_lists() {
3104        let mut v = vault();
3105        set_fact(&mut v, "pet", "rex", true).unwrap();
3106        save_list(&mut v, "food", &["kimchi".into(), "naan".into()], true).unwrap();
3107        let c = context(&v, Some(&entry()), "2026-11-15");
3108        assert_eq!(
3109            (
3110                c.provider.as_str(),
3111                c.host.as_str(),
3112                c.user.as_str(),
3113                c.project.as_str()
3114            ),
3115            ("Instagram", "www.instagram.com", "joy", "Social")
3116        );
3117        assert_eq!(
3118            (
3119                c.created.as_str(),
3120                c.counter,
3121                c.family.as_str(),
3122                c.secret_type.as_str()
3123            ),
3124            ("2018-11-11", 5, "meta", "password")
3125        );
3126        assert_eq!(c.avoid, ["old-1", "old-0"]);
3127        assert_eq!(c.vars["pet"], "rex");
3128        assert!(c.private_lists.contains("food") && c.lists["food"].len() == 2);
3129        assert_eq!(c.url, "https://www.instagram.com");
3130        let bare = context(&v, None, "2026-11-15");
3131        assert!(bare.provider.is_empty() && bare.counter == 1 && bare.now == "2026-11-15");
3132        // An entry with only the older `api_url` still has a host and an address.
3133        let old = context(
3134            &v,
3135            Some(&serde_json::json!({ "api_url": "https://api.x.test", "secretType": "" })),
3136            "2026-01-01",
3137        );
3138        assert_eq!(
3139            (
3140                old.host.as_str(),
3141                old.url.as_str(),
3142                old.secret_type.as_str()
3143            ),
3144            ("api.x.test", "https://api.x.test", "api_key")
3145        );
3146        let g = generated_by("social", 5, "2026-11-15");
3147        assert_eq!(
3148            (
3149                g["recipe"].as_str(),
3150                g["counter"].as_u64(),
3151                g["version"].as_u64()
3152            ),
3153            (Some("social"), Some(5), Some(1))
3154        );
3155    }
3156}