domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! Shared export row building logic.
//!
//! This module provides a unified way to fetch all data for a single export row,
//! eliminating duplication between CSV and JSONL exporters.

use anyhow::Result;
use sqlx::Row;

use crate::storage::DbPool;

use super::queries::{fetch_filtered_http_headers, fetch_string_list, HttpHeadersTable};

const EXPORT_LIMIT: i64 = crate::config::MAX_EXPORT_RELATED_RECORDS;

/// A single nameserver record.
#[derive(Debug, Clone)]
pub struct NameserverRecord {
    pub nameserver: String,
}

/// A single DNS TXT record.
#[derive(Debug, Clone)]
pub struct TxtRecord {
    pub record_type: String,
    pub record_value: String,
}

/// A single DNS MX record.
#[derive(Debug, Clone)]
pub struct MxRecord {
    pub priority: i64,
    pub mail_exchange: String,
}

/// A single structured data entry (JSON-LD, Open Graph, Twitter Card).
#[derive(Debug, Clone)]
pub struct StructuredDataEntry {
    pub data_type: String,
    pub property_name: String,
    pub property_value: String,
}

/// A single social media link with extracted identifier.
#[derive(Debug, Clone)]
pub struct SocialMediaLink {
    pub platform: String,
    pub profile_url: String,
    pub identifier: Option<String>,
}

/// A contact link (mailto/tel).
#[derive(Debug, Clone)]
pub struct ContactLinkRecord {
    pub contact_type: String,
    pub contact_value: String,
}

/// An exposed secret detected in HTML, with optional decoded JWT claims.
#[derive(Debug, Clone)]
pub struct ExposedSecretRecord {
    pub secret_type: String,
    pub matched_value: String,
    pub severity: String,
    pub location: String,
    pub context: Option<String>,
    // Decoded JWT claims (populated only for jwt/jwt-base64 secrets)
    pub jwt_algorithm: Option<String>,
    pub jwt_issuer: Option<String>,
    pub jwt_subject: Option<String>,
    pub jwt_audience: Option<String>,
    pub jwt_expiration_ms: Option<i64>,
    pub jwt_issued_at_ms: Option<i64>,
    pub jwt_header_json: Option<String>,
    pub jwt_payload_json: Option<String>,
}

/// A partial failure (DNS/TLS error that didn't block processing).
#[derive(Debug, Clone)]
pub struct PartialFailure {
    pub error_type: String,
    pub error_message: String,
}

/// An HTTP header name-value pair.
#[derive(Debug, Clone)]
pub struct HttpHeader {
    pub name: String,
    pub value: String,
}

/// Main row data from the `url_status` table.
#[derive(Debug)]
pub struct MainRowData {
    pub id: i64,
    pub initial_domain: String,
    pub final_domain: String,
    pub initial_url: Option<String>,
    pub final_url: Option<String>,
    pub ip_address: String,
    pub reverse_dns: Option<String>,
    pub status: u16,
    pub status_desc: String,
    pub response_time: f64,
    pub title: String,
    pub description: Option<String>,
    pub meta_robots: Option<String>,
    pub tls_version: Option<String>,
    pub ssl_cert_subject: Option<String>,
    pub ssl_cert_issuer: Option<String>,
    pub ssl_cert_valid_to_ms: Option<i64>,
    pub cipher_suite: Option<String>,
    pub key_algorithm: Option<String>,
    pub spf_record: Option<String>,
    pub dmarc_record: Option<String>,
    pub mta_sts_record: Option<String>,
    pub tls_rpt_record: Option<String>,
    pub bimi_record: Option<String>,
    pub hsts_max_age: Option<i64>,
    pub hsts_include_subdomains: Option<bool>,
    pub hsts_preload: Option<bool>,
    pub cdn_provider: Option<String>,
    pub timestamp: i64,
    pub run_id: Option<String>,
    pub body_sha256: Option<String>,
    pub content_length: Option<i64>,
    pub http_version: Option<String>,
    pub content_type: Option<String>,
    pub canonical_url: Option<String>,
    pub cert_fingerprint_sha256: Option<String>,
    /// True when the response body hit `MAX_RESPONSE_BODY_SIZE` and was truncated before
    /// secret-detection/hashing ran (see migration `0009_secrets_scan_completeness.sql`).
    pub body_truncated: bool,
}

