youtube-legend-cli 0.4.0

Non-interactive Rust CLI that downloads YouTube subtitles through third-party providers, using a native Unix stdin/stdout interface.
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
//! Session state: a persistent cookie jar and a Chrome-coherent
//! request-header fingerprint.
//!
//! # Cookie jar
//!
//! [`CookieJar`] is the single source of truth for session state. It
//! synchronises with the browser through `Network.getCookies` and
//! `Network.setCookie`, persists under the XDG data directory, and is
//! written with owner-only permissions (`0600` on Unix).
//!
//! Two rules govern its lifecycle:
//!
//! 1. **Expiry is read, not guessed.** [`CookieJar::prune_expired`]
//!    compares each cookie's own `expires` against the clock. Nothing
//!    re-authenticates on a fixed timer, because a fixed timer either
//!    throws away a still-valid session or keeps a dead one.
//! 2. **Challenge cookies survive a reset.** `cf_clearance`,
//!    `datadome`, `_px3` and their peers are the *proof* that a
//!    challenge was already solved. Discarding one forces a fresh
//!    challenge, which costs a round trip and another chance to be
//!    blocked. [`CookieJar::clear_except_challenges`] exists precisely
//!    so that "start over" does not mean "solve the challenge again".
//!
//! # Header fingerprint
//!
//! [`ChromeFingerprint`] emits the sixteen request fields Chrome sends,
//! **in Chrome's order**. Order is itself a fingerprint: a client that
//! sends the right headers in the wrong sequence is as identifiable as
//! one that sends the wrong headers.
//!
//! Client Hints are derived internally from a declared user-agent
//! string, so `sec-ch-ua` and `user-agent` can never disagree about the
//! Chrome major version. A mismatch between the two is an immediate
//! detection signal, and deriving one from the other removes the class
//! of bug entirely.
//!
//! ## On TLS-level fingerprinting
//!
//! This module deliberately stops at layer 7. Matching Chrome's TLS
//! `ClientHello` and HTTP/2 `SETTINGS` frame requires a second TLS
//! stack alongside the `rustls` one already linked through `reqwest`.
//! The candidate crate for that (`wreq`) was measured at 157
//! transitive dependencies and failed to complete a cold release build
//! inside a fifteen-minute budget, so it is not linked here. Header
//! order and Client Hints address the application-layer signal; the
//! transport-layer signal is documented as an accepted gap.

use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::error::{AppError, AppResult};
use crate::net::waf::is_challenge_cookie;

/// File name of the persisted jar inside the XDG data directory.
///
/// Compiled default behind `net.session.cookie_file`; read it through
/// [`cookie_file_name`].
pub const DEFAULT_COOKIE_FILE_NAME: &str = "cookies.json";

/// Unix permission bits applied to the persisted jar. Owner read/write
/// only: the file holds live session credentials.
///
/// Compiled default behind `net.session.cookie_file_mode`; read it
/// through [`cookie_file_mode`].
pub const DEFAULT_COOKIE_FILE_MODE: u32 = 0o600;

/// Chrome full version the fingerprint defaults to. Bump this together
/// with the pinned Chromium revision; a user-agent that names a Chrome
/// several majors behind the running binary is itself a signal.
///
/// Compiled default behind `net.session.chrome_full_version`.
pub const DEFAULT_CHROME_FULL_VERSION: &str = "131.0.6778.86";

/// The sixteen request fields Chrome emits, in the order it emits them.
/// The first four are HTTP/2 pseudo-headers.
///
/// This constant is the contract [`ChromeFingerprint::headers`] is
/// tested against; changing one without the other is a bug.
///
/// Compiled default behind `net.session.header_order`; read it through
/// [`chrome_header_order`].
pub const CHROME_HEADER_ORDER: [&str; 16] = [
    ":method",
    ":authority",
    ":scheme",
    ":path",
    "sec-ch-ua",
    "sec-ch-ua-mobile",
    "sec-ch-ua-platform",
    "upgrade-insecure-requests",
    "user-agent",
    "accept",
    "sec-fetch-site",
    "sec-fetch-mode",
    "sec-fetch-user",
    "sec-fetch-dest",
    "accept-encoding",
    "accept-language",
];

/// `Accept` value Chrome sends for a top-level navigation.
///
/// Compiled default behind `net.session.accept_navigation`; read it
/// through [`navigation_accept`].
pub const DEFAULT_NAVIGATION_ACCEPT: &str = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";

/// `Accept-Encoding` value Chrome sends.
///
/// Compiled default behind `net.session.accept_encoding`.
pub const DEFAULT_ACCEPT_ENCODING: &str = "gzip, deflate, br, zstd";

/// `Accept-Language` value used when the caller states no preference.
///
/// Compiled default behind `net.session.accept_language`.
pub const DEFAULT_ACCEPT_LANGUAGE: &str = "en-US,en;q=0.9";

/// File name — or absolute path — of the persisted cookie jar.
///
/// Resolves `net.session.cookie_file`, falling back to
/// [`DEFAULT_COOKIE_FILE_NAME`].
#[must_use]
pub fn cookie_file_name() -> String {
    crate::config::tuning_string_or("net.session.cookie_file", DEFAULT_COOKIE_FILE_NAME)
}

/// Unix permission bits applied to the persisted cookie jar.
///
/// Resolves `net.session.cookie_file_mode`, falling back to
/// [`DEFAULT_COOKIE_FILE_MODE`]. Only the nine permission bits are
/// accepted; anything wider is refused, because the jar holds live
/// session credentials.
#[must_use]
pub fn cookie_file_mode() -> u32 {
    crate::config::tuning_u32_in_range(
        "net.session.cookie_file_mode",
        DEFAULT_COOKIE_FILE_MODE,
        0o400,
        0o777,
    )
}

/// Chrome full version advertised in the client hints.
///
/// Resolves `net.session.chrome_full_version`, falling back to
/// [`DEFAULT_CHROME_FULL_VERSION`].
#[must_use]
pub fn chrome_full_version() -> String {
    crate::config::tuning_string_or(
        "net.session.chrome_full_version",
        DEFAULT_CHROME_FULL_VERSION,
    )
}

