vacant 0.3.0

Fast domain availability checker. Asks authoritative TLD nameservers directly instead of WHOIS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// ABOUTME: TOML-driven rules engine: zone matching plus per-zone label predicates.
// ABOUTME: Ports the Python rules.py / checker pre-DNS path so the Rust engine can A/B against it.

use std::collections::HashMap;

use regex::Regex;
use serde::Deserialize;
use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
    Available,
    Registered,
    Reserved,
    Invalid,
    Unknown,
}

impl Status {
    pub fn as_str(self) -> &'static str {
        match self {
            Status::Available => "available",
            Status::Registered => "registered",
            Status::Reserved => "reserved",
            Status::Invalid => "invalid",
            Status::Unknown => "unknown",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleViolation {
    pub rule: String,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZoneMatch {
    pub zone: String,
    pub label: String,
    pub registered: String,
    pub extra: Vec<String>,
}

pub enum MatchResult<'a> {
    Found {
        zone_match: ZoneMatch,
        policy: &'a ZonePolicy,
    },
    Fallback {
        zone: String,
        label: String,
        registered: String,
        policy: &'a ZonePolicy,
    },
}

/// What the rule layer can determine before any DNS work.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreCheck {
    /// The label and zone resolved cleanly; the caller should now do DNS lookups.
    Proceed {
        zone: String,
        label: String,
        registered: String,
        rdap: Option<String>,
    },
    /// Short-circuit answer; caller skips DNS.
    Verdict {
        status: Status,
        detail: String,
        zone: String,
        registered: String,
    },
}

#[derive(Debug)]
struct Predicate {
    name: &'static str,
    message: String,
    test: PredicateFn,
}

#[derive(Debug)]
enum PredicateFn {
    MinLength(usize),
    MaxLength(usize),
    Ldh,
    NoEdgeHyphen,
    NoTaggedHyphen,
    Pattern(Regex),
    ForbidPattern(Regex),
}

impl Predicate {
    fn check(&self, label: &str) -> bool {
        match &self.test {
            PredicateFn::MinLength(n) => label.chars().count() >= *n,
            PredicateFn::MaxLength(n) => label.chars().count() <= *n,
            PredicateFn::Ldh => {
                !label.is_empty()
                    && label
                        .chars()
                        .all(|c| c.is_ascii() && (c.is_ascii_alphanumeric() || c == '-'))
            }
            PredicateFn::NoEdgeHyphen => !(label.starts_with('-') || label.ends_with('-')),
            PredicateFn::NoTaggedHyphen => {
                if label.starts_with("xn--") {
                    return true;
                }
                let bytes = label.as_bytes();
                !(bytes.len() >= 4 && bytes[2] == b'-' && bytes[3] == b'-')
            }
            PredicateFn::Pattern(re) => re.is_match(label) && full_match(re, label),
            PredicateFn::ForbidPattern(re) => !re.is_match(label),
        }
    }
}

fn full_match(re: &Regex, label: &str) -> bool {
    match re.find(label) {
        Some(m) => m.start() == 0 && m.end() == label.len(),
        None => false,
    }
}

#[derive(Debug)]
pub struct ZonePolicy {
    pub zone: String,
    predicates: Vec<Predicate>,
    pub rdap: Option<String>,
}

impl ZonePolicy {
    pub fn evaluate(&self, label: &str) -> Option<RuleViolation> {
        for p in &self.predicates {
            if !p.check(label) {
                return Some(RuleViolation {
                    rule: p.name.to_string(),
                    message: p.message.clone(),
                });
            }
        }
        None
    }
}

#[derive(Debug)]
pub struct RuleSet {
    pub default: ZonePolicy,
    pub zones: HashMap<String, ZonePolicy>,
}

impl std::str::FromStr for RuleSet {
    type Err = LoadError;
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let raw: RawDocument = toml::from_str(text)?;
        let default_spec = raw.default.unwrap_or_default();
        let default = build_policy("*", &default_spec, &default_spec)?;