/// A single redirect entry.
#[derive(Debug)]
pub struct RedirectEntry {
    pub redirect_url: String,
    pub sequence_order: i64,
    pub http_status: Option<i64>,
}

/// `GeoIP` data for an export row.
#[derive(Debug, Default)]
pub struct GeoIpData {
    pub country_code: Option<String>,
    pub country_name: Option<String>,
    pub region: Option<String>,
    pub city: Option<String>,
    pub latitude: Option<f64>,
    pub longitude: Option<f64>,
    pub asn: Option<i64>,
    pub asn_org: Option<String>,
}

/// WHOIS data for an export row.
#[derive(Debug, Default)]
pub struct WhoisData {
    pub registrar: Option<String>,
    pub creation_date_ms: Option<i64>,
    pub expiration_date_ms: Option<i64>,
    pub registrant_country: Option<String>,
}

/// Technology record for export (avoids comma/colon delimiter corruption).
#[derive(Debug)]
pub struct TechnologyRecord {
    pub name: String,
    pub version: Option<String>,
    pub category: Option<String>,
    pub is_implied: bool,
    pub detection_source: Option<String>,
}

/// Analytics ID record for export (avoids comma/colon delimiter corruption).
#[derive(Debug)]
pub struct AnalyticsIdRecord {
    pub provider: String,
    pub tracking_id: String,
}

/// Host from a page `<script src>` attribute.
#[derive(Debug, Clone)]
pub struct ScriptHostRecord {
    pub host: String,
    pub registrable_domain: Option<String>,
    pub is_first_party: bool,
}

/// CAA record for export.
#[derive(Debug)]
pub struct CaaRecord {
    pub flag: i64,
    pub tag: String,
    pub value: String,
}

/// All data for a single export row.
///
/// This struct consolidates all satellite data fetched from various tables
/// for a single URL record, providing a unified view for exporters.
#[derive(Debug)]
pub struct ExportRow {
    /// Main row data from `url_status` table
    pub main: MainRowData,

    /// Redirect chain
    pub redirects: Vec<RedirectEntry>,
    pub redirect_count: usize,
    pub final_redirect_url: String,

    /// Technologies formatted as comma-separated `name:version` values for CSV export.
    /// JSONL uses [`Self::technologies`] for structured output.
    pub technologies_str: String,
    /// Categories for detected technologies (comma-separated, parallel to `technologies_str` order)
    pub technology_categories_str: String,
    pub technology_count: usize,
    /// Technologies as structured data (safe from delimiter corruption)
    pub technologies: Vec<TechnologyRecord>,

    /// Certificate SANs
    pub certificate_sans_str: String,
    pub certificate_san_count: usize,

    /// Certificate OIDs
    pub oids_str: String,
    pub oid_count: usize,

    /// DNS counts
    pub nameserver_count: usize,
    pub txt_count: usize,
    pub mx_count: usize,

    /// Actual DNS records
    pub nameservers: Vec<NameserverRecord>,
    pub txt_records: Vec<TxtRecord>,
    pub mx_records: Vec<MxRecord>,

    /// Analytics IDs formatted as comma-separated `provider:tracking_id` values for CSV export.
    /// JSONL uses [`Self::analytics_ids`] for structured output.
    pub analytics_ids_str: String,
    pub analytics_count: usize,
    /// Analytics IDs as structured data (safe from delimiter corruption)
    pub analytics_ids: Vec<AnalyticsIdRecord>,
    pub script_hosts: Vec<ScriptHostRecord>,
    pub script_hosts_str: String,

    /// Social media links (as "platform:url" strings)
    pub social_media_links_str: String,
    pub social_media_count: usize,

    /// Social media links with identifiers
    pub social_media_links: Vec<SocialMediaLink>,

    /// Structured data
    pub structured_data_types_str: String,
    pub structured_data_count: usize,

    /// Detailed structured data entries
    pub structured_data_entries: Vec<StructuredDataEntry>,

    /// HTTP headers (key headers only, for backward compat)
    pub http_headers_str: String,
    pub http_header_count: usize,

    /// Security headers (key headers only, for backward compat)
    pub security_headers_str: String,
    pub security_header_count: usize,