/// Order the request fields are emitted in.
///
/// Resolves `net.session.header_order`, falling back to
/// [`CHROME_HEADER_ORDER`]. A name this crate cannot produce a value
/// for is skipped, so a stale entry costs one field rather than the
/// whole request.
#[must_use]
pub fn chrome_header_order() -> Vec<String> {
    crate::config::tuning_str_list_or("net.session.header_order", &CHROME_HEADER_ORDER)
}

/// `Accept` value sent for a top-level navigation.
///
/// Resolves `net.session.accept_navigation`, falling back to
/// [`DEFAULT_NAVIGATION_ACCEPT`].
#[must_use]
pub fn navigation_accept() -> String {
    crate::config::tuning_string_or("net.session.accept_navigation", DEFAULT_NAVIGATION_ACCEPT)
}

/// `Accept-Encoding` value sent with every request.
///
/// Resolves `net.session.accept_encoding`, falling back to
/// [`DEFAULT_ACCEPT_ENCODING`].
#[must_use]
pub fn accept_encoding() -> String {
    crate::config::tuning_string_or("net.session.accept_encoding", DEFAULT_ACCEPT_ENCODING)
}

/// `Accept-Language` value used when the caller states no preference.
///
/// Resolves `net.session.accept_language`, falling back to
/// [`DEFAULT_ACCEPT_LANGUAGE`].
#[must_use]
pub fn accept_language() -> String {
    crate::config::tuning_string_or("net.session.accept_language", DEFAULT_ACCEPT_LANGUAGE)
}

// ---------------------------------------------------------------------------
// HTTP client factory
// ---------------------------------------------------------------------------

/// Builds the `reqwest::Client` every production call site is expected
/// to use.
///
/// # Why this exists
///
/// This module already models a coherent Chrome identity, but until
/// 2026-09-01 *applying* it was optional. Each provider called
/// `reqwest::Client::builder()` for itself and kept whichever pieces it
/// happened to remember: two of the four production sites sent the
/// crate's own `youtube-legend-cli/<version>` string, the other two sent
/// the Chrome user-agent, and not one of the four sent the Client Hints,
/// the `Accept` header or the field order defined above. That is the
/// same shape as GAP-2026-127, where the `user_agent` key and
/// `effective_user_agent` both existed and no HTTP client read either.
/// While the identity is opt-in, every client added later is another
/// chance to forget it, so the identity now lives in the only supported
/// way to build one.
///
/// # What it applies
///
/// [`ChromeFingerprint`] for the user-agent and the Client Hints derived
/// from it, [`navigation_accept`] for `Accept`, [`accept_language`] for
/// `Accept-Language`, and [`chrome_header_order`] for the sequence the
/// fields are inserted in.
///
/// An operator-supplied `user_agent` still wins: the tuning key is read
/// first and the Chrome string is only the fallback. When that value is
/// not a Chrome user-agent the Client Hints are dropped rather than sent
/// beside it, because `sec-ch-ua` naming Chrome next to a `curl/8`
/// user-agent is a stronger signal than sending no hint at all.
///
/// `Accept-Encoding` is now applied from [`accept_encoding`], which it
/// was not before 2026-09-01. `reqwest` sets its own `Accept-Encoding`
/// only when the request carries none, and it decodes exactly what its
/// enabled features cover, so sending the modelled `gzip, deflate, br,
/// zstd` is only safe because the manifest now compiles all four. That
/// pairing is load-bearing rather than tidy: MEASURED against
/// <https://www.cloudflare.com/> with only `gzip` compiled in, this
/// header returned 104 366 bytes tagged `content-encoding: br` with 83
/// of the first 200 printable, and with all four compiled the same
/// request returned 1 315 960 decoded bytes and no `content-encoding`.
/// Whoever drops a decompression feature from the manifest re-opens
/// exactly that, and silently.
///
/// One field is still deliberately left out.
///
/// 1. The `Sec-Fetch-*` set. Those four fields describe one request, not
///    one client, and a client-wide header map would stamp
///    `navigate`/`document` onto an XHR. An impossible pair denounces
///    more than an absent field;
///    [`ChromeFingerprint::transmittable_headers`] still emits the set
///    for callers that build a [`RequestContext`].
///
/// # Errors
///
/// - [`AppError::Http`] when `reqwest` refuses the configuration.
pub fn chrome_client(timeout: std::time::Duration) -> AppResult<reqwest::Client> {
    use reqwest::header::{HeaderMap, HeaderName, HeaderValue};

    let user_agent = crate::config::tuning_string("user_agent")
        .unwrap_or_else(|| ChromeFingerprint::default().user_agent().to_owned());
    let fingerprint = ChromeFingerprint::from_user_agent(&user_agent);

    let mut headers = HeaderMap::new();
    for name in chrome_header_order() {
        let value = match name.as_str() {
            "sec-ch-ua" => fingerprint.as_ref().map(ChromeFingerprint::sec_ch_ua),
            "sec-ch-ua-mobile" => fingerprint
                .as_ref()
                .map(|fp| fp.sec_ch_ua_mobile().to_owned()),
            "sec-ch-ua-platform" => fingerprint
                .as_ref()
                .map(ChromeFingerprint::sec_ch_ua_platform),
            "upgrade-insecure-requests" => Some("1".to_owned()),
            "accept" => Some(navigation_accept()),
            "accept-encoding" => Some(accept_encoding()),
            "accept-language" => Some(accept_language()),
            // Pseudo-headers are produced by the transport, the
            // `Sec-Fetch-*` set is per-request, `user-agent` is set
            // through the builder, and anything else is a stale entry in
            // `net.session.header_order`.
            _ => None,
        };
        let Some(value) = value else { continue };
        if let (Ok(name), Ok(value)) = (
            HeaderName::from_bytes(name.as_bytes()),
            HeaderValue::from_str(&value),
        ) {
            headers.insert(name, value);
        }
    }

    reqwest::Client::builder()
        .timeout(timeout)
        .user_agent(user_agent)
        .default_headers(headers)
        .build()
        .map_err(AppError::Http)
}

