adler_core/site.rs
1//! Site definitions and the multi-signal detection model.
2//!
3//! A site is a target URL plus a list of [`Signal`]s. Each signal is an
4//! independent rule that, when triggered against a response, votes either
5//! for the account existing ([`SignalVerdict::Found`]) or not
6//! ([`SignalVerdict::NotFound`]). Non-triggering signals stay silent
7//! ([`SignalVerdict::Ambiguous`]).
8//!
9//! Aggregation is **negative-priority**: if any signal votes
10//! [`SignalVerdict::NotFound`] the verdict is [`MatchKind::NotFound`];
11//! otherwise if any votes [`SignalVerdict::Found`] it is
12//! [`MatchKind::Found`]; with no votes at all it is
13//! [`MatchKind::Uncertain`].
14//!
15//! A `NotFound` vote wins over a `Found` vote because negative signals are
16//! specific (an exact "user not found" message, a 404, a login redirect)
17//! while a bare `200 OK` is weak positive evidence. This matches how
18//! Sherlock-style detectors work: a site that always returns 200 and only
19//! differentiates via an error string is correctly read as `NotFound` when
20//! that string is present, even though the 200 also satisfies a
21//! `StatusFound` signal.
22
23use std::fmt;
24
25use serde::{Deserialize, Serialize};
26
27use crate::check::MatchKind;
28use crate::error::{Error, Result};
29use crate::username::Username;
30
31/// One site we can probe for the existence of an account.
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct Site {
34 /// Human-readable site name. Doubles as the stable filter key
35 /// (case-insensitive) used by CLI `--only` / `--exclude`.
36 pub name: String,
37 /// URL template containing a `{username}` placeholder.
38 pub url: UrlTemplate,
39 /// Ordered list of detection signals. Aggregated per the type-level docs.
40 /// Optional in source JSON when [`Site::engine`] is set — the engine's
41 /// signals are inherited at load time. After
42 /// [`crate::Registry`] resolution this vec is always non-empty (or the
43 /// site fails `validate`).
44 #[serde(default, skip_serializing_if = "Vec::is_empty")]
45 pub signals: Vec<Signal>,
46 /// One or more usernames known to exist on this site. Consumed by
47 /// `adler doctor` to verify the signal list still reports `Found`
48 /// for a real account. Accepts either a single string or an array
49 /// of strings in JSON; the doctor probes each in declaration order
50 /// and passes the present-check if **any** one of them resolves to
51 /// `Found`. Listing several is defensive — brand accounts or other
52 /// users that the site special-cases (e.g. Instagram's own
53 /// `instagram` account) shouldn't false-fail the whole site.
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub known_present: Option<KnownPresent>,
56 /// Username known to *not* exist on this site (optional). When omitted,
57 /// the doctor generates a random nonsense username instead.
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub known_absent: Option<String>,
60 /// Optional CSS-selector rules for pulling profile fields (name, bio,
61 /// avatar, …) out of a `Found` page. Only applied under `--enrich`.
62 #[serde(default, skip_serializing_if = "Vec::is_empty")]
63 pub extract: Vec<Extractor>,
64 /// Free-form classification tags for scanning a subset of the registry,
65 /// e.g. `"social"`, `"dev"`, `"region:ru"`. Matched by CLI `--tag`.
66 /// A site with no tags is universal (included unless a `--tag` filter
67 /// excludes it). Conventionally lowercase; `axis:value` is just a naming
68 /// convention, not enforced.
69 #[serde(default, skip_serializing_if = "Vec::is_empty")]
70 pub tags: Vec<String>,
71 /// Extra HTTP headers to send with the probe (e.g.
72 /// `{"X-IG-App-ID": "936619743392459"}` to unlock Instagram's
73 /// `web_profile_info` endpoint, or a custom `User-Agent`). Browser
74 /// backends apply them via `Network.setExtraHTTPHeaders` before
75 /// navigation; the raw-HTTP path doesn't read this yet.
76 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
77 pub request_headers: std::collections::BTreeMap<String, String>,
78 /// Optional regular expression describing usernames a site will
79 /// accept. When set and the scanned username doesn't match, the
80 /// site is skipped (the outcome is reported as `Uncertain` with
81 /// reason `UsernameNotAllowed`, without issuing any HTTP request).
82 /// Saves work AND avoids the false-positive class where a site
83 /// 404s on illegal usernames in ways our signal can't tell apart
84 /// from a missing account.
85 ///
86 /// Imported from Sherlock's `regexCheck` field; 95+ sites
87 /// upstream carry one (length bounds, character classes, etc.).
88 /// Validation at load time compiles the regex with `regex::Regex`
89 /// — a malformed pattern rejects the site rather than silently
90 /// degrading at scan time.
91 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub regex_check: Option<String>,
93 /// Name of a shared [`Engine`] this site inherits from (e.g.
94 /// `"Discourse"`, `"vBulletin"`). Forum-software platforms host
95 /// thousands of instances with identical detection signatures;
96 /// defining the signature once on an engine and inheriting it
97 /// keeps the registry small and the cost of a platform-wide
98 /// HTML change one fix instead of hundreds.
99 ///
100 /// At [`crate::Registry::validate`] time, engine fields are
101 /// merged *under* the site's own — anything the site declares
102 /// explicitly (`signals`, `request_headers`, `regex_check`) wins on
103 /// conflict; anything left empty / unset is filled from the
104 /// engine. An `engine: "X"` referring to a non-existent X is a
105 /// load-time error.
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub engine: Option<String>,
108 /// Characters the site silently drops from the username server-side
109 /// before matching — `john.doe` and `johndoe` resolve to the same
110 /// account on a site that lists `strip_bad_char: "."`. We pre-strip
111 /// at probe time so the URL we issue matches the canonical form
112 /// the site uses, avoiding a false `NotFound` on a benign
113 /// punctuation variant. Mirrors `WhatsMyName`'s field of the same
114 /// name; carried verbatim through `scripts/import_whatsmyname.py`.
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub strip_bad_char: Option<String>,
117 /// HTTP method used to probe this site. Defaults to GET — the vast
118 /// majority of sites are GET-probed. A few (Anilist's GraphQL API,
119 /// some Discord/Holopin endpoints) only answer to POST.
120 #[serde(default, skip_serializing_if = "is_default_method")]
121 pub request_method: HttpMethod,
122 /// Request body to send when [`Site::request_method`] is POST. The
123 /// literal `{username}` placeholder is substituted with the probe
124 /// username (same as URL templates). For GraphQL endpoints this
125 /// is typically the JSON `{"query":"...","variables":{"name":"{username}"}}`.
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub request_body: Option<String>,
128 /// Specific anti-bot mechanisms the site is known to deploy. A
129 /// richer alternative to the flat `bot-protected` tag — knowing
130 /// *which* protection a site uses lets future routing pick the
131 /// right backend (`Cloudflare` → cloudscraper-style bypass,
132 /// `CfFirewall` → full browser, `UserAuth` → skip, …) instead
133 /// of the all-or-nothing `bot-protected` decision.
134 ///
135 /// Independent of [`Site::tags`]: the existing `bot-protected`
136 /// tag stays as a back-compat shorthand and routes through the
137 /// browser backend exactly as before. When this vector is
138 /// non-empty Adler also treats the site as bot-protected
139 /// regardless of the tag.
140 #[serde(default, skip_serializing_if = "Vec::is_empty")]
141 pub protection: Vec<ProtectionKind>,
142}
143
144/// A specific anti-bot mechanism a site is known to deploy. Used to
145/// route probes to the right backend (raw HTTP, cloudscraper, full
146/// browser) and to inform users what blocks reliable detection.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(rename_all = "kebab-case")]
149#[non_exhaustive]
150pub enum ProtectionKind {
151 /// Standard Cloudflare WAF — challenge pages, `cf_clearance`
152 /// cookie. Bypassable by cloudscraper-style HTTP-level solvers
153 /// (e.g. `FlareSolverr`) without a full browser.
154 Cloudflare,
155 /// AWS `CloudFront` edge protection. Often UA-strictness only.
156 Cloudfront,
157 /// `DDoS-Guard` (used by some Russian/CIS hosts). Similar
158 /// challenge model to Cloudflare.
159 DdosGuard,
160 /// Cloudflare's JS-challenge ("I am under attack" mode).
161 /// Needs a JS-executing backend.
162 CfJsChallenge,
163 /// Cloudflare's WAF firewall blocking by signature, requiring
164 /// a real browser fingerprint to clear.
165 CfFirewall,
166 /// JA3/JA4 TLS-fingerprint matching (servers that classify the
167 /// client by its TLS handshake shape, not its UA).
168 TlsFingerprint,
169 /// `Anubis` proof-of-work challenge. Used by codeberg + a
170 /// growing number of FOSS projects to discourage scraping.
171 Anubis,
172 /// Generic captcha challenge (hCaptcha, reCAPTCHA, …). Almost
173 /// always blocking — `Uncertain` is the honest answer.
174 Captcha,
175 /// Trivial UA-strictness: rejects unknown User-Agent strings
176 /// but lets through a real-browser UA. Cheapest to bypass.
177 UserAgent,
178 /// Endpoint requires authentication; no anonymous probe path
179 /// exists. Practically unscrapable for OSINT.
180 UserAuth,
181}
182
183/// HTTP method used to probe a site. Only GET and POST are supported.
184#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
185#[serde(rename_all = "UPPERCASE")]
186pub enum HttpMethod {
187 /// Standard GET — the default for ~99% of sites in the registry.
188 #[default]
189 Get,
190 /// POST — for API endpoints that only differentiate accounts via a
191 /// body payload (GraphQL queries, form submissions). Pair with
192 /// [`Site::request_body`].
193 Post,
194}
195
196/// serde's `skip_serializing_if` callback contract requires a
197/// reference, so the by-value lint on a 1-byte type doesn't apply.
198#[allow(clippy::trivially_copy_pass_by_ref)]
199fn is_default_method(m: &HttpMethod) -> bool {
200 matches!(m, HttpMethod::Get)
201}
202
203/// Shared detection signature template for a family of sites that
204/// run the same forum / blog / wiki software (Discourse, vBulletin,
205/// `XenForo`, `MediaWiki`, …). Referenced from [`Site::engine`].
206///
207/// Engines carry the same kinds of fields as a [`Site`] does (just
208/// the inheritable ones — there's no per-engine `url`, that comes
209/// from the site itself). At registry load, the engine's fields
210/// are merged *under* each referring site's own fields: site wins
211/// on conflict.
212#[derive(Debug, Clone, Default, Serialize, Deserialize)]
213#[non_exhaustive]
214pub struct Engine {
215 /// Default detection signals for sites of this family.
216 /// Inherited only when the site itself declares no `signals`.
217 #[serde(default, skip_serializing_if = "Vec::is_empty")]
218 pub signals: Vec<Signal>,
219 /// Default extra HTTP headers (e.g. a User-Agent that the
220 /// platform accepts where the browser default gets blocked).
221 /// Merged with the site's own headers; site wins per-key.
222 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
223 pub request_headers: std::collections::BTreeMap<String, String>,
224 /// Default username-validity regex inherited only when the site
225 /// itself doesn't declare one.
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub regex_check: Option<String>,
228}
229
230impl Engine {
231 /// Compile-check the engine's own constraints — the inheritable
232 /// fields are subject to the same validation as a site's would
233 /// be.
234 ///
235 /// # Errors
236 /// Returns [`Error::InvalidSite`] when the engine name is
237 /// empty, a signal carries an empty marker, or any other
238 /// constraint a [`Site::validate`] would also flag.
239 pub fn validate(&self, name: &str) -> Result<()> {
240 if name.trim().is_empty() {
241 return Err(Error::InvalidSite {
242 reason: "engine name is empty".into(),
243 });
244 }
245 for signal in &self.signals {
246 signal.validate().map_err(|reason| Error::InvalidSite {
247 reason: format!("engine {name:?}: {reason}"),
248 })?;
249 }
250 if let Some(pat) = &self.regex_check {
251 if let Err(err) = regex::Regex::new(pat) {
252 tracing::warn!(
253 engine = %name, pattern = %pat, error = %err,
254 "engine regex_check did not compile; gate disabled for inheriting sites",
255 );
256 }
257 }
258 Ok(())
259 }
260
261 /// Fill the inheritable empty / unset fields of `site` from
262 /// this engine. Site fields are authoritative: if the site has
263 /// any signals at all, no engine signals are merged in.
264 /// `request_headers` merge per-key (site wins on per-key
265 /// conflict).
266 pub fn merge_into(&self, site: &mut Site) {
267 if site.signals.is_empty() {
268 site.signals.clone_from(&self.signals);
269 }
270 for (k, v) in &self.request_headers {
271 site.request_headers
272 .entry(k.clone())
273 .or_insert_with(|| v.clone());
274 }
275 if site.regex_check.is_none() {
276 site.regex_check.clone_from(&self.regex_check);
277 }
278 }
279}
280
281/// Known-present declaration on a [`Site`].
282///
283/// In JSON this is `untagged`: a plain string `"torvalds"` deserialises
284/// into [`KnownPresent::Single`], an array `["torvalds", "leomessi"]`
285/// into [`KnownPresent::Multiple`]. Serialisation preserves the form
286/// the site was authored with, so single-username entries stay
287/// compact.
288#[derive(Debug, Clone, Serialize, Deserialize)]
289#[serde(untagged)]
290#[non_exhaustive]
291pub enum KnownPresent {
292 /// Exactly one candidate username.
293 Single(String),
294 /// Two or more candidate usernames. Doctor passes if any resolve
295 /// to `Found`.
296 Multiple(Vec<String>),
297}
298
299impl KnownPresent {
300 /// View all candidate usernames as a slice, in declaration order.
301 /// Always non-empty for `Single`; may be empty for a hand-authored
302 /// `Multiple([])` (validation rejects that).
303 pub fn as_slice(&self) -> &[String] {
304 match self {
305 Self::Single(s) => std::slice::from_ref(s),
306 Self::Multiple(v) => v.as_slice(),
307 }
308 }
309
310 /// Primary candidate — the first declared username. `Single`
311 /// always has one; `Multiple` may be empty if a contributor wrote
312 /// `[]` (caught by [`Site::validate`]).
313 pub fn primary(&self) -> Option<&str> {
314 self.as_slice().first().map(String::as_str)
315 }
316}
317
318impl From<&str> for KnownPresent {
319 fn from(s: &str) -> Self {
320 Self::Single(s.to_owned())
321 }
322}
323
324impl From<String> for KnownPresent {
325 fn from(s: String) -> Self {
326 Self::Single(s)
327 }
328}
329
330/// Upper bound on a site name's length. Names appear in CLI output,
331/// CSV columns, and the validate-sites.yml workflow's run-summary
332/// table — keeping them short avoids both UI breakage and
333/// pathological CI artefacts.
334const NAME_MAX_LEN: usize = 80;
335
336/// True when `name` consists only of characters safe to interpolate
337/// into shell, CSV, and CLI argument contexts. Matches the JSON
338/// Schema pattern `^[\w][\w .()!/+-]*$`.
339fn is_safe_site_name(name: &str) -> bool {
340 let mut chars = name.chars();
341 match chars.next() {
342 Some(c) if c.is_ascii_alphanumeric() || c == '_' => {}
343 _ => return false,
344 }
345 chars.all(|c| {
346 c.is_ascii_alphanumeric()
347 || c == '_'
348 || c == ' '
349 || matches!(c, '.' | '(' | ')' | '!' | '/' | '+' | '-')
350 })
351}
352
353/// A rule for extracting one profile field from a page.
354#[derive(Debug, Clone, Serialize, Deserialize)]
355pub struct Extractor {
356 /// Output field name, e.g. `"avatar"`, `"bio"`, `"name"`.
357 pub field: String,
358 /// CSS selector locating the element.
359 pub selector: String,
360 /// Attribute to read (e.g. `"src"`, `"content"`). When omitted, the
361 /// element's trimmed text content is used.
362 #[serde(default, skip_serializing_if = "Option::is_none")]
363 pub attr: Option<String>,
364}
365
366impl Site {
367 /// Render the site URL for a given username.
368 ///
369 /// If the site declares [`strip_bad_char`](Site::strip_bad_char),
370 /// those characters are removed from `username` before
371 /// substitution — so a `john.doe` probe against a site that
372 /// lists `strip_bad_char: "."` actually hits the URL for
373 /// `johndoe`, matching the canonical form the site stores
374 /// internally.
375 pub fn url_for(&self, username: &Username) -> String {
376 let raw = username.as_str();
377 match self.strip_bad_char.as_deref() {
378 Some(chars) if !chars.is_empty() && raw.chars().any(|c| chars.contains(c)) => {
379 let stripped: String = raw.chars().filter(|c| !chars.contains(*c)).collect();
380 self.url.substitute(&stripped)
381 }
382 _ => self.url.substitute(raw),
383 }
384 }
385
386 /// Validate semantic invariants the type system can't enforce
387 /// (empty signals list, empty markers, empty status code sets).
388 pub fn validate(&self) -> Result<()> {
389 if self.name.trim().is_empty() {
390 return Err(Error::InvalidSite {
391 reason: "site name is empty".into(),
392 });
393 }
394 // Site names doubled as shell-interpolation values in the
395 // `validate-sites.yml` PR gate; an unsanitised name like
396 // `Foo"; rm -rf /; #` would have broken out of `"$name"`
397 // quoting and run arbitrary commands on the runner. Both the
398 // JSON Schema and this Rust loader enforce a safe character
399 // class (word chars plus a few visual punctuation marks) at
400 // every entry point.
401 if self.name.len() > NAME_MAX_LEN {
402 return Err(Error::InvalidSite {
403 reason: format!(
404 "site name longer than {NAME_MAX_LEN} chars: {:?}",
405 self.name
406 ),
407 });
408 }
409 if !is_safe_site_name(&self.name) {
410 return Err(Error::InvalidSite {
411 reason: format!(
412 "site name {:?} contains characters outside the allowed \
413 set (word chars, space, `.()!/+-`)",
414 self.name
415 ),
416 });
417 }
418 if self.signals.is_empty() {
419 return Err(Error::InvalidSite {
420 reason: format!("site {:?}: signals list is empty", self.name),
421 });
422 }
423 for signal in &self.signals {
424 signal.validate().map_err(|reason| Error::InvalidSite {
425 reason: format!("site {:?}: {reason}", self.name),
426 })?;
427 }
428 for extractor in &self.extract {
429 if extractor.field.trim().is_empty() {
430 return Err(Error::InvalidSite {
431 reason: format!("site {:?}: extractor has an empty field name", self.name),
432 });
433 }
434 if scraper::Selector::parse(&extractor.selector).is_err() {
435 return Err(Error::InvalidSite {
436 reason: format!(
437 "site {:?}: invalid CSS selector {:?} for field {:?}",
438 self.name, extractor.selector, extractor.field
439 ),
440 });
441 }
442 }
443 if let Some(pat) = &self.regex_check {
444 if let Err(err) = regex::Regex::new(pat) {
445 // Sherlock's regexes occasionally use lookarounds
446 // (e.g. `(?![.-])`), which the Rust `regex` crate
447 // doesn't support — it's a true regular-language
448 // engine for performance + DoS safety. Rather than
449 // reject the whole site over a username-gate the
450 // probe path will simply skip, downgrade to a warn
451 // and let the site keep working at the cost of one
452 // wasted probe per illegal username.
453 tracing::warn!(
454 site = %self.name, pattern = %pat, error = %err,
455 "regex_check did not compile; username-gate disabled for this site",
456 );
457 }
458 }
459 if let Some(kp) = &self.known_present {
460 if kp.as_slice().is_empty() {
461 return Err(Error::InvalidSite {
462 reason: format!("site {:?}: known_present is an empty list", self.name),
463 });
464 }
465 for name in kp.as_slice() {
466 if name.trim().is_empty() {
467 return Err(Error::InvalidSite {
468 reason: format!(
469 "site {:?}: known_present contains an empty username",
470 self.name
471 ),
472 });
473 }
474 }
475 }
476 for tag in &self.tags {
477 if tag.trim().is_empty() {
478 return Err(Error::InvalidSite {
479 reason: format!("site {:?}: tag is empty", self.name),
480 });
481 }
482 }
483 Ok(())
484 }
485}
486
487/// URL template containing a `{username}` placeholder.
488///
489/// Validated at construction: must contain the placeholder and start with
490/// `http://` or `https://`.
491#[derive(Debug, Clone, PartialEq, Eq)]
492pub struct UrlTemplate(String);
493
494const PLACEHOLDER: &str = "{username}";
495
496impl UrlTemplate {
497 /// Build a template, validating placeholder and scheme.
498 pub fn new(template: impl Into<String>) -> Result<Self> {
499 let t = template.into();
500 if !t.contains(PLACEHOLDER) {
501 return Err(Error::InvalidSite {
502 reason: format!("url template missing {PLACEHOLDER} placeholder: {t:?}"),
503 });
504 }
505 if !(t.starts_with("http://") || t.starts_with("https://")) {
506 return Err(Error::InvalidSite {
507 reason: format!("url template must start with http(s)://: {t:?}"),
508 });
509 }
510 Ok(Self(t))
511 }
512
513 fn substitute(&self, username: &str) -> String {
514 self.0.replace(PLACEHOLDER, username)
515 }
516
517 /// Borrow the raw template (with placeholder).
518 pub fn as_str(&self) -> &str {
519 &self.0
520 }
521}
522
523impl fmt::Display for UrlTemplate {
524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525 f.write_str(&self.0)
526 }
527}
528
529impl Serialize for UrlTemplate {
530 fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
531 self.0.serialize(s)
532 }
533}
534
535impl<'de> Deserialize<'de> for UrlTemplate {
536 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
537 let raw = String::deserialize(d)?;
538 Self::new(raw).map_err(serde::de::Error::custom)
539 }
540}
541
542/// A single piece of evidence about whether an account exists.
543///
544/// Signals are tagged in JSON by their `kind`. New variants will land for
545/// Phase 2 length-baseline scoring; the enum is `#[non_exhaustive]` so
546/// adding variants is not a breaking change.
547#[derive(Debug, Clone, Serialize, Deserialize)]
548#[serde(tag = "kind", rename_all = "snake_case")]
549#[non_exhaustive]
550pub enum Signal {
551 /// Votes **`Found`** when the response status is in `codes`.
552 StatusFound {
553 /// Status codes that vote for existence. Must be non-empty.
554 codes: Vec<u16>,
555 },
556 /// Votes **`NotFound`** when the response status is in `codes`.
557 StatusNotFound {
558 /// Status codes that vote for non-existence. Must be non-empty.
559 codes: Vec<u16>,
560 },
561 /// Votes **`Found`** when the response body contains `text`.
562 BodyPresent {
563 /// Substring whose appearance votes for existence. Must be non-empty.
564 text: String,
565 },
566 /// Votes **`NotFound`** when the response body contains `text`.
567 BodyAbsent {
568 /// Substring whose appearance votes for non-existence (e.g.
569 /// `"Profile not found"`). Must be non-empty.
570 text: String,
571 },
572 /// Votes **`NotFound`** when the final URL (post-redirect) contains
573 /// `fragment`.
574 RedirectAbsent {
575 /// Substring that, when present in the final URL, indicates the
576 /// account is missing (typically `"/login"` or `"/404"`). Must be
577 /// non-empty.
578 fragment: String,
579 },
580}
581
582/// Probe data extracted from an HTTP response, fed to each [`Signal`].
583///
584/// Internal detection plumbing — not part of the public API.
585#[derive(Debug)]
586pub(crate) struct Probe<'a> {
587 /// HTTP status code.
588 pub(crate) status: u16,
589 /// Final URL after redirects.
590 pub(crate) final_url: &'a str,
591 /// Decoded response body. Empty string when no body-using signal is configured.
592 pub(crate) body: &'a str,
593}
594
595/// What one signal concluded after looking at a probe.
596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
597pub(crate) enum SignalVerdict {
598 /// This signal votes that the account exists.
599 Found,
600 /// This signal votes that the account does not exist.
601 NotFound,
602 /// This signal had nothing to say (its trigger condition didn't match).
603 Ambiguous,
604}
605
606impl Signal {
607 /// True if this signal needs to inspect the response body. Used by the
608 /// client to skip body reads when no signal requires them.
609 pub(crate) fn needs_body(&self) -> bool {
610 matches!(self, Self::BodyPresent { .. } | Self::BodyAbsent { .. })
611 }
612
613 /// Evaluate this signal against a probe and produce a vote.
614 pub(crate) fn evaluate(&self, probe: &Probe<'_>) -> SignalVerdict {
615 match self {
616 Self::StatusFound { codes } => {
617 if codes.contains(&probe.status) {
618 SignalVerdict::Found
619 } else {
620 SignalVerdict::Ambiguous
621 }
622 }
623 Self::StatusNotFound { codes } => {
624 if codes.contains(&probe.status) {
625 SignalVerdict::NotFound
626 } else {
627 SignalVerdict::Ambiguous
628 }
629 }
630 Self::BodyPresent { text } => {
631 if probe.body.contains(text.as_str()) {
632 SignalVerdict::Found
633 } else {
634 SignalVerdict::Ambiguous
635 }
636 }
637 Self::BodyAbsent { text } => {
638 if probe.body.contains(text.as_str()) {
639 SignalVerdict::NotFound
640 } else {
641 SignalVerdict::Ambiguous
642 }
643 }
644 Self::RedirectAbsent { fragment } => {
645 if probe.final_url.contains(fragment.as_str()) {
646 SignalVerdict::NotFound
647 } else {
648 SignalVerdict::Ambiguous
649 }
650 }
651 }
652 }
653
654 /// Human-readable description of why this signal fired against `probe`,
655 /// for verdict explainability. Only meaningful for a signal that voted
656 /// (i.e. didn't return [`SignalVerdict::Ambiguous`]); the caller filters.
657 pub(crate) fn describe_match(&self, probe: &Probe<'_>) -> String {
658 match self {
659 Self::StatusFound { .. } => format!("HTTP {} (status_found)", probe.status),
660 Self::StatusNotFound { .. } => format!("HTTP {} (status_not_found)", probe.status),
661 Self::BodyPresent { text } => format!("body contains {text:?} (body_present)"),
662 Self::BodyAbsent { text } => format!("body contains {text:?} (body_absent)"),
663 Self::RedirectAbsent { fragment } => {
664 format!("final URL contains {fragment:?} (redirect_absent)")
665 }
666 }
667 }
668
669 fn validate(&self) -> std::result::Result<(), String> {
670 match self {
671 Self::StatusFound { codes } | Self::StatusNotFound { codes } => {
672 if codes.is_empty() {
673 return Err("status signal codes list is empty".into());
674 }
675 }
676 Self::BodyPresent { text } | Self::BodyAbsent { text } => {
677 if text.is_empty() {
678 return Err("body signal text is empty".into());
679 }
680 }
681 Self::RedirectAbsent { fragment } => {
682 if fragment.is_empty() {
683 return Err("redirect signal fragment is empty".into());
684 }
685 }
686 }
687 Ok(())
688 }
689}
690
691/// Aggregate per-signal verdicts into a final [`MatchKind`].
692///
693/// Negative-priority counting: any `NotFound` vote → `NotFound`; otherwise
694/// any `Found` vote → `Found`; no votes at all → `Uncertain`. See the module
695/// docs for why a `NotFound` vote outranks a `Found` vote.
696pub(crate) fn aggregate<I>(verdicts: I) -> MatchKind
697where
698 I: IntoIterator<Item = SignalVerdict>,
699{
700 let mut found = false;
701 let mut not_found = false;
702 for v in verdicts {
703 match v {
704 SignalVerdict::Found => found = true,
705 SignalVerdict::NotFound => not_found = true,
706 SignalVerdict::Ambiguous => {}
707 }
708 }
709 if not_found {
710 MatchKind::NotFound
711 } else if found {
712 MatchKind::Found
713 } else {
714 MatchKind::Uncertain
715 }
716}
717
718#[cfg(test)]
719mod tests {
720 use super::*;
721
722 fn site_with(signals: Vec<Signal>) -> Site {
723 Site {
724 name: "Example".into(),
725 url: UrlTemplate::new("https://example.com/{username}").unwrap(),
726 signals,
727 known_present: None,
728 known_absent: None,
729 extract: Vec::new(),
730 tags: Vec::new(),
731 request_headers: std::collections::BTreeMap::new(),
732 regex_check: None,
733 engine: None,
734 strip_bad_char: None,
735 request_method: crate::site::HttpMethod::Get,
736 request_body: None,
737 protection: Vec::new(),
738 }
739 }
740
741 #[test]
742 fn url_template_substitutes_placeholder() {
743 let user = Username::new("alice").unwrap();
744 let site = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
745 assert_eq!(site.url_for(&user), "https://example.com/alice");
746 }
747
748 #[test]
749 fn url_for_strips_bad_chars_before_substitution() {
750 let user = Username::new("john.doe").unwrap();
751 let mut site = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
752 site.strip_bad_char = Some(".".into());
753 assert_eq!(site.url_for(&user), "https://example.com/johndoe");
754 }
755
756 #[test]
757 fn url_for_strip_bad_char_noop_when_no_match() {
758 let user = Username::new("alice").unwrap();
759 let mut site = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
760 site.strip_bad_char = Some(".".into());
761 assert_eq!(site.url_for(&user), "https://example.com/alice");
762 }
763
764 #[test]
765 fn url_template_rejects_missing_placeholder() {
766 assert!(UrlTemplate::new("https://example.com/users/").is_err());
767 }
768
769 #[test]
770 fn url_template_rejects_bad_scheme() {
771 assert!(UrlTemplate::new("ftp://example.com/{username}").is_err());
772 }
773
774 #[test]
775 fn validate_requires_non_empty_signals() {
776 let err = site_with(vec![]).validate().unwrap_err();
777 assert!(err.to_string().contains("signals list is empty"));
778 }
779
780 #[test]
781 fn validate_rejects_empty_status_codes() {
782 let err = site_with(vec![Signal::StatusFound { codes: vec![] }])
783 .validate()
784 .unwrap_err();
785 assert!(err.to_string().contains("status signal"));
786 }
787
788 #[test]
789 fn validate_rejects_empty_body_text() {
790 let err = site_with(vec![Signal::BodyAbsent {
791 text: String::new(),
792 }])
793 .validate()
794 .unwrap_err();
795 assert!(err.to_string().contains("body signal"));
796 }
797
798 #[test]
799 fn validate_rejects_empty_redirect_fragment() {
800 let err = site_with(vec![Signal::RedirectAbsent {
801 fragment: String::new(),
802 }])
803 .validate()
804 .unwrap_err();
805 assert!(err.to_string().contains("redirect signal"));
806 }
807
808 #[test]
809 fn validate_rejects_shell_metacharacters_in_name() {
810 // The validate-sites.yml workflow used to inject `--only "$name"`
811 // where `$name` came from PR-controlled sites.json. A name like
812 // `Foo"; rm -rf /; #` would have broken out of `"..."` quoting
813 // and executed on the runner. Schema + this loader both enforce
814 // a safe character class; verify a representative selection of
815 // dangerous chars is rejected.
816 for bad in [
817 "Foo\"; rm -rf /; #",
818 "Bar$(curl evil.com)",
819 "Baz`whoami`",
820 "Qux\\nfoo",
821 "back\\slash",
822 "pipe|ish",
823 "semi;colon",
824 "amp&and",
825 "lt<gt>",
826 ] {
827 let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
828 s.name = bad.into();
829 let err = s.validate().unwrap_err();
830 assert!(
831 err.to_string()
832 .contains("characters outside the allowed set"),
833 "expected unsafe-name rejection for {bad:?}, got {err}",
834 );
835 }
836 }
837
838 #[test]
839 fn validate_accepts_real_world_site_names() {
840 // Cross-check the validation against names we actually ship.
841 for ok in [
842 "GitHub",
843 "Steam Community (User)",
844 "X / Twitter",
845 "osu!",
846 "Eintracht Frankfurt Forum",
847 "Archive of Our Own",
848 "Career.habr",
849 "fl",
850 "GitLab.com",
851 "Sbazar.cz",
852 ] {
853 let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
854 s.name = ok.into();
855 assert!(s.validate().is_ok(), "expected {ok:?} to validate");
856 }
857 }
858
859 #[test]
860 fn validate_rejects_overlong_name() {
861 let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
862 s.name = "A".repeat(100);
863 let err = s.validate().unwrap_err();
864 assert!(err.to_string().contains("longer than"));
865 }
866
867 #[test]
868 fn validate_accepts_well_formed_regex_check() {
869 let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
870 s.regex_check = Some("^[a-zA-Z0-9_-]{3,40}$".into());
871 assert!(s.validate().is_ok());
872 }
873
874 #[test]
875 fn validate_tolerates_unsupported_regex_features() {
876 // Sherlock-imported regexes occasionally use lookarounds
877 // (e.g. `(?!...)`) that Rust's `regex` crate can't compile —
878 // those sites should still load, with the username-gate
879 // silently disabled rather than rejecting the whole site.
880 let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
881 s.regex_check = Some("^(?![.-])[a-zA-Z0-9_.-]{3,20}$".into());
882 assert!(
883 s.validate().is_ok(),
884 "lookaround-bearing regex should warn, not reject the site"
885 );
886 }
887
888 #[test]
889 fn signal_status_found_votes_only_on_match() {
890 let signal = Signal::StatusFound { codes: vec![200] };
891 let probe = Probe {
892 status: 200,
893 final_url: "https://example.com/alice",
894 body: "",
895 };
896 assert_eq!(signal.evaluate(&probe), SignalVerdict::Found);
897 let probe = Probe {
898 status: 404,
899 ..probe
900 };
901 assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
902 }
903
904 #[test]
905 fn signal_status_not_found_votes_only_on_match() {
906 let signal = Signal::StatusNotFound { codes: vec![404] };
907 let probe = Probe {
908 status: 404,
909 final_url: "",
910 body: "",
911 };
912 assert_eq!(signal.evaluate(&probe), SignalVerdict::NotFound);
913 let probe = Probe {
914 status: 200,
915 ..probe
916 };
917 assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
918 }
919
920 #[test]
921 fn signal_body_absent_votes_not_found_when_text_present() {
922 let signal = Signal::BodyAbsent {
923 text: "Profile not found".into(),
924 };
925 let probe = Probe {
926 status: 200,
927 final_url: "",
928 body: "<h1>Profile not found</h1>",
929 };
930 assert_eq!(signal.evaluate(&probe), SignalVerdict::NotFound);
931 let probe = Probe {
932 body: "<h1>Welcome alice</h1>",
933 ..probe
934 };
935 assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
936 }
937
938 #[test]
939 fn signal_redirect_absent_inspects_final_url() {
940 let signal = Signal::RedirectAbsent {
941 fragment: "/login".into(),
942 };
943 let probe = Probe {
944 status: 200,
945 final_url: "https://example.com/login?next=/alice",
946 body: "",
947 };
948 assert_eq!(signal.evaluate(&probe), SignalVerdict::NotFound);
949 let probe = Probe {
950 final_url: "https://example.com/alice",
951 ..probe
952 };
953 assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
954 }
955
956 #[test]
957 fn aggregate_found_when_only_found_signals_fire() {
958 let kind = aggregate([SignalVerdict::Found, SignalVerdict::Ambiguous]);
959 assert_eq!(kind, MatchKind::Found);
960 }
961
962 #[test]
963 fn aggregate_not_found_when_only_not_found_signals_fire() {
964 let kind = aggregate([SignalVerdict::NotFound, SignalVerdict::Ambiguous]);
965 assert_eq!(kind, MatchKind::NotFound);
966 }
967
968 #[test]
969 fn aggregate_not_found_wins_over_found() {
970 // Negative-priority: a NotFound vote outranks a Found vote.
971 let kind = aggregate([SignalVerdict::Found, SignalVerdict::NotFound]);
972 assert_eq!(kind, MatchKind::NotFound);
973 }
974
975 #[test]
976 fn aggregate_uncertain_when_no_signals_fire() {
977 let kind = aggregate([SignalVerdict::Ambiguous, SignalVerdict::Ambiguous]);
978 assert_eq!(kind, MatchKind::Uncertain);
979 }
980
981 #[test]
982 fn aggregate_empty_is_uncertain() {
983 let kind = aggregate(std::iter::empty());
984 assert_eq!(kind, MatchKind::Uncertain);
985 }
986
987 #[test]
988 fn needs_body_is_true_only_for_body_signals() {
989 assert!(!Signal::StatusFound { codes: vec![200] }.needs_body());
990 assert!(!Signal::StatusNotFound { codes: vec![404] }.needs_body());
991 assert!(
992 !Signal::RedirectAbsent {
993 fragment: "/login".into()
994 }
995 .needs_body()
996 );
997 assert!(Signal::BodyPresent { text: "x".into() }.needs_body());
998 assert!(Signal::BodyAbsent { text: "x".into() }.needs_body());
999 }
1000
1001 #[test]
1002 fn deserializes_signal_list() {
1003 let json = r#"{
1004 "name": "GitHub",
1005 "url": "https://github.com/{username}",
1006 "signals": [
1007 { "kind": "status_found", "codes": [200] },
1008 { "kind": "status_not_found", "codes": [404] }
1009 ]
1010 }"#;
1011 let site: Site = serde_json::from_str(json).unwrap();
1012 assert_eq!(site.name, "GitHub");
1013 assert_eq!(site.signals.len(), 2);
1014 site.validate().unwrap();
1015 }
1016
1017 proptest::proptest! {
1018 /// For any mix of per-signal verdicts, aggregation obeys the
1019 /// negative-priority spec: any NotFound wins; else any Found; else
1020 /// Uncertain.
1021 #[test]
1022 fn aggregate_matches_negative_priority_spec(
1023 votes in proptest::collection::vec(
1024 proptest::prop_oneof![
1025 proptest::strategy::Just(SignalVerdict::Found),
1026 proptest::strategy::Just(SignalVerdict::NotFound),
1027 proptest::strategy::Just(SignalVerdict::Ambiguous),
1028 ],
1029 0..16,
1030 ),
1031 ) {
1032 let kind = aggregate(votes.iter().copied());
1033 let expected = if votes.contains(&SignalVerdict::NotFound) {
1034 MatchKind::NotFound
1035 } else if votes.contains(&SignalVerdict::Found) {
1036 MatchKind::Found
1037 } else {
1038 MatchKind::Uncertain
1039 };
1040 proptest::prop_assert_eq!(kind, expected);
1041 }
1042 }
1043}