    /// All HTTP headers (unfiltered)
    pub all_http_headers: Vec<HttpHeader>,
    /// All security headers (unfiltered)
    pub all_security_headers: Vec<HttpHeader>,

    /// Partial failures (DNS/TLS errors that didn't block processing)
    pub partial_failures: Vec<PartialFailure>,

    /// `GeoIP` data
    pub geoip: GeoIpData,

    /// WHOIS data
    pub whois: WhoisData,

    /// Favicon hash (Shodan-compatible `MurmurHash3`)
    pub favicon_hash: Option<i32>,
    /// Favicon URL
    pub favicon_url: Option<String>,

    /// Contact links (mailto/tel)
    pub contact_links: Vec<ContactLinkRecord>,
    pub contact_link_count: usize,

    /// Exposed secrets detected in HTML
    pub exposed_secrets: Vec<ExposedSecretRecord>,
    pub exposed_secret_count: usize,

    /// CNAME records
    pub cname_records: Vec<String>,
    pub cname_count: usize,

    /// IPv6 addresses
    pub ipv6_addresses: Vec<String>,
    pub ipv6_count: usize,

    /// CAA records
    pub caa_records: Vec<CaaRecord>,
    pub caa_count: usize,
}

/// Key HTTP headers to include in exports.
const HTTP_KEY_HEADERS: &[&str] = &[
    "Content-Type",
    "Server",
    "X-Powered-By",
    "X-Frame-Options",
    "X-Content-Type-Options",
    "Strict-Transport-Security",
    "Content-Security-Policy",
];

/// Key security headers to include in exports.
const SECURITY_KEY_HEADERS: &[&str] = &[
    "Content-Security-Policy",
    "X-Frame-Options",
    "X-Content-Type-Options",
    "Strict-Transport-Security",
    "Referrer-Policy",
    "Permissions-Policy",
];

/// Extract main row data from a database row.
pub fn extract_main_row_data(row: &sqlx::sqlite::SqliteRow) -> MainRowData {
    MainRowData {
        id: row.get("id"),
        initial_domain: row.get("initial_domain"),
        final_domain: row.get("final_domain"),
        initial_url: row.get("initial_url"),
        final_url: row.get("final_url"),
        ip_address: row.get("ip_address"),
        reverse_dns: row.get("reverse_dns_name"),
        status: row.get("http_status"),
        status_desc: row.get("http_status_text"),
        response_time: row.get("response_time_seconds"),
        title: row.get("title"),
        description: row.get("description"),
        meta_robots: row.get("meta_robots"),
        tls_version: row.get("tls_version"),
        ssl_cert_subject: row.get("ssl_cert_subject"),
        ssl_cert_issuer: row.get("ssl_cert_issuer"),
        ssl_cert_valid_to_ms: row.get("ssl_cert_valid_to_ms"),
        cipher_suite: row.get("cipher_suite"),
        key_algorithm: row.get("key_algorithm"),
        spf_record: row.get("spf_record"),
        dmarc_record: row.get("dmarc_record"),
        mta_sts_record: row.get("mta_sts_record"),
        tls_rpt_record: row.get("tls_rpt_record"),
        bimi_record: row.get("bimi_record"),
        hsts_max_age: row.get("hsts_max_age"),
        hsts_include_subdomains: row.get("hsts_include_subdomains"),
        hsts_preload: row.get("hsts_preload"),
        cdn_provider: row.get("cdn_provider"),
        timestamp: row.get("observed_at_ms"),
        run_id: row.get("run_id"),
        body_sha256: row.get("body_sha256"),
        content_length: row.get("content_length"),
        http_version: row.get("http_version"),
        content_type: row.get("content_type"),
        canonical_url: row.get("canonical_url"),
        cert_fingerprint_sha256: row.get("cert_fingerprint_sha256"),
        body_truncated: row.get("body_truncated"),
    }
}