// ---------------------------------------------------------------------------
// Cookie jar
// ---------------------------------------------------------------------------

/// One cookie, as stored.
///
/// The value is session-bearing material. It is never written to a log.
/// The HAR redaction that used to be named here left with the browser
/// subsystem on 2026-09-04, and no code writes a HAR archive any more.
/// [`fmt::Debug`] is implemented by hand so that a stray `{:?}` in a
/// log statement cannot leak it either.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoredCookie {
    /// Cookie name.
    pub name: String,
    /// Cookie value. Secret.
    pub value: String,
    /// Cookie domain, without a leading dot.
    pub domain: String,
    /// Cookie path.
    pub path: String,
    /// Absolute expiry, or `None` for a session cookie.
    pub expires: Option<DateTime<Utc>>,
    /// `Secure` attribute.
    pub secure: bool,
    /// `HttpOnly` attribute.
    pub http_only: bool,
    /// `SameSite` attribute, verbatim, when the browser reported one.
    pub same_site: Option<String>,
}

impl fmt::Debug for StoredCookie {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StoredCookie")
            .field("name", &self.name)
            .field("value", &"[REDACTED]")
            .field("domain", &self.domain)
            .field("path", &self.path)
            .field("expires", &self.expires)
            .field("secure", &self.secure)
            .field("http_only", &self.http_only)
            .field("same_site", &self.same_site)
            .finish()
    }
}

impl StoredCookie {
    /// Builds a session cookie (no expiry) for `domain`, path `/`.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        value: impl Into<String>,
        domain: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
            domain: domain.into(),
            path: "/".to_owned(),
            expires: None,
            secure: true,
            http_only: false,
            same_site: None,
        }
    }

    /// Sets an absolute expiry.
    #[must_use]
    pub fn with_expiry(mut self, expires: DateTime<Utc>) -> Self {
        self.expires = Some(expires);
        self
    }

    /// Sets the path.
    #[must_use]
    pub fn with_path(mut self, path: impl Into<String>) -> Self {
        self.path = path.into();
        self
    }

    /// Whether this cookie has passed its own stated expiry at `now`.
    /// Session cookies (no expiry) are never expired by the clock.
    #[must_use]
    pub fn is_expired_at(&self, now: DateTime<Utc>) -> bool {
        self.expires.is_some_and(|exp| exp <= now)
    }

    /// Whether this cookie proves a WAF challenge was already solved.
    #[must_use]
    pub fn is_challenge(&self) -> bool {
        is_challenge_cookie(&self.name)
    }

    /// Identity used for de-duplication: `(domain, path, name)`, as
    /// RFC 6265 defines cookie identity.
    #[must_use]
    pub fn key(&self) -> String {
        format!(
            "{}\u{1f}{}\u{1f}{}",
            self.domain.trim_start_matches('.').to_ascii_lowercase(),
            self.path,
            self.name
        )
    }
}

/// A cookie store keyed on `(domain, path, name)`.
///
/// ```
/// use chrono::{Duration, Utc};
/// use youtube_legend_cli::net::{CookieJar, StoredCookie};
///
/// let mut jar = CookieJar::new();
/// jar.insert(StoredCookie::new("cf_clearance", "proof", "example.com"));
/// jar.insert(
///     StoredCookie::new("stale", "x", "example.com")
///         .with_expiry(Utc::now() - Duration::hours(1)),
/// );
///
/// assert_eq!(jar.prune_expired(Utc::now()), 1);
/// jar.clear_except_challenges();
/// assert_eq!(jar.len(), 1, "the challenge cookie survives a reset");
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CookieJar {
    cookies: BTreeMap<String, StoredCookie>,
}

impl CookieJar {
    /// An empty jar.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts or replaces a cookie.
    pub fn insert(&mut self, cookie: StoredCookie) {
        self.cookies.insert(cookie.key(), cookie);
    }

    /// Looks a cookie up by domain, path and name.
    #[must_use]
    pub fn get(&self, domain: &str, path: &str, name: &str) -> Option<&StoredCookie> {
        let probe = StoredCookie {
            name: name.to_owned(),
            value: String::new(),
            domain: domain.to_owned(),
            path: path.to_owned(),
            expires: None,
            secure: false,
            http_only: false,
            same_site: None,
        };
        self.cookies.get(&probe.key())
    }

    /// Every cookie in the jar, in key order.
    pub fn iter(&self) -> impl Iterator<Item = &StoredCookie> {
        self.cookies.values()
    }

    /// Number of cookies held.
    #[must_use]
    pub fn len(&self) -> usize {
        self.cookies.len()
    }