        let mut zones = HashMap::new();
        if let Some(table) = raw.zone {
            for (name, spec) in table {
                let merged = merge(&default_spec, &spec);
                let lower = name.to_ascii_lowercase();
                let policy = build_policy(&lower, &merged, &default_spec)?;
                zones.insert(lower, policy);
            }
        }
        Ok(RuleSet { default, zones })
    }
}

impl RuleSet {
    pub fn policy_for(&self, zone: &str) -> &ZonePolicy {
        self.zones
            .get(&zone.to_ascii_lowercase())
            .unwrap_or(&self.default)
    }

    pub fn match_zone(&self, domain: &str) -> Option<ZoneMatch> {
        let cleaned = normalize(domain);
        if cleaned.is_empty() || self.zones.contains_key(&cleaned) {
            return None;
        }
        let labels: Vec<&str> = cleaned.split('.').collect();
        for j in 1..labels.len() {
            let candidate = labels[j..].join(".");
            if self.zones.contains_key(&candidate) {
                let label = labels[j - 1].to_string();
                let registered = labels[j - 1..].join(".");
                let extra = labels[..j - 1].iter().map(|s| s.to_string()).collect();
                return Some(ZoneMatch {
                    zone: candidate,
                    label,
                    registered,
                    extra,
                });
            }
        }
        None
    }

    /// Run the full pre-DNS pipeline (the Python checker.check() prologue, end-to-end).
    pub fn precheck(&self, raw_domain: &str) -> PreCheck {
        let cleaned = normalize(raw_domain);
        if !cleaned.contains('.') {
            return PreCheck::Verdict {
                status: Status::Invalid,
                detail: "input has no TLD".to_string(),
                zone: String::new(),
                registered: cleaned,
            };
        }
        if cleaned.split('.').any(|l| l.is_empty()) {
            return PreCheck::Verdict {
                status: Status::Invalid,
                detail: "malformed: empty label (leading/trailing dot or '..')".to_string(),
                zone: String::new(),
                registered: cleaned,
            };
        }
        if self.zones.contains_key(&cleaned) {
            return PreCheck::Verdict {
                status: Status::Invalid,
                detail: format!("'{cleaned}' is a registry suffix, not a registrable name"),
                zone: cleaned.clone(),
                registered: cleaned,
            };
        }

        let m = match self.match_zone(&cleaned) {
            Some(m) => m,
            None => {
                let tld = cleaned.rsplit('.').next().unwrap_or("");
                return PreCheck::Verdict {
                    status: Status::Invalid,
                    detail: format!("unknown TLD '.{tld}' (not in the public suffix list)"),
                    zone: tld.to_string(),
                    registered: cleaned,
                };
            }
        };
        if !m.extra.is_empty() {
            let detail = format!(
                "'{cleaned}' is below the registrable level for zone '{}' (registrable name would be '{}')",
                m.zone, m.registered
            );
            return PreCheck::Verdict {
                status: Status::Invalid,
                detail,
                zone: m.zone,
                registered: m.registered,
            };
        }
        let policy = self.policy_for(&m.zone);
        let (zone, label, registered) = (m.zone, m.label, m.registered);

        if let Some(violation) = policy.evaluate(&label) {
            return PreCheck::Verdict {
                status: Status::Reserved,
                detail: format!("{}: {}", violation.rule, violation.message),
                zone,
                registered,
            };
        }

        PreCheck::Proceed {
            zone,
            label,
            registered,
            rdap: policy.rdap.clone(),
        }
    }
}

fn normalize(domain: &str) -> String {
    domain.trim().trim_end_matches('.').to_ascii_lowercase()
}

#[derive(Debug, Default, Deserialize)]
struct RawDocument {
    #[serde(default)]
    default: Option<RawSpec>,
    #[serde(default)]
    zone: Option<HashMap<String, RawSpec>>,
}