/// Build a complete export row by fetching all satellite data.
///
/// This function takes the main row data and fetches all related data
/// from satellite tables, constructing a complete `ExportRow`.
///
/// # Arguments
///
/// * `pool` - Database connection pool
/// * `main` - Main row data extracted from the `url_status` table
///
/// # Returns
///
/// A complete `ExportRow` with all satellite data populated.
/// Fetch DNS satellite data (nameservers, TXT, MX records).
async fn fetch_dns_records(
    pool: &DbPool,
    url_status_id: i64,
) -> Result<(Vec<NameserverRecord>, Vec<TxtRecord>, Vec<MxRecord>)> {
    let nameservers: Vec<NameserverRecord> = sqlx::query(
        "SELECT nameserver FROM url_nameservers WHERE url_status_id = ? ORDER BY nameserver LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| NameserverRecord {
        nameserver: r.get("nameserver"),
    })
    .collect();

    let txt_records: Vec<TxtRecord> = sqlx::query(
        "SELECT record_type, record_value FROM url_txt_records WHERE url_status_id = ? ORDER BY record_type, record_value LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| TxtRecord {
        record_type: r.get("record_type"),
        record_value: r.get("record_value"),
    })
    .collect();

    let mx_records: Vec<MxRecord> = sqlx::query(
        "SELECT priority, mail_exchange FROM url_mx_records WHERE url_status_id = ? ORDER BY priority, mail_exchange LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| MxRecord {
        priority: r.get("priority"),
        mail_exchange: r.get("mail_exchange"),
    })
    .collect();

    Ok((nameservers, txt_records, mx_records))
}

/// Fetch all HTTP/security headers (unfiltered) and partial failures.
async fn fetch_headers_and_failures(
    pool: &DbPool,
    url_status_id: i64,
) -> Result<(Vec<HttpHeader>, Vec<HttpHeader>, Vec<PartialFailure>)> {
    let all_http_headers: Vec<HttpHeader> = sqlx::query(
        "SELECT header_name, header_value FROM url_http_headers WHERE url_status_id = ? ORDER BY header_name LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| HttpHeader {
        name: r.get("header_name"),
        value: r.get("header_value"),
    })
    .collect();

    let all_security_headers: Vec<HttpHeader> = sqlx::query(
        "SELECT header_name, header_value FROM url_security_headers WHERE url_status_id = ? ORDER BY header_name LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| HttpHeader {
        name: r.get("header_name"),
        value: r.get("header_value"),
    })
    .collect();

    let partial_failures: Vec<PartialFailure> = sqlx::query(
        "SELECT error_type, error_message FROM url_partial_failures WHERE url_status_id = ? ORDER BY observed_at_ms LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| PartialFailure {
        error_type: r.get("error_type"),
        error_message: r.get("error_message"),
    })
    .collect();

    Ok((all_http_headers, all_security_headers, partial_failures))
}

/// Fetch social media links with identifiers and structured data entries.
async fn fetch_social_and_structured(
    pool: &DbPool,
    url_status_id: i64,
) -> Result<(Vec<SocialMediaLink>, Vec<StructuredDataEntry>)> {
    let social_media_links: Vec<SocialMediaLink> = sqlx::query(
        "SELECT platform, profile_url, identifier FROM url_social_media_links WHERE url_status_id = ? ORDER BY platform, profile_url LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| SocialMediaLink {
        platform: r.get("platform"),
        profile_url: r.get("profile_url"),
        identifier: r.get("identifier"),
    })
    .collect();

    let structured_data_entries: Vec<StructuredDataEntry> = sqlx::query(
        "SELECT data_type, property_name, property_value FROM url_structured_data WHERE url_status_id = ? ORDER BY data_type, property_name LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| StructuredDataEntry {
        data_type: r.get("data_type"),
        property_name: r.get("property_name"),
        property_value: r.get("property_value"),
    })
    .collect();

    Ok((social_media_links, structured_data_entries))
}

/// CSV `key:value` flattening used by `fetch_key_value_list` (empty value → trailing colon).
fn join_colon_pairs<'a, I>(pairs: I) -> String
where
    I: IntoIterator<Item = (&'a str, &'a str)>,
{
    pairs
        .into_iter()
        .map(|(k, v)| format!("{k}:{v}"))
        .collect::<Vec<_>>()
        .join(",")
}