    /// `true` when the jar holds nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cookies.is_empty()
    }

    /// The names of every cookie held, for
    /// [`crate::net::waf::detect`].
    #[must_use]
    pub fn cookie_names(&self) -> Vec<String> {
        self.cookies.values().map(|c| c.name.clone()).collect()
    }

    /// Drops cookies that have passed their own stated expiry, and
    /// returns how many were dropped.
    ///
    /// This reads the cookie's real `expires` attribute. Nothing here
    /// is time-boxed by policy: a session that is still valid is kept,
    /// and one that the server already invalidated is dropped, however
    /// recently it was obtained.
    pub fn prune_expired(&mut self, now: DateTime<Utc>) -> usize {
        let before = self.cookies.len();
        self.cookies.retain(|_, cookie| !cookie.is_expired_at(now));
        before - self.cookies.len()
    }

    /// Empties the jar except for WAF challenge-clearance cookies.
    ///
    /// Use this instead of [`Self::clear`] when resetting a stuck
    /// session: throwing away `cf_clearance` forces a fresh challenge.
    pub fn clear_except_challenges(&mut self) {
        self.cookies.retain(|_, cookie| cookie.is_challenge());
    }

    /// Empties the jar unconditionally, challenge cookies included.
    pub fn clear(&mut self) {
        self.cookies.clear();
    }

    /// Whether every challenge cookie for `domain` is still valid at
    /// `now`. `false` means a fresh challenge is genuinely required —
    /// as opposed to a timer having elapsed.
    #[must_use]
    pub fn challenge_is_valid(&self, domain: &str, now: DateTime<Utc>) -> bool {
        let domain = domain.trim_start_matches('.').to_ascii_lowercase();
        let mut seen = false;
        for cookie in self.cookies.values().filter(|c| c.is_challenge()) {
            let cookie_domain = cookie.domain.trim_start_matches('.').to_ascii_lowercase();
            if domain == cookie_domain || domain.ends_with(&format!(".{cookie_domain}")) {
                seen = true;
                if cookie.is_expired_at(now) {
                    return false;
                }
            }
        }
        seen
    }

    /// The default persistence path under the XDG data directory.
    ///
    /// # Errors
    ///
    /// - [`AppError::Config`] when the platform data directory cannot
    ///   be resolved.
    pub fn default_path() -> AppResult<PathBuf> {
        let dirs = crate::config::project_dirs().ok_or_else(|| {
            AppError::Config("cannot resolve the platform data directory".to_owned())
        })?;
        Ok(dirs.data_dir().join(cookie_file_name()))
    }

    /// Loads a jar from `path`. A missing file yields an empty jar,
    /// because "no session yet" is a normal first run and not an error.
    ///
    /// # Errors
    ///
    /// - [`AppError::Io`] when the file exists but cannot be read.
    /// - [`AppError::Serde`] when its contents are not a valid jar.
    pub fn load(path: &Path) -> AppResult<Self> {
        match fs::read(path) {
            Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::new()),
            Err(e) => Err(AppError::Io(e)),
        }
    }

    /// Writes the jar to `path`, creating parent directories, with
    /// owner-only permissions on Unix.
    ///
    /// The write goes to a sibling temporary file which is then
    /// renamed, so a crash mid-write cannot leave a truncated jar
    /// behind. Permissions are applied to the temporary file *before*
    /// the secret is written into it, so the contents are never
    /// world-readable, not even for an instant.
    ///
    /// On Windows the file inherits the directory ACL; the XDG data
    /// directory is already per-user there, so no extra step is taken.
    ///
    /// # Errors
    ///
    /// - [`AppError::Serde`] when the jar cannot be serialised.
    /// - [`AppError::Io`] when a directory, file or rename operation
    ///   fails.
    pub fn save(&self, path: &Path) -> AppResult<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let json = serde_json::to_vec_pretty(self)?;

        let tmp = path.with_extension("json.tmp");
        {
            let mut file = fs::File::create(&tmp)?;
            restrict_permissions(&file)?;
            file.write_all(&json)?;
            file.sync_all()?;
        }
        fs::rename(&tmp, path)?;
        Ok(())
    }

    /// Loads from, or saves to, [`Self::default_path`].
    ///
    /// # Errors
    ///
    /// As [`Self::default_path`] and [`Self::load`].
    pub fn load_default() -> AppResult<Self> {
        let path = Self::default_path()?;
        Self::load(&path)
    }

    /// Saves to [`Self::default_path`].
    ///
    /// # Errors
    ///
    /// As [`Self::default_path`] and [`Self::save`].
    pub fn save_default(&self) -> AppResult<()> {
        let path = Self::default_path()?;
        self.save(&path)
    }
}

/// Applies owner-only permissions to a freshly created file.
#[cfg(unix)]
fn restrict_permissions(file: &fs::File) -> AppResult<()> {
    use std::os::unix::fs::PermissionsExt;
    let perms = fs::Permissions::from_mode(cookie_file_mode());
    file.set_permissions(perms)?;
    Ok(())
}

/// No-op on non-Unix platforms: the XDG data directory is already
/// per-user and the file inherits its ACL.
#[cfg(not(unix))]
fn restrict_permissions(_file: &fs::File) -> AppResult<()> {
    Ok(())
}

// `seconds_since_epoch` and `epoch_seconds_to_datetime` translated cookie
// expiry between this jar and the CDP wire format. Both were removed on
// 2026-09-04 with `to_cdp_params` and `absorb_cdp_cookies`, the only two
// callers, when the browser subsystem left. The jar itself stays: it is
// the cookie store the HTTP providers use.

// ---------------------------------------------------------------------------
// Header fingerprint
// ---------------------------------------------------------------------------

/// The operating system a fingerprint claims to run on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChromePlatform {
    /// Windows.
    Windows,
    /// macOS.
    MacOs,
    /// Linux.
    Linux,
}

impl ChromePlatform {
    /// The value Chrome puts in `sec-ch-ua-platform`, quotes included
    /// at emit time.
    #[must_use]
    pub const fn ch_ua_platform(self) -> &'static str {
        match self {
            Self::Windows => "Windows",
            Self::MacOs => "macOS",
            Self::Linux => "Linux",
        }
    }

    /// The platform token Chrome puts in its user-agent string.
    #[must_use]
    pub const fn ua_platform_token(self) -> &'static str {
        match self {
            Self::Windows => "Windows NT 10.0; Win64; x64",
            Self::MacOs => "Macintosh; Intel Mac OS X 10_15_7",
            Self::Linux => "X11; Linux x86_64",
        }
    }

    /// The platform of the host this binary is running on.
    #[must_use]
    pub const fn host() -> Self {
        if cfg!(target_os = "windows") {
            Self::Windows
        } else if cfg!(target_os = "macos") {
            Self::MacOs
        } else {
            Self::Linux
        }
    }
}

/// How the request relates to the page that triggered it. These four
/// fields are the `Sec-Fetch-*` metadata set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchMetadata {
    /// `sec-fetch-site`, for example `none`, `same-origin`, `cross-site`.
    pub site: String,
    /// `sec-fetch-mode`, for example `navigate`, `cors`, `no-cors`.
    pub mode: String,
    /// `sec-fetch-user`; Chrome sends `?1` only for user-activated
    /// navigations and omits the header otherwise.
    pub user: Option<String>,
    /// `sec-fetch-dest`, for example `document`, `empty`, `script`.
    pub dest: String,
}