#[derive(Debug, Default, Clone, Deserialize)]
struct RawSpec {
    #[serde(default)]
    min_length: Option<i64>,
    #[serde(default)]
    max_length: Option<i64>,
    #[serde(default)]
    charset: Option<String>,
    #[serde(default)]
    no_edge_hyphen: Option<bool>,
    #[serde(default)]
    no_tagged_hyphen: Option<bool>,
    #[serde(default)]
    pattern: Option<String>,
    #[serde(default)]
    forbid_pattern: Option<String>,
    #[serde(default)]
    rdap: Option<String>,
}

fn merge(default: &RawSpec, override_: &RawSpec) -> RawSpec {
    RawSpec {
        min_length: override_.min_length.or(default.min_length),
        max_length: override_.max_length.or(default.max_length),
        charset: override_
            .charset
            .clone()
            .or_else(|| default.charset.clone()),
        no_edge_hyphen: override_.no_edge_hyphen.or(default.no_edge_hyphen),
        no_tagged_hyphen: override_.no_tagged_hyphen.or(default.no_tagged_hyphen),
        pattern: override_
            .pattern
            .clone()
            .or_else(|| default.pattern.clone()),
        forbid_pattern: override_
            .forbid_pattern
            .clone()
            .or_else(|| default.forbid_pattern.clone()),
        rdap: override_.rdap.clone().or_else(|| default.rdap.clone()),
    }
}

fn build_policy(zone: &str, spec: &RawSpec, _root: &RawSpec) -> Result<ZonePolicy, LoadError> {
    let mut predicates = Vec::new();
    if let Some(n) = spec.min_length {
        let n = usize::try_from(n).map_err(|_| LoadError::BadValue("min_length"))?;
        predicates.push(Predicate {
            name: "min-length",
            message: format!("label must be at least {n} characters"),
            test: PredicateFn::MinLength(n),
        });
    }
    if let Some(n) = spec.max_length {
        let n = usize::try_from(n).map_err(|_| LoadError::BadValue("max_length"))?;
        predicates.push(Predicate {
            name: "max-length",
            message: format!("label must be at most {n} characters"),
            test: PredicateFn::MaxLength(n),
        });
    }
    if let Some(charset) = &spec.charset {
        match charset.as_str() {
            "ldh" => predicates.push(Predicate {
                name: "charset-ldh",
                message: "label must contain only letters, digits, and hyphens".to_string(),
                test: PredicateFn::Ldh,
            }),
            other => return Err(LoadError::UnknownCharset(other.to_string())),
        }
    }
    if spec.no_edge_hyphen.unwrap_or(false) {
        predicates.push(Predicate {
            name: "no-edge-hyphen",
            message: "label cannot start or end with '-'".to_string(),
            test: PredicateFn::NoEdgeHyphen,
        });
    }
    if spec.no_tagged_hyphen.unwrap_or(false) {
        predicates.push(Predicate {
            name: "no-tagged-hyphen",
            message: "label cannot have '-' in positions 3 and 4".to_string(),
            test: PredicateFn::NoTaggedHyphen,
        });
    }
    if let Some(pat) = &spec.pattern {
        let re = Regex::new(pat).map_err(LoadError::Regex)?;
        predicates.push(Predicate {
            name: "pattern",
            message: format!("label must match {pat}"),
            test: PredicateFn::Pattern(re),
        });
    }
    if let Some(pat) = &spec.forbid_pattern {
        let re = Regex::new(pat).map_err(LoadError::Regex)?;
        predicates.push(Predicate {
            name: "forbid-pattern",
            message: format!("label must not match {pat}"),
            test: PredicateFn::ForbidPattern(re),
        });
    }
    Ok(ZonePolicy {
        zone: zone.to_string(),
        predicates,
        rdap: spec.rdap.clone(),
    })
}

#[derive(Debug, Error)]
pub enum LoadError {
    #[error("toml parse: {0}")]
    Toml(#[from] toml::de::Error),
    #[error("regex: {0}")]
    Regex(regex::Error),
    #[error("unknown charset: {0}")]
    UnknownCharset(String),
    #[error("invalid value for {0}")]
    BadValue(&'static str),
}