#[allow(clippy::too_many_lines)] // Sequentially fetches ~15 related tables to build a single export row
#[allow(clippy::cognitive_complexity)] // Inherent in assembling data from many DB tables into one struct
pub async fn build_export_row(
    pool: &DbPool,
    main: MainRowData,
    include_implied_tech: bool,
) -> Result<ExportRow> {
    let url_status_id = main.id;

    // Fetch redirect chain
    let redirect_rows = sqlx::query(
        "SELECT redirect_url, sequence_order, http_status FROM url_redirect_chain
         WHERE url_status_id = ? ORDER BY sequence_order LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?;

    let redirects: Vec<RedirectEntry> = redirect_rows
        .iter()
        .map(|r| RedirectEntry {
            redirect_url: r.get("redirect_url"),
            sequence_order: r.get("sequence_order"),
            http_status: r.get("http_status"),
        })
        .collect();

    let redirect_count = redirects.len();
    let final_redirect_url = redirects
        .last()
        .map(|r| r.redirect_url.clone())
        .unwrap_or_default();

    // One SELECT; CSV joined strings are derived from the same rows as JSONL/Parquet.
    let tech_filter = if include_implied_tech {
        ""
    } else {
        " AND COALESCE(is_implied, 0) = 0"
    };
    let tech_struct_sql = format!(
        "SELECT technology_name, technology_version, technology_category, is_implied, detection_source
         FROM url_technologies WHERE url_status_id = ?{tech_filter} ORDER BY technology_name LIMIT ?"
    );
    let technologies: Vec<TechnologyRecord> = crate::sql::query(tech_struct_sql)
        .bind(url_status_id)
        .bind(EXPORT_LIMIT)
        .fetch_all(pool.as_ref())
        .await?
        .iter()
        .map(|r| TechnologyRecord {
            name: r.get("technology_name"),
            version: r.get("technology_version"),
            category: r.get("technology_category"),
            is_implied: r.get::<i64, _>("is_implied") != 0,
            detection_source: r.get("detection_source"),
        })
        .collect();
    let technologies_str = join_colon_pairs(
        technologies
            .iter()
            .map(|t| (t.name.as_str(), t.version.as_deref().unwrap_or(""))),
    );
    let technology_count = technologies.len();
    let technology_categories_str = technologies
        .iter()
        .filter_map(|t| t.category.as_deref())
        .collect::<Vec<_>>()
        .join(", ");

    // Fetch certificate SANs
    let (certificate_sans_str, certificate_san_count) = fetch_string_list(
        pool,
        "SELECT san_value FROM url_certificate_sans WHERE url_status_id = ? ORDER BY san_value",
        url_status_id,
    )
    .await?;

    // Fetch OIDs
    let (oids_str, oid_count) = fetch_string_list(
        pool,
        "SELECT oid FROM url_certificate_oids WHERE url_status_id = ? ORDER BY oid",
        url_status_id,
    )
    .await?;

    // Fetch DNS records (actual data)
    let (nameservers, txt_records, mx_records) = fetch_dns_records(pool, url_status_id).await?;
    // DNS record counts are bounded by EXPORT_LIMIT (small constant), safe to cast
    #[allow(clippy::cast_possible_wrap)]
    let nameserver_count = nameservers.len() as i64;
    #[allow(clippy::cast_possible_wrap)]
    let txt_count = txt_records.len() as i64;
    #[allow(clippy::cast_possible_wrap)]
    let mx_count = mx_records.len() as i64;

    // Fetch CNAME records
    let cname_records: Vec<String> = sqlx::query(
        "SELECT cname_target FROM url_cname_records WHERE url_status_id = ? ORDER BY cname_target LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| r.get::<String, _>("cname_target"))
    .collect();
    let cname_count = cname_records.len();

    // Fetch IPv6 addresses
    let ipv6_addresses: Vec<String> = sqlx::query(
        "SELECT ipv6_address FROM url_ipv6_addresses WHERE url_status_id = ? ORDER BY ipv6_address LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| r.get::<String, _>("ipv6_address"))
    .collect();
    let ipv6_count = ipv6_addresses.len();

    // Fetch CAA records
    let caa_records: Vec<CaaRecord> = sqlx::query(
        "SELECT flag, tag, value FROM url_caa_records WHERE url_status_id = ? ORDER BY tag, value LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| CaaRecord {
        flag: r.get("flag"),
        tag: r.get("tag"),
        value: r.get("value"),
    })
    .collect();
    let caa_count = caa_records.len();

    let analytics_ids: Vec<AnalyticsIdRecord> = sqlx::query(
        "SELECT provider, tracking_id FROM url_analytics_ids WHERE url_status_id = ? ORDER BY provider, tracking_id LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| AnalyticsIdRecord {
        provider: r.get("provider"),
        tracking_id: r.get("tracking_id"),
    })
    .collect();
    let analytics_ids_str = join_colon_pairs(
        analytics_ids
            .iter()
            .map(|a| (a.provider.as_str(), a.tracking_id.as_str())),
    );
    let analytics_count = analytics_ids.len();

    let script_hosts: Vec<ScriptHostRecord> = sqlx::query(
        "SELECT host, registrable_domain, is_first_party FROM url_script_hosts WHERE url_status_id = ? ORDER BY host LIMIT ?",
    )
    .bind(main.id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| ScriptHostRecord {
        host: r.get("host"),
        registrable_domain: r.get("registrable_domain"),
        is_first_party: r.get::<i64, _>("is_first_party") != 0,
    })
    .collect();
    let script_hosts_str = script_hosts
        .iter()
        .map(|h| {
            if h.is_first_party {
                format!("{} (1p)", h.host)
            } else {
                h.host.clone()
            }
        })
        .collect::<Vec<_>>()
        .join("; ");

    let (social_media_links, structured_data_entries) =
        fetch_social_and_structured(pool, url_status_id).await?;
    let social_media_links_str = join_colon_pairs(
        social_media_links
            .iter()
            .map(|s| (s.platform.as_str(), s.profile_url.as_str())),
    );
    let social_media_count = social_media_links.len();

    let mut structured_data_types: Vec<&str> = structured_data_entries
        .iter()
        .map(|e| e.data_type.as_str())
        .collect();
    structured_data_types.sort_unstable();
    structured_data_types.dedup();
    let structured_data_types_str = structured_data_types.join(",");
    let structured_data_count = structured_data_entries.len();

    // Fetch HTTP headers
    let (http_headers_str, http_header_count) = fetch_filtered_http_headers(
        pool,
        HttpHeadersTable::Standard,
        url_status_id,
        HTTP_KEY_HEADERS,
    )
    .await?;

    // Fetch security headers (filtered, for backward compat)
    let (security_headers_str, security_header_count) = fetch_filtered_http_headers(
        pool,
        HttpHeadersTable::Security,
        url_status_id,
        SECURITY_KEY_HEADERS,
    )
    .await?;

    // Fetch all headers (unfiltered) and partial failures
    let (all_http_headers, all_security_headers, partial_failures) =
        fetch_headers_and_failures(pool, url_status_id).await?;

    // Fetch GeoIP data
    let geoip_row = sqlx::query(
        "SELECT country_code, country_name, region, city, latitude, longitude, asn, asn_org
         FROM url_geoip WHERE url_status_id = ?",
    )
    .bind(url_status_id)
    .fetch_optional(pool.as_ref())
    .await?;

    let geoip = if let Some(row) = geoip_row {
        GeoIpData {
            country_code: row.get("country_code"),
            country_name: row.get("country_name"),
            region: row.get("region"),
            city: row.get("city"),
            latitude: row.get("latitude"),
            longitude: row.get("longitude"),
            asn: row.get("asn"),
            asn_org: row.get("asn_org"),
        }
    } else {
        GeoIpData::default()
    };

    // Fetch WHOIS data
    let whois_row = sqlx::query(
        "SELECT registrar, creation_date_ms, expiration_date_ms, registrant_country
         FROM url_whois WHERE url_status_id = ?",
    )
    .bind(url_status_id)
    .fetch_optional(pool.as_ref())
    .await?;

    let whois = if let Some(row) = whois_row {
        WhoisData {
            registrar: row.get("registrar"),
            creation_date_ms: row.get("creation_date_ms"),
            expiration_date_ms: row.get("expiration_date_ms"),
            registrant_country: row.get("registrant_country"),
        }
    } else {
        WhoisData::default()
    };

    // Fetch favicon data
    let favicon_row =
        sqlx::query("SELECT hash, favicon_url FROM url_favicons WHERE url_status_id = ?")
            .bind(url_status_id)
            .fetch_optional(pool.as_ref())
            .await?;

    let (favicon_hash, favicon_url) = if let Some(row) = favicon_row {
        (
            Some(row.get::<i32, _>("hash")),
            Some(row.get::<String, _>("favicon_url")),
        )
    } else {
        (None, None)
    };

    // Fetch contact links
    let contact_links: Vec<ContactLinkRecord> = sqlx::query(
        "SELECT contact_type, contact_value FROM url_contact_links WHERE url_status_id = ? ORDER BY contact_type, contact_value LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| ContactLinkRecord {
        contact_type: r.get("contact_type"),
        contact_value: r.get("contact_value"),
    })
    .collect();
    let contact_link_count = contact_links.len();

    // Fetch exposed secrets with optional decoded JWT claims
    let exposed_secrets: Vec<ExposedSecretRecord> = sqlx::query(
        "SELECT es.secret_type, es.matched_value, es.severity, es.location, es.context,
                jc.algorithm AS jwt_algorithm, jc.issuer AS jwt_issuer,
                jc.subject AS jwt_subject, jc.audience AS jwt_audience,
                jc.expiration_ms AS jwt_expiration_ms, jc.issued_at_ms AS jwt_issued_at_ms,
                jc.header_json AS jwt_header_json, jc.payload_json AS jwt_payload_json
         FROM url_exposed_secrets es
         LEFT JOIN url_jwt_claims jc ON jc.exposed_secret_id = es.id
         WHERE es.url_status_id = ? ORDER BY es.secret_type LIMIT ?",
    )
    .bind(url_status_id)
    .bind(EXPORT_LIMIT)
    .fetch_all(pool.as_ref())
    .await?
    .iter()
    .map(|r| ExposedSecretRecord {
        secret_type: r.get("secret_type"),
        matched_value: r.get("matched_value"),
        severity: r.get("severity"),
        location: r.get("location"),
        context: r.get("context"),
        jwt_algorithm: r.get("jwt_algorithm"),
        jwt_issuer: r.get("jwt_issuer"),
        jwt_subject: r.get("jwt_subject"),
        jwt_audience: r.get("jwt_audience"),
        jwt_expiration_ms: r.get("jwt_expiration_ms"),
        jwt_issued_at_ms: r.get("jwt_issued_at_ms"),
        jwt_header_json: r.get("jwt_header_json"),
        jwt_payload_json: r.get("jwt_payload_json"),
    })
    .collect();
    let exposed_secret_count = exposed_secrets.len();

    // SAFETY: All count values are non-negative database counts that fit in usize.
    // These casts are safe because:
    // 1. SQL COUNT(*) always returns non-negative values
    // 2. Realistic table sizes are well within usize range
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    Ok(ExportRow {
        main,
        redirects,
        redirect_count,
        final_redirect_url,
        technologies_str,
        technology_categories_str,
        technology_count,
        technologies,
        certificate_sans_str,
        certificate_san_count,
        oids_str,
        oid_count,
        nameserver_count: nameserver_count as usize,
        txt_count: txt_count as usize,
        mx_count: mx_count as usize,
        nameservers,
        txt_records,
        mx_records,
        analytics_ids_str,
        analytics_count,
        analytics_ids,
        script_hosts,
        script_hosts_str,
        social_media_links_str,
        social_media_count,
        social_media_links,
        structured_data_types_str,
        structured_data_count,
        structured_data_entries,
        http_headers_str,
        http_header_count: http_header_count as usize,
        security_headers_str,
        security_header_count: security_header_count as usize,
        all_http_headers,
        all_security_headers,
        partial_failures,
        geoip,
        whois,
        favicon_hash,
        favicon_url,
        contact_links,
        contact_link_count,
        exposed_secrets,
        exposed_secret_count,
        cname_records,
        cname_count,
        ipv6_addresses,
        ipv6_count,
        caa_records,
        caa_count,
    })
}

/// Parse a comma-separated string into a Vec of strings.
pub fn parse_string_list(list_str: &str) -> Vec<String> {
    if list_str.is_empty() {
        return vec![];
    }

    list_str
        .split(',')
        .map(std::string::ToString::to_string)
        .collect()
}

/// Build the URL from `final_domain`.
pub fn build_url(final_domain: &str) -> String {
    if final_domain.starts_with("http://") || final_domain.starts_with("https://") {
        final_domain.to_string()
    } else {
        format!("https://{final_domain}")
    }
}