impl FetchMetadata {
    /// The metadata Chrome sends for a top-level, user-typed
    /// navigation.
    #[must_use]
    pub fn top_level_navigation() -> Self {
        Self {
            site: "none".to_owned(),
            mode: "navigate".to_owned(),
            user: Some("?1".to_owned()),
            dest: "document".to_owned(),
        }
    }

    /// The metadata Chrome sends for a same-origin `fetch()` call.
    #[must_use]
    pub fn same_origin_xhr() -> Self {
        Self {
            site: "same-origin".to_owned(),
            mode: "cors".to_owned(),
            user: None,
            dest: "empty".to_owned(),
        }
    }
}

/// Everything about a single request that the header set depends on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestContext {
    /// HTTP method, uppercase.
    pub method: String,
    /// URL scheme, without `://`.
    pub scheme: String,
    /// Host and optional port, the HTTP/2 `:authority`.
    pub authority: String,
    /// Path and query, the HTTP/2 `:path`.
    pub path: String,
    /// `Accept` value.
    pub accept: String,
    /// `Accept-Language` value.
    pub accept_language: String,
    /// The `Sec-Fetch-*` set.
    pub fetch: FetchMetadata,
}

impl RequestContext {
    /// A `GET` navigation to `https://{authority}{path}`.
    #[must_use]
    pub fn navigation(authority: impl Into<String>, path: impl Into<String>) -> Self {
        Self {
            method: "GET".to_owned(),
            scheme: "https".to_owned(),
            authority: authority.into(),
            path: path.into(),
            accept: navigation_accept(),
            accept_language: accept_language(),
            fetch: FetchMetadata::top_level_navigation(),
        }
    }

    /// Overrides `Accept-Language`, for example from the `--lang` flag.
    #[must_use]
    pub fn with_accept_language(mut self, value: impl Into<String>) -> Self {
        self.accept_language = value.into();
        self
    }
}

/// A coherent Chrome identity: user-agent plus the Client Hints derived
/// from it.
///
/// The invariant this type exists to enforce is that `sec-ch-ua` and
/// `user-agent` always name the same Chrome major version. Both are
/// generated from one declared full version, so they cannot drift.
///
/// ```
/// use youtube_legend_cli::net::ChromeFingerprint;
///
/// let fp = ChromeFingerprint::from_user_agent(
///     "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
///      Chrome/131.0.6778.86 Safari/537.36",
/// )
/// .expect("a Chrome user-agent must parse");
///
/// assert_eq!(fp.major_version(), 131);
/// assert!(fp.sec_ch_ua().contains("\"131\""));
/// assert!(fp.is_coherent());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChromeFingerprint {
    full_version: String,
    major_version: u32,
    platform: ChromePlatform,
    user_agent: String,
}

impl Default for ChromeFingerprint {
    fn default() -> Self {
        Self::new(ChromePlatform::host(), &chrome_full_version())
            .unwrap_or_else(|| Self::fallback(ChromePlatform::host()))
    }
}

impl ChromeFingerprint {
    /// Builds a fingerprint from a platform and a dotted Chrome version
    /// such as `131.0.6778.86`. Returns `None` when the version has no
    /// parsable leading major component.
    #[must_use]
    pub fn new(platform: ChromePlatform, full_version: &str) -> Option<Self> {
        let major = full_version.split('.').next()?.parse::<u32>().ok()?;
        let user_agent = format!(
            "Mozilla/5.0 ({}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{} Safari/537.36",
            platform.ua_platform_token(),
            full_version
        );
        Some(Self {
            full_version: full_version.to_owned(),
            major_version: major,
            platform,
            user_agent,
        })
    }

    /// Last-resort constructor used when the compiled-in default
    /// version constant is malformed. Kept infallible so that
    /// [`Default`] cannot panic.
    fn fallback(platform: ChromePlatform) -> Self {
        let full_version = "131.0.0.0";
        let user_agent = format!(
            "Mozilla/5.0 ({}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{} Safari/537.36",
            platform.ua_platform_token(),
            full_version
        );
        Self {
            full_version: full_version.to_owned(),
            major_version: 131,
            platform,
            user_agent,
        }
    }

    /// Derives a fingerprint from an existing Chrome user-agent string,
    /// so that the Client Hints match a user-agent the caller already
    /// committed to elsewhere.
    ///
    /// Returns `None` when the string carries no `Chrome/<major>` token.
    #[must_use]
    pub fn from_user_agent(user_agent: &str) -> Option<Self> {
        let after = user_agent.split("Chrome/").nth(1)?;
        let full_version: String = after
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '.')
            .collect();
        let major = full_version.split('.').next()?.parse::<u32>().ok()?;

        let platform = if user_agent.contains("Windows NT") {
            ChromePlatform::Windows
        } else if user_agent.contains("Mac OS X") || user_agent.contains("Macintosh") {
            ChromePlatform::MacOs
        } else {
            ChromePlatform::Linux
        };

        Some(Self {
            full_version,
            major_version: major,
            platform,
            user_agent: user_agent.to_owned(),
        })
    }

    /// The full dotted version.
    #[must_use]
    pub fn full_version(&self) -> &str {
        &self.full_version
    }

    /// The Chrome major version.
    #[must_use]
    pub const fn major_version(&self) -> u32 {
        self.major_version
    }

    /// The platform claimed.
    #[must_use]
    pub const fn platform(&self) -> ChromePlatform {
        self.platform
    }

    /// The user-agent string.
    #[must_use]
    pub fn user_agent(&self) -> &str {
        &self.user_agent
    }

    /// The `sec-ch-ua` brand list, derived from
    /// [`Self::major_version`].
    ///
    /// The middle entry is the deliberately meaningless "GREASE" brand
    /// the specification requires, so that servers cannot hard-code the
    /// list. Its label is derived from the major version rather than
    /// randomised, because a brand list that changes between two
    /// requests of the same session is itself a signal.
    #[must_use]
    pub fn sec_ch_ua(&self) -> String {
        let major = self.major_version;
        format!(
            "\"Chromium\";v=\"{major}\", \"{}\";v=\"{}\", \"Google Chrome\";v=\"{major}\"",
            grease_brand(major),
            grease_version(major)
        )
    }

    /// The `sec-ch-ua-mobile` value. Always `?0`: this crate never
    /// claims to be a phone.
    #[must_use]
    pub const fn sec_ch_ua_mobile(&self) -> &'static str {
        "?0"
    }

    /// The `sec-ch-ua-platform` value, quoted as the header requires.
    #[must_use]
    pub fn sec_ch_ua_platform(&self) -> String {
        format!("\"{}\"", self.platform.ch_ua_platform())
    }

    /// Whether the Client Hints and the user-agent agree on the Chrome
    /// major version.
    ///
    /// This can only be `false` for a fingerprint built via
    /// [`Self::from_user_agent`] from a malformed string; the other
    /// constructors derive both sides from one value.
    #[must_use]
    pub fn is_coherent(&self) -> bool {
        let hint_names_major = self
            .sec_ch_ua()
            .contains(&format!("\"{}\"", self.major_version));
        let ua_names_major = self
            .user_agent
            .contains(&format!("Chrome/{}", self.major_version));
        hint_names_major && ua_names_major
    }

    /// Emits the full request field set, **in Chrome's order**.
    ///
    /// The returned names match [`CHROME_HEADER_ORDER`] position by
    /// position, except that `sec-fetch-user` is omitted when
    /// [`FetchMetadata::user`] is `None` — Chrome omits it rather than
    /// sending `?0`.
    #[must_use]
    pub fn headers(&self, ctx: &RequestContext) -> Vec<(String, String)> {
        let order = chrome_header_order();
        let encoding = accept_encoding();
        let mut out: Vec<(String, String)> = Vec::with_capacity(order.len());
        for name in &order {
            // A field the caller cannot produce a value for is skipped:
            // `sec-fetch-user` is absent on a non-navigation request,
            // and an unrecognised name comes from a stale config entry.
            let value = match name.as_str() {
                ":method" => Some(ctx.method.clone()),
                ":authority" => Some(ctx.authority.clone()),
                ":scheme" => Some(ctx.scheme.clone()),
                ":path" => Some(ctx.path.clone()),
                "sec-ch-ua" => Some(self.sec_ch_ua()),
                "sec-ch-ua-mobile" => Some(self.sec_ch_ua_mobile().to_owned()),
                "sec-ch-ua-platform" => Some(self.sec_ch_ua_platform()),
                "upgrade-insecure-requests" => Some("1".to_owned()),
                "user-agent" => Some(self.user_agent.clone()),
                "accept" => Some(ctx.accept.clone()),
                "sec-fetch-site" => Some(ctx.fetch.site.clone()),
                "sec-fetch-mode" => Some(ctx.fetch.mode.clone()),
                "sec-fetch-user" => ctx.fetch.user.clone(),
                "sec-fetch-dest" => Some(ctx.fetch.dest.clone()),
                "accept-encoding" => Some(encoding.clone()),
                "accept-language" => Some(ctx.accept_language.clone()),
                _ => None,
            };
            if let Some(value) = value {
                out.push((name.clone(), value));
            }
        }
        out
    }

    /// The subset of [`Self::headers`] that can be set on a real HTTP
    /// client: the four HTTP/2 pseudo-headers are produced by the
    /// transport, not by the caller.
    #[must_use]
    pub fn transmittable_headers(&self, ctx: &RequestContext) -> Vec<(String, String)> {
        self.headers(ctx)
            .into_iter()
            .filter(|(name, _)| !name.starts_with(':'))
            .collect()
    }
}

/// The GREASE brand label for a given major version. Deterministic, so
/// that one session never changes its brand list mid-flight.
fn grease_brand(major: u32) -> String {
    const SEPARATORS: [&str; 4] = ["Not_A Brand", "Not-A.Brand", "Not.A/Brand", "Not?A_Brand"];
    let idx = (major as usize) % SEPARATORS.len();
    SEPARATORS[idx].to_owned()
}

/// The version Chrome pairs with the GREASE brand. Chrome has used a
/// small rotating set; deriving it keeps it stable per major version.
fn grease_version(major: u32) -> u32 {
    const CANDIDATES: [u32; 4] = [8, 24, 99, 128];
    CANDIDATES[(major as usize) % CANDIDATES.len()]
}

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

    // -- header order ----------------------------------------------------

    fn linux_fp() -> ChromeFingerprint {
        ChromeFingerprint::new(ChromePlatform::Linux, "131.0.6778.86")
            .expect("a well-formed version must parse")
    }

    #[test]
    fn headers_are_emitted_in_chrome_order() {
        let fp = linux_fp();
        let ctx = RequestContext::navigation("example.com", "/watch");
        let headers = fp.headers(&ctx);
        let names: Vec<&str> = headers.iter().map(|(n, _)| n.as_str()).collect();

        assert_eq!(names.len(), CHROME_HEADER_ORDER.len());
        for (idx, expected) in CHROME_HEADER_ORDER.iter().enumerate() {
            assert_eq!(names[idx], *expected, "field {idx} out of order");
        }
    }

    #[test]
    fn pseudo_headers_come_first_and_in_chrome_sequence() {
        let fp = linux_fp();
        let ctx = RequestContext::navigation("example.com", "/x");
        let headers = fp.headers(&ctx);
        let pseudo: Vec<&str> = headers
            .iter()
            .take_while(|(n, _)| n.starts_with(':'))
            .map(|(n, _)| n.as_str())
            .collect();
        assert_eq!(pseudo, [":method", ":authority", ":scheme", ":path"]);
    }

    #[test]
    fn sec_fetch_user_is_omitted_rather_than_sent_as_false() {
        let fp = linux_fp();
        let mut ctx = RequestContext::navigation("example.com", "/api");
        ctx.fetch = FetchMetadata::same_origin_xhr();
        let headers = fp.headers(&ctx);
        assert!(
            !headers.iter().any(|(n, _)| n == "sec-fetch-user"),
            "Chrome omits sec-fetch-user; it never sends ?0"
        );
        assert_eq!(headers.len(), CHROME_HEADER_ORDER.len() - 1);
    }

    #[test]
    fn transmittable_headers_drop_the_pseudo_headers() {
        let fp = linux_fp();
        let ctx = RequestContext::navigation("example.com", "/x");
        let headers = fp.transmittable_headers(&ctx);
        assert!(!headers.iter().any(|(n, _)| n.starts_with(':')));
        assert_eq!(headers.len(), CHROME_HEADER_ORDER.len() - 4);
        assert_eq!(headers[0].0, "sec-ch-ua");
    }

    // -- client hints ----------------------------------------------------

    #[test]
    fn client_hints_agree_with_the_user_agent() {
        for version in ["120.0.6099.109", "131.0.6778.86", "142.0.7444.12"] {
            let fp = ChromeFingerprint::new(ChromePlatform::Windows, version)
                .expect("version must parse");
            let major = version
                .split('.')
                .next()
                .and_then(|m| m.parse::<u32>().ok())
                .expect("major must parse");

            assert_eq!(fp.major_version(), major);
            assert!(
                fp.sec_ch_ua()
                    .contains(&format!("\"Chromium\";v=\"{major}\"")),
                "sec-ch-ua must name Chromium {major}"
            );
            assert!(
                fp.sec_ch_ua()
                    .contains(&format!("\"Google Chrome\";v=\"{major}\"")),
                "sec-ch-ua must name Google Chrome {major}"
            );
            assert!(fp.user_agent().contains(&format!("Chrome/{version}")));
            assert!(fp.is_coherent());
        }
    }

    #[test]
    fn hints_derived_from_a_user_agent_cannot_drift_from_it() {
        let ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \
                  (KHTML, like Gecko) Chrome/128.0.6613.120 Safari/537.36";
        let fp = ChromeFingerprint::from_user_agent(ua).expect("must parse");

        assert_eq!(fp.major_version(), 128);
        assert_eq!(fp.full_version(), "128.0.6613.120");
        assert_eq!(fp.platform(), ChromePlatform::MacOs);
        assert_eq!(fp.sec_ch_ua_platform(), "\"macOS\"");
        assert!(fp.sec_ch_ua().contains("\"128\""));
        assert!(fp.is_coherent());
    }

    #[test]
    fn platform_hint_matches_the_user_agent_token() {
        for (platform, hint, token) in [
            (ChromePlatform::Windows, "\"Windows\"", "Windows NT"),
            (ChromePlatform::MacOs, "\"macOS\"", "Mac OS X"),
            (ChromePlatform::Linux, "\"Linux\"", "X11; Linux"),
        ] {
            let fp = ChromeFingerprint::new(platform, "131.0.6778.86").expect("must parse");
            assert_eq!(fp.sec_ch_ua_platform(), hint);
            assert!(
                fp.user_agent().contains(token),
                "{hint} must pair with the {token} user-agent token"
            );
        }
    }

    #[test]
    fn grease_brand_is_stable_for_a_given_version() {
        let a = ChromeFingerprint::new(ChromePlatform::Linux, "131.0.6778.86")
            .expect("must parse")
            .sec_ch_ua();
        let b = ChromeFingerprint::new(ChromePlatform::Linux, "131.0.6778.86")
            .expect("must parse")
            .sec_ch_ua();
        assert_eq!(a, b, "the brand list must not change between requests");
    }

    #[test]
    fn a_non_chrome_user_agent_is_rejected() {
        assert!(ChromeFingerprint::from_user_agent(
            "Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0"
        )
        .is_none());
        assert!(ChromeFingerprint::new(ChromePlatform::Linux, "not-a-version").is_none());
    }

    #[test]
    fn the_default_fingerprint_is_coherent() {
        let fp = ChromeFingerprint::default();
        assert!(fp.is_coherent());
        assert_eq!(fp.full_version(), chrome_full_version());
    }

    // -- cookie jar ------------------------------------------------------

    #[test]
    fn expiry_is_read_from_the_cookie_not_from_a_timer() {
        let now = Utc::now();
        let mut jar = CookieJar::new();
        jar.insert(
            StoredCookie::new("fresh", "v", "example.com").with_expiry(now + Duration::hours(2)),
        );
        jar.insert(
            StoredCookie::new("stale", "v", "example.com").with_expiry(now - Duration::seconds(1)),
        );
        jar.insert(StoredCookie::new("session", "v", "example.com"));

        assert_eq!(jar.prune_expired(now), 1);
        assert_eq!(jar.len(), 2);
        assert!(jar.get("example.com", "/", "fresh").is_some());
        assert!(jar.get("example.com", "/", "session").is_some());
        assert!(jar.get("example.com", "/", "stale").is_none());
    }

    #[test]
    fn challenge_cookies_survive_a_reset() {
        let mut jar = CookieJar::new();
        jar.insert(StoredCookie::new("cf_clearance", "proof", "example.com"));
        jar.insert(StoredCookie::new("datadome", "proof", "example.com"));
        jar.insert(StoredCookie::new("session_id", "s", "example.com"));
        jar.insert(StoredCookie::new("ab_test", "b", "example.com"));

        jar.clear_except_challenges();

        assert_eq!(jar.len(), 2);
        assert!(jar.iter().all(StoredCookie::is_challenge));
    }

    #[test]
    fn challenge_validity_reflects_real_expiry() {
        let now = Utc::now();
        let mut jar = CookieJar::new();
        assert!(
            !jar.challenge_is_valid("example.com", now),
            "no challenge cookie at all means no valid challenge"
        );

        jar.insert(
            StoredCookie::new("cf_clearance", "proof", "example.com")
                .with_expiry(now + Duration::minutes(30)),
        );
        assert!(jar.challenge_is_valid("example.com", now));
        assert!(jar.challenge_is_valid("www.example.com", now));

        jar.insert(
            StoredCookie::new("cf_clearance", "proof", "example.com")
                .with_expiry(now - Duration::minutes(1)),
        );
        assert!(!jar.challenge_is_valid("example.com", now));
    }

    #[test]
    fn cookie_identity_is_domain_path_name() {
        let mut jar = CookieJar::new();
        jar.insert(StoredCookie::new("a", "1", "example.com"));
        jar.insert(StoredCookie::new("a", "2", "example.com"));
        assert_eq!(jar.len(), 1, "same identity must replace");
        assert_eq!(
            jar.get("example.com", "/", "a").map(|c| c.value.as_str()),
            Some("2")
        );

        jar.insert(StoredCookie::new("a", "3", "example.com").with_path("/sub"));
        assert_eq!(jar.len(), 2, "a different path is a different cookie");

        jar.insert(StoredCookie::new("a", "4", "other.com"));
        assert_eq!(jar.len(), 3, "a different domain is a different cookie");
    }

    #[test]
    fn cookie_value_is_not_printed_by_debug() {
        let cookie = StoredCookie::new("cf_clearance", "topsecretvalue", "example.com");
        let rendered = format!("{cookie:?}");
        assert!(
            !rendered.contains("topsecretvalue"),
            "Debug leaked a cookie value: {rendered}"
        );
        assert!(rendered.contains("[REDACTED]"));
        assert!(rendered.contains("cf_clearance"), "the name is diagnostic");
    }

    #[test]
    fn jar_round_trips_through_disk_with_owner_only_permissions() {
        let dir = std::env::temp_dir().join(format!(
            "ylc-net-session-{}-{}",
            std::process::id(),
            Utc::now().timestamp_nanos_opt().unwrap_or_default()
        ));
        let path = dir.join("nested").join(cookie_file_name());

        let mut jar = CookieJar::new();
        jar.insert(StoredCookie::new("cf_clearance", "proof", "example.com"));
        jar.save(&path).expect("save must succeed");

        let loaded = CookieJar::load(&path).expect("load must succeed");
        assert_eq!(loaded.len(), 1);
        assert_eq!(
            loaded
                .get("example.com", "/", "cf_clearance")
                .map(|c| c.value.as_str()),
            Some("proof")
        );

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = fs::metadata(&path)
                .expect("metadata must be readable")
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(mode, cookie_file_mode(), "jar must be owner-only");
        }

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_missing_jar_file_is_an_empty_jar_not_an_error() {
        let path = std::env::temp_dir().join("ylc-net-session-does-not-exist.json");
        let _ = fs::remove_file(&path);
        let jar = CookieJar::load(&path).expect("a missing file must not be an error");
        assert!(jar.is_empty());
    }

    // -- production client factory gate ----------------------------------

    /// The slice of a source file that is production code.
    ///
    /// The classifier is the first `#[cfg(test)]` attribute: everything
    /// from that byte onward counts as test code. It is a lexical
    /// heuristic, not a parse, and its weakness is stated plainly — a
    /// file that puts production code *after* a test module, or that
    /// carries an item-level `#[cfg(test)]` near the top, hides
    /// everything below it from the gate. Every file in this crate keeps
    /// its test module last, which is what makes the cheap rule hold.
    fn production_prefix(source: &str) -> &str {
        match source.find("#[cfg(test)]") {
            Some(idx) => &source[..idx],
            None => source,
        }
    }

    /// Every `.rs` file under `src/`, depth first.
    fn rust_sources(root: &Path) -> Vec<PathBuf> {
        let mut stack = vec![root.to_path_buf()];
        let mut found = Vec::new();
        while let Some(dir) = stack.pop() {
            let entries = fs::read_dir(&dir).expect("src/ must be readable");
            for entry in entries {
                let path = entry.expect("a directory entry must be readable").path();
                if path.is_dir() {
                    stack.push(path);
                } else if path.extension().is_some_and(|ext| ext == "rs") {
                    found.push(path);
                }
            }
        }
        found
    }

    /// No production code may build its own HTTP client.
    ///
    /// GAP-2026-127 happened because the Chrome identity was opt-in and
    /// four call sites each opted in differently. A factory only closes
    /// that gap while it is the *single* way in, so this test fails the
    /// build the moment a fifth call site opens its own builder.
    #[test]
    fn every_production_http_client_comes_from_the_factory() {
        const FORBIDDEN: [&str; 2] = ["reqwest::Client::builder", "reqwest::Client::new"];

        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        let sources = rust_sources(&root);

        let mut files_scanned = 0_usize;
        let mut occurrences_seen = 0_usize;
        let mut offenders: Vec<String> = Vec::new();

        for path in &sources {
            // This file *is* the factory; it is the one place allowed to
            // reach for the builder.
            if path.ends_with("net/session.rs") {
                continue;
            }
            let source = fs::read_to_string(path).expect("a source file must be readable");
            files_scanned += 1;

            let production = production_prefix(&source);
            for (number, line) in source.lines().enumerate() {
                for needle in FORBIDDEN {
                    if !line.contains(needle) {
                        continue;
                    }
                    occurrences_seen += 1;
                    // `line` is a slice of `source`; compare its start
                    // against the production/test boundary.
                    let offset = line.as_ptr() as usize - source.as_ptr() as usize;
                    if offset < production.len() {
                        offenders.push(format!(
                            "{}:{}: {needle} outside net::session::chrome_client",
                            path.display(),
                            number + 1
                        ));
                    }
                }
            }
        }

        // A walker that returns nothing makes this test pass while
        // measuring nothing, so both floors are asserted before the
        // verdict.
        assert!(
            files_scanned >= 40,
            "the gate scanned only {files_scanned} files; the walker is broken"
        );
        assert!(
            occurrences_seen >= 1,
            "the gate matched no `reqwest::Client::` at all; the needles are stale"
        );
        assert!(
            offenders.is_empty(),
            "production HTTP clients built outside the factory:\n{}",
            offenders.join("\n")
        );
    }

    #[test]
    fn cookie_names_feed_the_waf_classifier() {
        let mut jar = CookieJar::new();
        jar.insert(StoredCookie::new("datadome", "x", "example.com"));
        let names = jar.cookie_names();
        let hit = crate::net::waf::detect(&[], &names).expect("must classify");
        assert_eq!(hit.vendor, crate::net::waf::WafVendor::DataDome);
    }
}