perimeterx-fastly-enforcer 2.2.2

PerimeterX Fastly Compute@Edge Rust Enforcer
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
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
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
#[cfg(feature = "kv_store")]
use crate::modules::kvstore_ext::KVStoreGetExt;
use crate::modules::pxconstants::{
    CUSTOM_COOKIE_HEADER, GRAPHQL_BODY_MAX_LENGTH, MCP_ENDPOINT_PATH, WHITELIST_EXT,
};
use crate::px_error;
use crate::pxcontext::{PXContext, PXModuleMode, TokenVersion};
#[cfg(target_arch = "wasm32")]
use fastly::secret_store::SecretStore;
#[cfg(not(feature = "kv_store"))]
use fastly::ConfigStore;
#[cfg(feature = "kv_store")]
use fastly::KVStore;
use fastly::{Request, Response};
use regex::Regex;
use serde::{
    de::{self, Deserializer, MapAccess, Visitor},
    ser::{SerializeMap, Serializer},
    Deserialize, Serialize,
};
use std::collections::HashSet;
use std::fmt;
use strum::{EnumProperty, IntoEnumIterator};
use strum_macros::{AsRefStr, Display, EnumIter, EnumProperty as EnumPropertyMacro};

/// Custom parameters structure
#[derive(Default, Clone)]
pub struct PXCustomParams {
    pub custom_param1: String,
    pub custom_param2: String,
    pub custom_param3: String,
    pub custom_param4: String,
    pub custom_param5: String,
    pub custom_param6: String,
    pub custom_param7: String,
    pub custom_param8: String,
    pub custom_param9: String,
    pub custom_param10: String,
}

/// callback function to fill PXCustomParams structure
pub type PXEnrichCustomParamsFn = fn(req: &Request, conf: &PXConfig, params: &mut PXCustomParams);
/// callback function to determine if a request is sensitive
pub type PXIsSensitiveRequestFn = fn(req: &Request, conf: &PXConfig) -> bool;
/// callback function to determine if a request should be filtered
pub type PXIsFilteredRequestFn = fn(req: &Request, conf: &PXConfig) -> bool;
/// callback function to determine if a request should be enforced
pub type PXIsEnforcedRequestFn = fn(req: &Request, conf: &PXConfig) -> bool;
/// callback function to determine if a request should be monitored
pub type PXIsMonitoredRequestFn = fn(req: &Request, conf: &PXConfig) -> bool;
/// callback function executed after sending page_requested or block activity to the collector
pub type PXAdditionalActivityHandlerFn = fn(req: &Request, conf: &PXConfig, ctx: &PXContext);
/// callback function to create a custom preflight response
pub type PXCorsCustomPreflightHandlerFn = fn(req: &Request, conf: &PXConfig) -> Option<Response>;
/// callback function to create custom CORS headers for block responses
pub type PXCorsCustomBlockResponseHeadersFn =
    fn(req: &Request, conf: &PXConfig) -> Vec<(String, String)>;

/// Raw credentials extracted from a login request (before hashing).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PXRawCredentials {
    pub user: Option<String>,
    pub pass: Option<String>,
}

impl PXRawCredentials {
    /// Treat empty strings as missing credential fields.
    pub fn without_empty_fields(mut self) -> Self {
        if self.user.as_deref().is_some_and(str::is_empty) {
            self.user = None;
        }
        if self.pass.as_deref().is_some_and(str::is_empty) {
            self.pass = None;
        }
        self
    }
}

/// Custom credential extraction for `sent_through: custom` endpoints.
pub type PXExtractCredentialsFn =
    fn(req: &Request, endpoint_index: usize) -> Option<PXRawCredentials>;

/// Custom login-success evaluation for `login_successful_reporting_method: custom`.
pub type PXLoginSuccessfulFn = fn(resp: &Response, endpoint_index: usize) -> Option<bool>;

/// Credential endpoint configuration object (`px_login_credentials_extraction` item).
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct PXCredentialEndpointConfig {
    pub path: String,
    #[serde(default)]
    pub path_type: String,
    pub method: String,
    #[serde(default)]
    pub sent_through: String,
    #[serde(default)]
    pub user_field: String,
    #[serde(default)]
    pub pass_field: String,
    #[serde(default)]
    pub protocol: String,
    #[serde(default)]
    pub login_successful_reporting_method: String,
    #[serde(default)]
    pub login_successful_statuses: Vec<u16>,
    #[serde(default)]
    pub login_successful_body_regex: String,
    #[serde(default)]
    pub login_successful_header_name: String,
    #[serde(default)]
    pub login_successful_header_value: String,
}

/// Runtime-compiled credential endpoint (regex path, etc.).
#[derive(Clone)]
pub struct PXPreparedCredentialEndpoint {
    pub config: PXCredentialEndpointConfig,
    pub path_regex: Option<Regex>,
}

/// Stringly-typed key for every configurable field on [`PXConfig`].
///
/// Each variant's [`AsRef<str>`] / [`Display`] representation is the canonical
/// snake-case name with a leading `px_` prefix — matching both the
/// ConfigStore/KVStore key used to populate the field and the JSON key used by
/// the custom `Serialize`/`Deserialize` impls below.
///
/// Special flags:
/// - `#[strum(props(static = "true"))]`: static fields that are included in the static configuration
/// - `#[strum(props(sensitive = "true"))]`: sensitive fields that are redacted in the serialized output
/// - `#[strum(props(required = "true"))]`: required fields that must be present in the configuration
/// - `#[strum(props(local = "true"))]`: local fields that are only available in the local Enforcer
#[derive(
    Display, AsRefStr, EnumIter, EnumPropertyMacro, Clone, Copy, PartialEq, Eq, Hash, Debug,
)]
#[strum(serialize_all = "snake_case")]
#[strum(prefix = "px_")]
#[doc(hidden)]
pub enum PXConfigKey {
    #[strum(props(static = "true", required = "true"))]
    AppId,
    #[strum(props(sensitive = "true", static = "true", required = "true"))]
    CookieSecret,
    #[strum(props(sensitive = "true", static = "true", required = "true"))]
    AuthToken,
    Debug,
    BlockingScore,
    ModuleEnabled,
    ModuleMode,
    SensitiveHeaders,
    SensitiveRoutes,
    SensitiveRoutesRegex,
    FilterByRoute,
    FilterByExtension,
    FilterByUserAgent,
    FilterByIp,
    FilterByHttpMethod,
    CustomCookieHeader,
    EnforcedRoutes,
    MonitoredRoutes,
    BypassMonitorHeader,
    FirstPartyEnabled,
    CustomLogo,
    JsRef,
    CssRef,
    #[strum(props(local = "true"))]
    HumanSapiHost,
    #[strum(props(local = "true"))]
    HumanSapiBackend,
    #[strum(props(local = "true"))]
    HumanCollectorHost,
    #[strum(props(local = "true"))]
    HumanCollectorBackend,
    #[strum(props(local = "true"))]
    HumanClientHost,
    #[strum(props(local = "true"))]
    HumanClientBackend,
    #[strum(props(local = "true"))]
    HumanCaptchaHost,
    #[strum(props(local = "true"))]
    HumanCaptchaBackend,
    IpHeaders,
    LogEndpoint,
    DataEnrichmentHeaderName,
    ExtractedCookies,
    CorsSupportEnabled,
    CorsPreflightRequestFilterEnabled,
    GraphqlEnabled,
    GraphqlRoutes,
    SensitiveGraphqlOperationNames,
    SensitiveGraphqlOperationTypes,
    GraphqlBodyMaxLength,
    GraphqlKeywords,
    S2sTimeout,
    TokenVersion,
    CustomFirstPartyCaptchaEndpoint,
    CustomFirstPartySensorEndpoint,
    CustomFirstPartyXhrEndpoint,
    UserAgentMaxLength,
    RiskCookieMaxLength,
    RiskCookieMinIterations,
    RiskCookieMaxIterations,
    AgenticTrustEnabled,
    AgenticTrustMcpEndpointPath,
    SecuredPxhdEnabled,
    PxhdDomain,
    JwtCookieName,
    JwtCookieUserIdFieldName,
    JwtCookieAdditionalFieldNames,
    JwtHeaderName,
    JwtHeaderUserIdFieldName,
    JwtHeaderAdditionalFieldNames,
    #[strum(props(sensitive = "true", static = "true"))]
    LoggerAuthToken,
    LoginCredentialsExtractionEnabled,
    LoginCredentialsExtraction,
    CredentialsIntelligenceVersion,
    CompromisedCredentialsHeader,
    SendRawUsernameOnAdditionalS2sActivity,
    AdditionalS2sActivityEnabled,
    AdditionalS2sActivityHeaderEnabled,
    LoginSuccessfulReportingMethod,
    LoginSuccessfulBodyRegex,
    LoginSuccessfulHeaderName,
    LoginSuccessfulHeaderValue,
    LoginSuccessfulStatus,
}

impl PXConfigKey {
    /// Returns `true` if this key represents a sensitive field whose value
    /// must be redacted before being serialized to telemetry / logs.
    pub fn is_sensitive(&self) -> bool {
        self.get_str("sensitive") == Some("true")
    }

    /// Returns `true` if this key is marked as static (e.g. for minimal
    /// config payloads such as startup telemetry).
    pub fn is_static(&self) -> bool {
        self.get_str("static") == Some("true")
    }

    /// Returns `true` if this key must be configured before the enforcer can
    /// operate correctly.
    pub fn is_required(&self) -> bool {
        self.get_str("required") == Some("true")
    }

    /// Returns `true` if this key is local-only and should be excluded from
    /// serialized output (e.g. telemetry payloads sent to the collector).
    pub fn is_local(&self) -> bool {
        self.get_str("local") == Some("true")
    }
}

/// Typed view of a value pulled from [`PXConfig`] via [`PXConfig::get`] or
/// [`PXConfig::fields`]. Borrows from the backing config so it is cheap to
/// produce.
pub enum PXConfigValue<'a> {
    Bool(bool),
    U8(u8),
    U16(u16),
    U16Vec(&'a [u16]),
    U32(u32),
    USize(usize),
    Str(&'a str),
    StrVec(&'a [String]),
    RegexVec(&'a [Regex]),
    ModuleMode(PXModuleMode),
    TokenVersion(TokenVersion),
    CiEndpoints(&'a [PXCredentialEndpointConfig]),
}

impl fmt::Display for PXConfigValue<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bool(v) => write!(f, "Bool({v})"),
            Self::U8(v) => write!(f, "U8({v})"),
            Self::U16(v) => write!(f, "U16({v})"),
            Self::U16Vec(v) => write!(f, "U16Vec({v:?})"),
            Self::U32(v) => write!(f, "U32({v})"),
            Self::USize(v) => write!(f, "USize({v})"),
            Self::Str(v) => write!(f, "Str({v})"),
            Self::StrVec(v) => write!(f, "StrVec({v:?})"),
            Self::RegexVec(v) => {
                let pats: Vec<&str> = v.iter().map(Regex::as_str).collect();
                write!(f, "RegexVec({pats:?})")
            }
            Self::ModuleMode(v) => write!(f, "ModuleMode({})", v.as_ref()),
            Self::TokenVersion(v) => write!(f, "TokenVersion({})", v.as_ref()),
            Self::CiEndpoints(v) => write!(f, "CiEndpoints({v:?})"),
        }
    }
}

impl Serialize for PXConfigValue<'_> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Bool(v) => v.serialize(s),
            Self::U8(v) => v.serialize(s),
            Self::U16(v) => v.serialize(s),
            Self::U16Vec(v) => v.serialize(s),
            Self::U32(v) => v.serialize(s),
            Self::USize(v) => v.serialize(s),
            Self::Str(v) => v.serialize(s),
            Self::StrVec(v) => v.serialize(s),
            Self::RegexVec(v) => {
                let pats: Vec<String> = v
                    .iter()
                    .map(|r| format!("{REGEX_PREFIX}{}", r.as_str()))
                    .collect();
                pats.serialize(s)
            }
            Self::ModuleMode(v) => v.serialize(s),
            Self::TokenVersion(v) => v.serialize(s),
            Self::CiEndpoints(v) => v.serialize(s),
        }
    }
}

const REDACTED: &str = "***REDACTED***";
const REDACT_THRESHOLD: usize = 50;
const REDACT_TAIL_LEN: usize = 5;
pub(crate) const REGEX_PREFIX: &str = "_REGEXP ";

fn redact(s: &str) -> String {
    let char_count = s.chars().count();
    if char_count >= REDACT_THRESHOLD {
        let tail: String = s.chars().skip(char_count - REDACT_TAIL_LEN).collect();
        format!("{REDACTED}{tail}")
    } else if char_count > 0 {
        REDACTED.to_owned()
    } else {
        s.to_owned()
    }
}

struct Redacted<'a>(&'a PXConfigValue<'a>);

impl Serialize for Redacted<'_> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self.0 {
            PXConfigValue::Bool(v) => redact(&v.to_string()).serialize(s),
            PXConfigValue::U8(v) => redact(&v.to_string()).serialize(s),
            PXConfigValue::U16(v) => redact(&v.to_string()).serialize(s),
            PXConfigValue::U16Vec(v) => v
                .iter()
                .map(|n| redact(&n.to_string()))
                .collect::<Vec<_>>()
                .serialize(s),
            PXConfigValue::U32(v) => redact(&v.to_string()).serialize(s),
            PXConfigValue::USize(v) => redact(&v.to_string()).serialize(s),
            PXConfigValue::Str(v) => redact(v).serialize(s),
            PXConfigValue::StrVec(v) => v
                .iter()
                .map(|item| redact(item))
                .collect::<Vec<_>>()
                .serialize(s),
            PXConfigValue::RegexVec(v) => v
                .iter()
                .map(|item| redact(item.as_str()))
                .collect::<Vec<_>>()
                .serialize(s),
            PXConfigValue::ModuleMode(v) => redact(v.as_ref()).serialize(s),
            PXConfigValue::TokenVersion(v) => redact(v.as_ref()).serialize(s),
            PXConfigValue::CiEndpoints(v) => v.serialize(s),
        }
    }
}

impl Serialize for PXModuleMode {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_ref())
    }
}

impl<'de> Deserialize<'de> for PXModuleMode {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        s.parse().map_err(de::Error::custom)
    }
}

impl Serialize for TokenVersion {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_ref())
    }
}

impl<'de> Deserialize<'de> for TokenVersion {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        s.parse().map_err(de::Error::custom)
    }
}

/// Enforcer configuration.
///
/// Configuration must be set before calling `PXEnforcer::enforce()`.
///
/// Most fields are populated from the underlying ConfigStore / KVStore via
/// [`PXConfig::new`]. Callback function fields are runtime-only and excluded
/// from iteration / serialization.
pub struct PXConfig {
    #[cfg(not(feature = "kv_store"))]
    /// Backing Fastly ConfigStore used to load `px_*` keys at startup.
    pub store: Option<ConfigStore>,
    #[cfg(feature = "kv_store")]
    /// Backing Fastly KVStore used to load and persist `px_*` keys.
    pub store: Option<KVStore>,

    /// `px_app_id`: HUMAN application ID used in activities, Risk API calls, and derived hosts.
    pub app_id: String,
    /// `px_cookie_secret`: secret used to validate risk cookies, PXDE cookies, and telemetry commands.
    pub cookie_secret: String,
    /// `px_auth_token`: bearer token used when sending Risk API, async activity, and telemetry requests.
    pub auth_token: String,
    /// `px_debug`: enables verbose PerimeterX debug logs in this Fastly implementation.
    pub debug: bool,
    /// `px_blocking_score`: minimum score, inclusive, that should block for Cookie V3/Risk API flows.
    pub blocking_score: u8,
    /// `px_module_enabled`: master on/off switch; disabled modules pass requests without verification.
    pub module_enabled: bool,
    /// `px_module_mode`: active blocking blocks high-risk requests; monitor simulates blocks and passes.
    pub module_mode: PXModuleMode,
    /// `px_sensitive_headers`: request header names removed from Risk API and async activity payloads.
    pub sensitive_headers: Vec<String>,
    /// `px_sensitive_routes`: path prefixes that always trigger Risk API after valid low-risk cookies.
    pub sensitive_routes: Vec<String>,
    /// `px_sensitive_routes_regex`: compiled regex routes with the same sensitive-route semantics.
    pub sensitive_routes_regex: Vec<Regex>,
    /// `px_filter_by_route`: path prefixes filtered from the enforcement flow before context creation.
    pub filter_by_route: Vec<String>,
    /// `px_filter_by_extension`: file extensions filtered from verification before context creation.
    pub filter_by_extension: Vec<String>,
    /// `px_filter_by_user_agent`: user-agent values filtered from verification before context creation.
    pub filter_by_user_agent: Vec<String>,
    /// `px_filter_by_ip`: client IP values filtered from verification before context creation.
    pub filter_by_ip: Vec<String>,
    /// `px_filter_by_http_method`: HTTP methods filtered from verification before context creation.
    pub filter_by_http_method: Vec<String>,
    /// `px_custom_cookie_header`: alternate header used to read PX cookies instead of the `Cookie` header.
    pub custom_cookie_header: String,
    /// `px_enforced_routes`: routes treated as active blocking even while the module is in monitor mode.
    pub enforced_routes: Vec<String>,
    /// `px_monitored_routes`: routes treated as monitor even while the module is in active blocking mode.
    pub monitored_routes: Vec<String>,
    /// `px_bypass_monitor_header`: header name whose value `1` forces blocking flow in monitor mode.
    pub bypass_monitor_header: String,
    /// `px_first_party_enabled`: enables first-party proxying for sensor, captcha, and XHR endpoints.
    pub first_party_enabled: bool,
    /// `px_custom_logo`: block-page logo URL; empty keeps the logo hidden.
    pub custom_logo: String,
    /// `px_js_ref`: custom block-page JavaScript URL loaded after default scripts.
    pub js_ref: String,
    /// `px_css_ref`: custom block-page CSS URL loaded by the rendered block template.
    pub css_ref: String,
    /// `px_ip_headers`: trusted header names, checked in order, for extracting the real client IP.
    pub ip_headers: Vec<String>,
    /// `px_log_endpoint`: Fastly logging endpoint used by platform-specific activity delivery.
    pub log_endpoint: String,
    /// `px_data_enrichment_header_name`: request header to receive verified PXDE JSON; empty disables it.
    pub data_enrichment_header_name: String,
    /// `px_extracted_cookies`: cookie names copied into Risk API additional fields.
    pub extracted_cookies: Vec<String>,
    /// `px_cors_support_enabled`: enables CORS handling for preflight and block responses.
    pub cors_support_enabled: bool,
    /// `px_cors_preflight_request_filter_enabled`: passes CORS preflight requests before verification.
    pub cors_preflight_request_filter_enabled: bool,
    /// `px_graphql_enabled`: enables extraction of GraphQL operation data from matching POST requests.
    pub graphql_enabled: bool,
    /// `px_graphql_routes`: regex routes that identify requests eligible for GraphQL extraction.
    pub graphql_routes: Vec<Regex>,
    /// `px_sensitive_graphql_operation_names`: operation names that mark GraphQL requests as sensitive.
    pub sensitive_graphql_operation_names: Vec<String>,
    /// `px_sensitive_graphql_operation_types`: operation types that mark GraphQL requests as sensitive.
    pub sensitive_graphql_operation_types: Vec<String>,
    /// `px_graphql_body_max_length`: maximum body prefix read while parsing GraphQL JSON.
    pub graphql_body_max_length: usize,
    /// `px_graphql_keywords`: regex patterns matched against GraphQL query text for activity keywords.
    pub graphql_keywords: Vec<Regex>,
    /// `px_s2s_timeout`: Risk API timeout in milliseconds; timeouts fail open.
    pub s2s_timeout: u32,
    /// `px_token_version`: risk-cookie/mobile token format version expected by validators.
    pub token_version: TokenVersion,
    /// `px_custom_first_party_captcha_endpoint`: custom path treated as first-party captcha proxy.
    pub custom_first_party_captcha_endpoint: String,
    /// `px_custom_first_party_sensor_endpoint`: custom path treated as first-party sensor proxy.
    pub custom_first_party_sensor_endpoint: String,
    /// `px_custom_first_party_xhr_endpoint`: custom path treated as first-party XHR proxy.
    pub custom_first_party_xhr_endpoint: String,
    /// `px_user_agent_max_length`: maximum user-agent length used for risk-cookie validation.
    pub user_agent_max_length: usize,
    /// `px_risk_cookie_max_length`: maximum risk-cookie value length accepted before validation fails.
    pub risk_cookie_max_length: usize,
    /// `px_risk_cookie_min_iterations`: minimum accepted PBKDF2 iteration count for Cookie V3.
    pub risk_cookie_min_iterations: usize,
    /// `px_risk_cookie_max_iterations`: maximum accepted PBKDF2 iteration count for Cookie V3.
    pub risk_cookie_max_iterations: usize,
    /// `px_agentic_trust_enabled`: enables agentic trust verification for MCP requests.
    pub agentic_trust_enabled: bool,
    /// `px_agentic_trust_mcp_endpoint_path`: MCP endpoint path used for agentic trust verification.
    pub agentic_trust_mcp_endpoint_path: String,
    /// `px_logger_auth_token`: token required by header-based enforcer log collection.
    pub logger_auth_token: String,
    /// `px_secured_pxhd_enabled`: when true, `_pxhd` response cookies include the `Secure` attribute.
    pub secured_pxhd_enabled: bool,
    /// `px_pxhd_domain`: when non-empty, overrides Risk API `pxhdDomain` on `_pxhd` Set-Cookie.
    pub pxhd_domain: String,
    /// `px_jwt_cookie_name`: cookie name that carries the customer JWT.
    pub jwt_cookie_name: String,
    /// `px_jwt_cookie_user_id_field_name`: dot path in the JWT payload for the app user ID.
    pub jwt_cookie_user_id_field_name: String,
    /// `px_jwt_cookie_additional_field_names`: dot paths of extra JWT payload fields to extract.
    pub jwt_cookie_additional_field_names: Vec<String>,
    /// `px_jwt_header_name`: request header name that carries the customer JWT.
    pub jwt_header_name: String,
    /// `px_jwt_header_user_id_field_name`: dot path in the JWT payload for the app user ID.
    pub jwt_header_user_id_field_name: String,
    /// `px_jwt_header_additional_field_names`: dot paths of extra JWT payload fields to extract.
    pub jwt_header_additional_field_names: Vec<String>,

    /// `px_human_sapi_host`: HUMAN SAPI host for Risk API and telemetry requests.
    pub human_sapi_host: String,
    /// `px_human_sapi_backend`: Fastly backend for HUMAN SAPI requests.
    pub human_sapi_backend: String,
    /// `px_human_collector_host`: HUMAN collector host for activity and XHR requests.
    pub human_collector_host: String,
    /// `px_human_collector_backend`: Fastly backend for HUMAN collector requests.
    pub human_collector_backend: String,
    /// `px_human_client_host`: HUMAN client host for first-party sensor requests.
    pub human_client_host: String,
    /// `px_human_client_backend`: Fastly backend for HUMAN client requests.
    pub human_client_backend: String,
    /// `px_human_captcha_host`: HUMAN captcha host for block-page and first-party captcha requests.
    pub human_captcha_host: String,
    /// `px_human_captcha_backend`: Fastly backend for HUMAN captcha requests.
    pub human_captcha_backend: String,
    /// `px_login_credentials_extraction_enabled`: master switch for Credentials Intelligence.
    pub login_credentials_extraction_enabled: bool,
    /// `px_login_credentials_extraction`: credential endpoint definitions.
    pub login_credentials_extraction: Vec<PXCredentialEndpointConfig>,
    /// Compiled credential endpoints (regex paths, etc.).
    pub prepared_ci_endpoints: Vec<PXPreparedCredentialEndpoint>,
    /// `px_credentials_intelligence_version`: default hashing protocol (`v2`, `multistep_sso`, `both`).
    pub credentials_intelligence_version: String,
    /// `px_compromised_credentials_header`: origin request header when credentials are breached.
    pub compromised_credentials_header: String,
    /// `px_send_raw_username_on_additional_s2s_activity`: include raw username on additional_s2s when allowed.
    pub send_raw_username_on_additional_s2s_activity: bool,
    /// `px_additional_s2s_activity_enabled`: send additional_s2s automatically after response.
    pub additional_s2s_activity_enabled: bool,
    /// `px_additional_s2s_activity_header_enabled`: attach additional_s2s payload to origin request headers.
    pub additional_s2s_activity_header_enabled: bool,
    /// `px_login_successful_reporting_method`: default login-success detection method.
    pub login_successful_reporting_method: String,
    /// `px_login_successful_body_regex`: default body regex for login-success detection.
    pub login_successful_body_regex: String,
    /// `px_login_successful_header_name`: default response header name for login-success detection.
    pub login_successful_header_name: String,
    /// `px_login_successful_header_value`: default response header value for login-success detection.
    pub login_successful_header_value: String,
    /// `px_login_successful_status`: default HTTP status codes meaning login success.
    pub login_successful_status: Vec<u16>,

    // Runtime-only callbacks
    /// `px_enrich_custom_parameters`: fills up to ten custom params on Risk and async activities.
    pub enrich_params_fn: Option<PXEnrichCustomParamsFn>,
    /// `px_custom_is_sensitive_request`: runtime callback for marking a request sensitive.
    pub is_sensitive_request_fn: Option<PXIsSensitiveRequestFn>,
    /// `px_custom_is_enforced_request`: runtime callback for marking a request enforced.
    pub is_enforced_request_fn: Option<PXIsEnforcedRequestFn>,
    /// `px_custom_is_monitored_request`: runtime callback for marking a request monitored.
    pub is_monitored_request_fn: Option<PXIsMonitoredRequestFn>,
    /// `px_filter_by_custom_function`: runtime callback for filtering a request before verification.
    pub is_filtered_request_fn: Option<PXIsFilteredRequestFn>,
    /// `px_additional_activity_handler`: runs after page_requested or block activity is sent.
    pub additional_activity_handler_fn: Option<PXAdditionalActivityHandlerFn>,
    /// `px_cors_custom_preflight_handler`: custom response hook for CORS preflight requests.
    pub cors_custom_preflight_handler_fn: Option<PXCorsCustomPreflightHandlerFn>,
    /// `px_cors_create_custom_block_response_headers`: custom CORS headers for block responses.
    pub cors_create_custom_block_response_headers_fn: Option<PXCorsCustomBlockResponseHeadersFn>,
    /// Runtime callback for custom credential extraction (`sent_through: custom`).
    pub ci_extract_credentials_fn: Option<PXExtractCredentialsFn>,
    /// Runtime callback for custom login-success reporting.
    pub ci_login_successful_fn: Option<PXLoginSuccessfulFn>,
}

impl Default for PXConfig {
    fn default() -> Self {
        Self {
            store: None,
            app_id: String::new(),
            cookie_secret: String::new(),
            auth_token: String::new(),
            debug: false,
            blocking_score: 100,
            module_enabled: false,
            module_mode: PXModuleMode::Monitor,
            sensitive_headers: vec!["Cookie".to_owned(), "Cookies".to_owned()],
            sensitive_routes: Vec::new(),
            sensitive_routes_regex: Vec::new(),
            filter_by_route: Vec::new(),
            filter_by_extension: WHITELIST_EXT.iter().map(|ext| (*ext).to_owned()).collect(),
            filter_by_user_agent: Vec::new(),
            filter_by_ip: Vec::new(),
            filter_by_http_method: Vec::new(),
            custom_cookie_header: CUSTOM_COOKIE_HEADER.to_owned(),
            enforced_routes: Vec::new(),
            monitored_routes: Vec::new(),
            bypass_monitor_header: "x-px-block".to_owned(),
            first_party_enabled: true,
            custom_logo: String::new(),
            js_ref: String::new(),
            css_ref: String::new(),
            human_sapi_host: default_human_sapi_host(""),
            human_sapi_backend: "human_sapi".to_owned(),
            human_collector_host: default_human_collector_host(""),
            human_collector_backend: "human_collector".to_owned(),
            human_client_host: "client.perimeterx.net".to_owned(),
            human_client_backend: "human_client".to_owned(),
            human_captcha_host: "captcha.px-cdn.net".to_owned(),
            human_captcha_backend: "human_captcha".to_owned(),
            ip_headers: Vec::new(),
            log_endpoint: String::new(),
            data_enrichment_header_name: String::new(),
            extracted_cookies: Vec::new(),
            cors_support_enabled: false,
            cors_preflight_request_filter_enabled: false,
            graphql_enabled: false,
            graphql_routes: default_graphql_routes(),
            sensitive_graphql_operation_names: Vec::new(),
            sensitive_graphql_operation_types: Vec::new(),
            graphql_body_max_length: GRAPHQL_BODY_MAX_LENGTH,
            graphql_keywords: Vec::new(),
            s2s_timeout: 2000,
            token_version: TokenVersion::V3,
            custom_first_party_captcha_endpoint: String::new(),
            custom_first_party_sensor_endpoint: String::new(),
            custom_first_party_xhr_endpoint: String::new(),
            user_agent_max_length: 8528,
            risk_cookie_max_length: 2048,
            risk_cookie_min_iterations: 500,
            risk_cookie_max_iterations: 5000,
            agentic_trust_enabled: false,
            agentic_trust_mcp_endpoint_path: MCP_ENDPOINT_PATH.to_owned(),
            logger_auth_token: String::new(),
            secured_pxhd_enabled: false,
            pxhd_domain: String::new(),
            jwt_cookie_name: String::new(),
            jwt_cookie_user_id_field_name: String::new(),
            jwt_cookie_additional_field_names: Vec::new(),
            jwt_header_name: String::new(),
            jwt_header_user_id_field_name: String::new(),
            jwt_header_additional_field_names: Vec::new(),
            login_credentials_extraction_enabled: false,
            login_credentials_extraction: Vec::new(),
            prepared_ci_endpoints: Vec::new(),
            credentials_intelligence_version: "both".to_owned(),
            compromised_credentials_header:
                crate::modules::pxconstants::DEFAULT_COMPROMISED_CREDENTIALS_HEADER.to_owned(),
            send_raw_username_on_additional_s2s_activity: false,
            additional_s2s_activity_enabled: true,
            additional_s2s_activity_header_enabled: false,
            login_successful_reporting_method: "status".to_owned(),
            login_successful_body_regex: String::new(),
            login_successful_header_name: String::new(),
            login_successful_header_value: String::new(),
            login_successful_status: vec![200],
            enrich_params_fn: None,
            is_sensitive_request_fn: None,
            is_enforced_request_fn: None,
            is_monitored_request_fn: None,
            is_filtered_request_fn: None,
            additional_activity_handler_fn: None,
            cors_custom_preflight_handler_fn: None,
            cors_create_custom_block_response_headers_fn: None,
            ci_extract_credentials_fn: None,
            ci_login_successful_fn: None,
        }
    }
}

fn compile_ci_path_regex(path: &str) -> Option<Regex> {
    let raw = path.strip_prefix(REGEX_PREFIX).unwrap_or(path);
    match Regex::new(raw) {
        Ok(re) => Some(re),
        Err(e) => {
            px_error!("Invalid CI endpoint regex {:?}: {}", raw, e);
            None
        }
    }
}

pub(crate) fn rebuild_prepared_ci_endpoints(conf: &mut PXConfig) {
    conf.prepared_ci_endpoints = conf
        .login_credentials_extraction
        .iter()
        .map(|config| {
            let path_regex = if config.path_type.eq_ignore_ascii_case("regex") {
                compile_ci_path_regex(&config.path)
            } else {
                None
            };
            PXPreparedCredentialEndpoint {
                config: config.clone(),
                path_regex,
            }
        })
        .collect();
}

fn is_empty_ci_endpoints_value(v: &serde_json::Value) -> bool {
    match v {
        serde_json::Value::Object(map) => map.is_empty(),
        serde_json::Value::Array(arr) => {
            arr.is_empty()
                || arr
                    .iter()
                    .all(|item| item.as_object().is_some_and(serde_json::Map::is_empty))
        }
        _ => false,
    }
}

fn parse_ci_endpoints_from_value(
    v: &serde_json::Value,
) -> Result<Vec<PXCredentialEndpointConfig>, serde_json::Error> {
    if is_empty_ci_endpoints_value(v) {
        return Ok(Vec::new());
    }
    if let Some(raw) = v.as_str() {
        if raw.trim().is_empty() {
            return Ok(Vec::new());
        }
        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(raw) {
            return parse_ci_endpoints_from_value(&parsed);
        }
        serde_json::from_str(raw)
    } else {
        serde_json::from_value(v.clone())
    }
}

fn parse_ci_endpoints(raw: &str) -> Vec<PXCredentialEndpointConfig> {
    match parse_ci_endpoints_from_value(&serde_json::Value::String(raw.to_owned())) {
        Ok(endpoints) => endpoints,
        Err(e) => {
            px_error!(
                "failed to parse px_login_credentials_extraction from store: {}",
                e
            );
            Vec::new()
        }
    }
}

fn parse_status_vec(raw: &str) -> Vec<u16> {
    if let Ok(vec) = serde_json::from_str::<Vec<u16>>(raw) {
        return vec;
    }
    raw.split(',')
        .filter_map(|s| s.trim().parse::<u16>().ok())
        .collect()
}

fn default_graphql_routes() -> Vec<Regex> {
    Regex::new("^/graphql$")
        .map(|r| vec![r])
        .unwrap_or_default()
}

/// Parse a raw store value into a `Vec<String>`, handling both
/// JSON-encoded arrays (written by `serde_json::Value::to_string()`)
/// and plain comma-separated values.
pub(crate) fn parse_vec(input: &str) -> Vec<String> {
    if let Ok(vec) = serde_json::from_str::<Vec<String>>(input) {
        return vec.into_iter().filter(|s| !s.is_empty()).collect();
    }
    input
        .split(',')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_owned())
        .collect()
}

fn parse_regex_vec(key_name: &str, input: &str) -> Vec<Regex> {
    let items: Vec<String> = if let Ok(vec) = serde_json::from_str::<Vec<String>>(input) {
        vec.into_iter().filter(|s| !s.is_empty()).collect()
    } else {
        input
            .split(',')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_owned())
            .collect()
    };
    items
        .iter()
        .filter_map(|s| match Regex::new(s) {
            Ok(r) => Some(r),
            Err(_) => {
                px_error!("[{}] Invalid regex {:?}", key_name, s);
                None
            }
        })
        .collect()
}

/// Convert a `serde_json::Value` to a plain-text string suitable for the
/// KVStore.  Strings are stored without JSON quotes; arrays are stored as
/// comma-separated values so `parse_vec` / `parse_regex_vec` can read them
/// back without JSON decoding.
#[cfg(feature = "kv_store")]
pub(crate) fn json_value_to_raw_store(v: &serde_json::Value) -> String {
    match v {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(arr) => {
            let all_strings = arr.iter().all(serde_json::Value::is_string);
            if all_strings {
                arr.iter()
                    .filter_map(|item| item.as_str())
                    .collect::<Vec<_>>()
                    .join(",")
            } else {
                v.to_string()
            }
        }
        other => other.to_string(),
    }
}

/// Strip surrounding double-quote characters that appear when a
/// `serde_json::Value::to_string()` output is stored verbatim in the KVStore.
pub(crate) fn strip_json_quotes(s: &str) -> &str {
    s.strip_prefix('"')
        .and_then(|inner| inner.strip_suffix('"'))
        .unwrap_or(s)
}

fn parse_string(input: &str) -> String {
    if input.eq_ignore_ascii_case("none") {
        String::new()
    } else {
        input.to_owned()
    }
}

fn default_human_sapi_host(app_id: &str) -> String {
    format!("sapi-{app_id}.perimeterx.net")
}

fn default_human_collector_host(app_id: &str) -> String {
    format!("collector-{app_id}.perimeterx.net")
}

/// Compile a sequence of pattern strings into `Regex` objects, dropping (and
/// logging) any that fail to compile. Used by the JSON deserialization paths
/// where `Regex` itself does not implement `Deserialize`. Strips the leading
/// `_REGEXP` prefix added by `PXConfigValue::RegexVec`'s `Serialize` impl.
fn compile_regex_vec<I, S>(patterns: I, key_name: &str) -> Vec<Regex>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    patterns
        .into_iter()
        .filter_map(|p| {
            let raw = p.as_ref().strip_prefix(REGEX_PREFIX).unwrap_or(p.as_ref());
            match Regex::new(raw) {
                Ok(r) => Some(r),
                Err(_) => {
                    px_error!("Invalid regex {:?} for key {}", raw, key_name);
                    None
                }
            }
        })
        .collect()
}

/// Keys loaded from Fastly Secret Store when configured; values override
/// ConfigStore/KVStore for the same `px_*` names.
#[cfg(any(target_arch = "wasm32", test))]
const SECRET_STORE_KEYS: &[PXConfigKey] = &[
    PXConfigKey::AppId,
    PXConfigKey::CookieSecret,
    PXConfigKey::AuthToken,
    PXConfigKey::LoggerAuthToken,
];

#[cfg(any(target_arch = "wasm32", test))]
pub(crate) fn secret_store_keys() -> &'static [PXConfigKey] {
    SECRET_STORE_KEYS
}

/// Apply secret values onto an already-loaded config. Used by [`PXConfig::new`]
/// and unit tests.
#[cfg(any(target_arch = "wasm32", test))]
pub(crate) fn apply_secret_values(conf: &mut PXConfig, secrets: &[(PXConfigKey, &str)]) {
    for (key, raw) in secrets {
        conf.set_from_raw(*key, raw);
    }
}

fn config_value_is_set(value: &PXConfigValue<'_>) -> bool {
    match value {
        PXConfigValue::Str(v) => !v.is_empty(),
        PXConfigValue::StrVec(v) => !v.is_empty(),
        PXConfigValue::RegexVec(v) => !v.is_empty(),
        PXConfigValue::U16Vec(v) => !v.is_empty(),
        PXConfigValue::CiEndpoints(v) => !v.is_empty(),
        PXConfigValue::Bool(_)
        | PXConfigValue::U8(_)
        | PXConfigValue::U16(_)
        | PXConfigValue::U32(_)
        | PXConfigValue::USize(_)
        | PXConfigValue::ModuleMode(_)
        | PXConfigValue::TokenVersion(_) => true,
    }
}

pub(crate) fn load_secrets_from_store(conf: &mut PXConfig, secret_store_name: &str) {
    if secret_store_name.is_empty() {
        return;
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        let _ = conf;
    }

    #[cfg(target_arch = "wasm32")]
    let secret_store = match SecretStore::open(secret_store_name) {
        Ok(store) => store,
        Err(e) => {
            px_error!("Failed to open Secret Store {:?}: {}", secret_store_name, e);
            return;
        }
    };

    #[cfg(target_arch = "wasm32")]
    {
        let mut overlay = Vec::with_capacity(secret_store_keys().len());
        for key in secret_store_keys() {
            let secret_name = key.as_ref();
            match secret_store.try_get(secret_name) {
                Ok(Some(secret)) => match secret.try_plaintext() {
                    Ok(plaintext) => {
                        if let Ok(value) = std::str::from_utf8(plaintext.as_ref()) {
                            overlay.push((*key, value.to_owned()));
                        } else {
                            px_error!(
                                "Secret {:?} in Secret Store {:?} is not valid UTF-8",
                                secret_name,
                                secret_store_name
                            );
                        }
                    }
                    Err(e) => {
                        px_error!(
                            "Failed to decrypt secret {:?} in Secret Store {:?}: {}",
                            secret_name,
                            secret_store_name,
                            e
                        );
                    }
                },
                Ok(None) => {}
                Err(e) => {
                    px_error!(
                        "Failed to lookup secret {:?} in Secret Store {:?}: {}",
                        secret_name,
                        secret_store_name,
                        e
                    );
                }
            }
        }

        let overlay_refs: Vec<(PXConfigKey, &str)> = overlay
            .iter()
            .map(|(key, value)| (*key, value.as_str()))
            .collect();
        apply_secret_values(conf, &overlay_refs);
    }
}

pub(crate) fn recompute_derived(conf: &mut PXConfig, previous_app_id: &str) {
    let previous_sapi_host = default_human_sapi_host(previous_app_id);
    if conf.human_sapi_host.is_empty() || conf.human_sapi_host == previous_sapi_host {
        conf.human_sapi_host = default_human_sapi_host(&conf.app_id);
    }

    let previous_collector_host = default_human_collector_host(previous_app_id);
    if conf.human_collector_host.is_empty() || conf.human_collector_host == previous_collector_host
    {
        conf.human_collector_host = default_human_collector_host(&conf.app_id);
    }
}

impl Serialize for PXConfig {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let entries: Vec<_> = self.fields().filter(|(k, _)| !k.is_local()).collect();
        let mut map = s.serialize_map(Some(entries.len()))?;
        for (key, value) in entries {
            if key.is_sensitive() {
                map.serialize_entry(key.as_ref(), &Redacted(&value))?;
            } else {
                map.serialize_entry(key.as_ref(), &value)?;
            }
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for PXConfig {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct PXConfigVisitor;

        impl<'de> Visitor<'de> for PXConfigVisitor {
            type Value = PXConfig;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a PXConfig map keyed by PXConfigKey names")
            }

            fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<PXConfig, M::Error> {
                let mut out = PXConfig::default();
                // TODO: should we keep the default values?
                // out.sensitive_headers.clear();
                // out.graphql_routes.clear();
                let mut seen: HashSet<PXConfigKey> = HashSet::new();

                while let Some(key) = map.next_key::<String>()? {
                    let variant = PXConfigKey::iter()
                        .find(|v| v.as_ref() == key)
                        .ok_or_else(|| de::Error::custom(format!("unknown field `{key}`")))?;
                    if !seen.insert(variant) {
                        return Err(de::Error::custom(format!("duplicate field `{key}`")));
                    }
                    out.set_from(variant, &mut map)?;
                }

                if let Some(missing) =
                    PXConfigKey::iter().find(|v| !v.is_local() && !seen.contains(v))
                {
                    return Err(de::Error::custom(format!(
                        "missing field `{}`",
                        missing.as_ref()
                    )));
                }

                rebuild_prepared_ci_endpoints(&mut out);
                recompute_derived(&mut out, "");
                Ok(out)
            }
        }

        d.deserialize_map(PXConfigVisitor)
    }
}

impl PXConfig {
    pub fn get_module_mode(&self) -> PXModuleMode {
        self.module_mode
    }

    /// Construct a `PXConfig` by reading every [`PXConfigKey`] from the
    /// backing config store (or KV store when `kv_store` is enabled), then
    /// overlaying `secret_store_keys` from Fastly Secret Store when
    /// `secret_store_name` is non-empty.
    pub fn new(config_store_name: &str, secret_store_name: &str) -> Self {
        let mut conf = PXConfig::default();

        #[cfg(feature = "kv_store")]
        let confg_store = {
            match KVStore::open(config_store_name) {
                Ok(Some(kv)) => kv,
                Ok(None) => {
                    px_error!(
                        "KVStore {:?} not found; falling back to default PXConfig",
                        config_store_name
                    );
                    return Self::default();
                }
                Err(e) => {
                    px_error!(
                        "Failed to open KVStore {:?}: {:?}; falling back to default PXConfig",
                        config_store_name,
                        e
                    );
                    return Self::default();
                }
            }
        };

        #[cfg(not(feature = "kv_store"))]
        let confg_store = ConfigStore::open(config_store_name);

        for key in PXConfigKey::iter() {
            if let Some(raw) = confg_store.get(key.as_ref()) {
                conf.set_from_raw(key, &raw);
            }
        }

        recompute_derived(&mut conf, "");
        conf.store = Some(confg_store);
        let app_id_before_secrets = conf.app_id.clone();
        load_secrets_from_store(&mut conf, secret_store_name);
        rebuild_prepared_ci_endpoints(&mut conf);
        recompute_derived(&mut conf, &app_id_before_secrets);
        conf.validate_required_fields();
        conf
    }

    /// Partial JSON update — applies values for any [`PXConfigKey`] present
    /// (and non-null) in `cfg`. Unknown keys are ignored; type errors are
    /// logged and the affected field is left unchanged.
    #[doc(hidden)]
    pub fn update_from_json(&mut self, cfg: &serde_json::Value) {
        let config_obj = cfg.get("configValue").unwrap_or(cfg);

        let previous_app_id = self.app_id.clone();
        let mut config_found = false;
        for key in PXConfigKey::iter() {
            let Some(v) = config_obj.get(key.as_ref()).filter(|v| !v.is_null()) else {
                continue;
            };

            config_found = true;
            if let Err(e) = self.set_from_value(key, v) {
                px_error!("update_from_json: bad value for {}: {}", key.as_ref(), e);
            }

            #[cfg(feature = "kv_store")]
            if let Some(store) = self.store.as_mut() {
                let store_value = json_value_to_raw_store(v);
                let _ = store.insert(key.as_ref(), store_value);
            }
        }

        if !config_found {
            px_error!("update_from_json: config not found in body");
        }
        rebuild_prepared_ci_endpoints(self);
        recompute_derived(self, &previous_app_id);
        self.validate_required_fields();
    }

    /// Look up a field by its [`PXConfigKey`].
    pub fn get(&self, key: PXConfigKey) -> PXConfigValue<'_> {
        self.get_value(key)
    }

    /// Iterate `(key, value)` pairs over every configurable field.
    pub fn fields(&self) -> impl ExactSizeIterator<Item = (PXConfigKey, PXConfigValue<'_>)> {
        PXConfigKey::iter().map(|k| (k, self.get_value(k)))
    }

    /// Look up a field by its serialized name (e.g. `"px_app_id"`).
    pub fn get_field(&self, name: impl AsRef<str>) -> Option<PXConfigValue<'_>> {
        let name = name.as_ref();
        self.fields()
            .find_map(|(k, v)| (k.as_ref() == name).then_some(v))
    }

    /// Build a JSON object containing only the fields whose [`PXConfigKey`]
    /// is marked with `#[strum(props(required = "true"))]`. Sensitive values
    /// are redacted the same way as in the full `Serialize` impl.
    pub(crate) fn build_static_json(&self) -> serde_json::Value {
        let static_fields: Vec<(PXConfigKey, PXConfigValue<'_>)> =
            self.fields().filter(|(k, _)| k.is_static()).collect();
        let mut map = serde_json::Map::with_capacity(static_fields.len());
        for (key, value) in static_fields {
            let json_value = if key.is_sensitive() {
                serde_json::to_value(Redacted(&value)).unwrap_or_default()
            } else {
                serde_json::to_value(&value).unwrap_or_default()
            };
            map.insert(key.as_ref().to_owned(), json_value);
        }
        serde_json::Value::Object(map)
    }

    /// Serialize the active enforcer configuration for the telemetry payload.
    /// Excludes fields marked `static = "true"` (immutable between restarts)
    /// and `local = "true"` (never sent off-box).
    pub(crate) fn build_config_json(&self) -> serde_json::Value {
        let entries: Vec<(PXConfigKey, PXConfigValue<'_>)> =
            self.fields().filter(|(k, _)| !k.is_local()).collect();
        let mut map = serde_json::Map::with_capacity(entries.len());
        for (key, value) in entries {
            let json_value = if key.is_sensitive() {
                serde_json::to_value(Redacted(&value)).unwrap_or_default()
            } else {
                serde_json::to_value(&value).unwrap_or_default()
            };
            map.insert(key.as_ref().to_owned(), json_value);
        }
        serde_json::Value::Object(map)
    }

    fn missing_required_fields(&self) -> Vec<PXConfigKey> {
        self.fields()
            .filter_map(|(key, value)| {
                (key.is_required() && !config_value_is_set(&value)).then_some(key)
            })
            .collect()
    }

    fn validate_required_fields(&self) {
        for key in self.missing_required_fields() {
            px_error!(
                "Required PX configuration key {} is missing or empty",
                key.as_ref()
            );
        }
    }

    fn get_value(&self, key: PXConfigKey) -> PXConfigValue<'_> {
        match key {
            PXConfigKey::AppId => PXConfigValue::Str(&self.app_id),
            PXConfigKey::CookieSecret => PXConfigValue::Str(&self.cookie_secret),
            PXConfigKey::AuthToken => PXConfigValue::Str(&self.auth_token),
            PXConfigKey::Debug => PXConfigValue::Bool(self.debug),
            PXConfigKey::BlockingScore => PXConfigValue::U8(self.blocking_score),
            PXConfigKey::ModuleEnabled => PXConfigValue::Bool(self.module_enabled),
            PXConfigKey::ModuleMode => PXConfigValue::ModuleMode(self.module_mode),
            PXConfigKey::SensitiveHeaders => PXConfigValue::StrVec(&self.sensitive_headers),
            PXConfigKey::SensitiveRoutes => PXConfigValue::StrVec(&self.sensitive_routes),
            PXConfigKey::SensitiveRoutesRegex => {
                PXConfigValue::RegexVec(&self.sensitive_routes_regex)
            }
            PXConfigKey::FilterByRoute => PXConfigValue::StrVec(&self.filter_by_route),
            PXConfigKey::FilterByExtension => PXConfigValue::StrVec(&self.filter_by_extension),
            PXConfigKey::FilterByUserAgent => PXConfigValue::StrVec(&self.filter_by_user_agent),
            PXConfigKey::FilterByIp => PXConfigValue::StrVec(&self.filter_by_ip),
            PXConfigKey::FilterByHttpMethod => PXConfigValue::StrVec(&self.filter_by_http_method),
            PXConfigKey::CustomCookieHeader => PXConfigValue::Str(&self.custom_cookie_header),
            PXConfigKey::EnforcedRoutes => PXConfigValue::StrVec(&self.enforced_routes),
            PXConfigKey::MonitoredRoutes => PXConfigValue::StrVec(&self.monitored_routes),
            PXConfigKey::BypassMonitorHeader => PXConfigValue::Str(&self.bypass_monitor_header),
            PXConfigKey::FirstPartyEnabled => PXConfigValue::Bool(self.first_party_enabled),
            PXConfigKey::CustomLogo => PXConfigValue::Str(&self.custom_logo),
            PXConfigKey::JsRef => PXConfigValue::Str(&self.js_ref),
            PXConfigKey::CssRef => PXConfigValue::Str(&self.css_ref),
            PXConfigKey::HumanSapiHost => PXConfigValue::Str(&self.human_sapi_host),
            PXConfigKey::HumanSapiBackend => PXConfigValue::Str(&self.human_sapi_backend),
            PXConfigKey::HumanCollectorHost => PXConfigValue::Str(&self.human_collector_host),
            PXConfigKey::HumanCollectorBackend => PXConfigValue::Str(&self.human_collector_backend),
            PXConfigKey::HumanClientHost => PXConfigValue::Str(&self.human_client_host),
            PXConfigKey::HumanClientBackend => PXConfigValue::Str(&self.human_client_backend),
            PXConfigKey::HumanCaptchaHost => PXConfigValue::Str(&self.human_captcha_host),
            PXConfigKey::HumanCaptchaBackend => PXConfigValue::Str(&self.human_captcha_backend),
            PXConfigKey::IpHeaders => PXConfigValue::StrVec(&self.ip_headers),
            PXConfigKey::LogEndpoint => PXConfigValue::Str(&self.log_endpoint),
            PXConfigKey::DataEnrichmentHeaderName => {
                PXConfigValue::Str(&self.data_enrichment_header_name)
            }
            PXConfigKey::ExtractedCookies => PXConfigValue::StrVec(&self.extracted_cookies),
            PXConfigKey::CorsSupportEnabled => PXConfigValue::Bool(self.cors_support_enabled),
            PXConfigKey::CorsPreflightRequestFilterEnabled => {
                PXConfigValue::Bool(self.cors_preflight_request_filter_enabled)
            }
            PXConfigKey::GraphqlEnabled => PXConfigValue::Bool(self.graphql_enabled),
            PXConfigKey::GraphqlRoutes => PXConfigValue::RegexVec(&self.graphql_routes),
            PXConfigKey::SensitiveGraphqlOperationNames => {
                PXConfigValue::StrVec(&self.sensitive_graphql_operation_names)
            }
            PXConfigKey::SensitiveGraphqlOperationTypes => {
                PXConfigValue::StrVec(&self.sensitive_graphql_operation_types)
            }
            PXConfigKey::GraphqlBodyMaxLength => PXConfigValue::USize(self.graphql_body_max_length),
            PXConfigKey::GraphqlKeywords => PXConfigValue::RegexVec(&self.graphql_keywords),
            PXConfigKey::S2sTimeout => PXConfigValue::U32(self.s2s_timeout),
            PXConfigKey::TokenVersion => PXConfigValue::TokenVersion(self.token_version),
            PXConfigKey::CustomFirstPartyCaptchaEndpoint => {
                PXConfigValue::Str(&self.custom_first_party_captcha_endpoint)
            }
            PXConfigKey::CustomFirstPartySensorEndpoint => {
                PXConfigValue::Str(&self.custom_first_party_sensor_endpoint)
            }
            PXConfigKey::CustomFirstPartyXhrEndpoint => {
                PXConfigValue::Str(&self.custom_first_party_xhr_endpoint)
            }
            PXConfigKey::UserAgentMaxLength => PXConfigValue::USize(self.user_agent_max_length),
            PXConfigKey::RiskCookieMaxLength => PXConfigValue::USize(self.risk_cookie_max_length),
            PXConfigKey::RiskCookieMinIterations => {
                PXConfigValue::USize(self.risk_cookie_min_iterations)
            }
            PXConfigKey::RiskCookieMaxIterations => {
                PXConfigValue::USize(self.risk_cookie_max_iterations)
            }
            PXConfigKey::AgenticTrustEnabled => PXConfigValue::Bool(self.agentic_trust_enabled),
            PXConfigKey::AgenticTrustMcpEndpointPath => {
                PXConfigValue::Str(&self.agentic_trust_mcp_endpoint_path)
            }
            PXConfigKey::SecuredPxhdEnabled => PXConfigValue::Bool(self.secured_pxhd_enabled),
            PXConfigKey::PxhdDomain => PXConfigValue::Str(&self.pxhd_domain),
            PXConfigKey::JwtCookieName => PXConfigValue::Str(&self.jwt_cookie_name),
            PXConfigKey::JwtCookieUserIdFieldName => {
                PXConfigValue::Str(&self.jwt_cookie_user_id_field_name)
            }
            PXConfigKey::JwtCookieAdditionalFieldNames => {
                PXConfigValue::StrVec(&self.jwt_cookie_additional_field_names)
            }
            PXConfigKey::JwtHeaderName => PXConfigValue::Str(&self.jwt_header_name),
            PXConfigKey::JwtHeaderUserIdFieldName => {
                PXConfigValue::Str(&self.jwt_header_user_id_field_name)
            }
            PXConfigKey::JwtHeaderAdditionalFieldNames => {
                PXConfigValue::StrVec(&self.jwt_header_additional_field_names)
            }
            PXConfigKey::LoggerAuthToken => PXConfigValue::Str(&self.logger_auth_token),
            PXConfigKey::LoginCredentialsExtractionEnabled => {
                PXConfigValue::Bool(self.login_credentials_extraction_enabled)
            }
            PXConfigKey::LoginCredentialsExtraction => {
                PXConfigValue::CiEndpoints(&self.login_credentials_extraction)
            }
            PXConfigKey::CredentialsIntelligenceVersion => {
                PXConfigValue::Str(&self.credentials_intelligence_version)
            }
            PXConfigKey::CompromisedCredentialsHeader => {
                PXConfigValue::Str(&self.compromised_credentials_header)
            }
            PXConfigKey::SendRawUsernameOnAdditionalS2sActivity => {
                PXConfigValue::Bool(self.send_raw_username_on_additional_s2s_activity)
            }
            PXConfigKey::AdditionalS2sActivityEnabled => {
                PXConfigValue::Bool(self.additional_s2s_activity_enabled)
            }
            PXConfigKey::AdditionalS2sActivityHeaderEnabled => {
                PXConfigValue::Bool(self.additional_s2s_activity_header_enabled)
            }
            PXConfigKey::LoginSuccessfulReportingMethod => {
                PXConfigValue::Str(&self.login_successful_reporting_method)
            }
            PXConfigKey::LoginSuccessfulBodyRegex => {
                PXConfigValue::Str(&self.login_successful_body_regex)
            }
            PXConfigKey::LoginSuccessfulHeaderName => {
                PXConfigValue::Str(&self.login_successful_header_name)
            }
            PXConfigKey::LoginSuccessfulHeaderValue => {
                PXConfigValue::Str(&self.login_successful_header_value)
            }
            PXConfigKey::LoginSuccessfulStatus => {
                PXConfigValue::U16Vec(&self.login_successful_status)
            }
        }
    }

    fn set_from<'de, M: MapAccess<'de>>(
        &mut self,
        key: PXConfigKey,
        map: &mut M,
    ) -> Result<(), M::Error> {
        match key {
            PXConfigKey::AppId => self.app_id = map.next_value()?,
            PXConfigKey::CookieSecret => self.cookie_secret = map.next_value()?,
            PXConfigKey::AuthToken => self.auth_token = map.next_value()?,
            PXConfigKey::Debug => self.debug = map.next_value()?,
            PXConfigKey::BlockingScore => self.blocking_score = map.next_value()?,
            PXConfigKey::ModuleEnabled => self.module_enabled = map.next_value()?,
            PXConfigKey::ModuleMode => self.module_mode = map.next_value()?,
            PXConfigKey::SensitiveHeaders => self.sensitive_headers = map.next_value()?,
            PXConfigKey::SensitiveRoutes => self.sensitive_routes = map.next_value()?,
            PXConfigKey::SensitiveRoutesRegex => {
                let pats: Vec<String> = map.next_value()?;
                self.sensitive_routes_regex = compile_regex_vec(pats, key.as_ref());
            }
            PXConfigKey::FilterByRoute => self.filter_by_route = map.next_value()?,
            PXConfigKey::FilterByExtension => self.filter_by_extension = map.next_value()?,
            PXConfigKey::FilterByUserAgent => self.filter_by_user_agent = map.next_value()?,
            PXConfigKey::FilterByIp => self.filter_by_ip = map.next_value()?,
            PXConfigKey::FilterByHttpMethod => self.filter_by_http_method = map.next_value()?,
            PXConfigKey::CustomCookieHeader => self.custom_cookie_header = map.next_value()?,
            PXConfigKey::EnforcedRoutes => self.enforced_routes = map.next_value()?,
            PXConfigKey::MonitoredRoutes => self.monitored_routes = map.next_value()?,
            PXConfigKey::BypassMonitorHeader => self.bypass_monitor_header = map.next_value()?,
            PXConfigKey::FirstPartyEnabled => self.first_party_enabled = map.next_value()?,
            PXConfigKey::CustomLogo => self.custom_logo = map.next_value()?,
            PXConfigKey::JsRef => self.js_ref = map.next_value()?,
            PXConfigKey::CssRef => self.css_ref = map.next_value()?,
            PXConfigKey::HumanSapiHost => self.human_sapi_host = map.next_value()?,
            PXConfigKey::HumanSapiBackend => self.human_sapi_backend = map.next_value()?,
            PXConfigKey::HumanCollectorHost => self.human_collector_host = map.next_value()?,
            PXConfigKey::HumanCollectorBackend => {
                self.human_collector_backend = map.next_value()?
            }
            PXConfigKey::HumanClientHost => self.human_client_host = map.next_value()?,
            PXConfigKey::HumanClientBackend => self.human_client_backend = map.next_value()?,
            PXConfigKey::HumanCaptchaHost => self.human_captcha_host = map.next_value()?,
            PXConfigKey::HumanCaptchaBackend => self.human_captcha_backend = map.next_value()?,
            PXConfigKey::IpHeaders => self.ip_headers = map.next_value()?,
            PXConfigKey::LogEndpoint => self.log_endpoint = map.next_value()?,
            PXConfigKey::DataEnrichmentHeaderName => {
                self.data_enrichment_header_name = map.next_value()?
            }
            PXConfigKey::ExtractedCookies => self.extracted_cookies = map.next_value()?,
            PXConfigKey::CorsSupportEnabled => self.cors_support_enabled = map.next_value()?,
            PXConfigKey::CorsPreflightRequestFilterEnabled => {
                self.cors_preflight_request_filter_enabled = map.next_value()?
            }
            PXConfigKey::GraphqlEnabled => self.graphql_enabled = map.next_value()?,
            PXConfigKey::GraphqlRoutes => {
                let pats: Vec<String> = map.next_value()?;
                self.graphql_routes = compile_regex_vec(pats, key.as_ref());
            }
            PXConfigKey::SensitiveGraphqlOperationNames => {
                self.sensitive_graphql_operation_names = map.next_value()?
            }
            PXConfigKey::SensitiveGraphqlOperationTypes => {
                self.sensitive_graphql_operation_types = map.next_value()?
            }
            PXConfigKey::GraphqlBodyMaxLength => self.graphql_body_max_length = map.next_value()?,
            PXConfigKey::GraphqlKeywords => {
                let pats: Vec<String> = map.next_value()?;
                self.graphql_keywords = compile_regex_vec(pats, key.as_ref());
            }
            PXConfigKey::S2sTimeout => self.s2s_timeout = map.next_value()?,
            PXConfigKey::TokenVersion => self.token_version = map.next_value()?,
            PXConfigKey::CustomFirstPartyCaptchaEndpoint => {
                self.custom_first_party_captcha_endpoint = map.next_value()?
            }
            PXConfigKey::CustomFirstPartySensorEndpoint => {
                self.custom_first_party_sensor_endpoint = map.next_value()?
            }
            PXConfigKey::CustomFirstPartyXhrEndpoint => {
                self.custom_first_party_xhr_endpoint = map.next_value()?
            }
            PXConfigKey::UserAgentMaxLength => self.user_agent_max_length = map.next_value()?,
            PXConfigKey::RiskCookieMaxLength => self.risk_cookie_max_length = map.next_value()?,
            PXConfigKey::RiskCookieMinIterations => {
                self.risk_cookie_min_iterations = map.next_value()?
            }
            PXConfigKey::RiskCookieMaxIterations => {
                self.risk_cookie_max_iterations = map.next_value()?
            }
            PXConfigKey::AgenticTrustEnabled => self.agentic_trust_enabled = map.next_value()?,
            PXConfigKey::AgenticTrustMcpEndpointPath => {
                self.agentic_trust_mcp_endpoint_path = map.next_value()?
            }
            PXConfigKey::SecuredPxhdEnabled => self.secured_pxhd_enabled = map.next_value()?,
            PXConfigKey::PxhdDomain => self.pxhd_domain = map.next_value()?,
            PXConfigKey::JwtCookieName => self.jwt_cookie_name = map.next_value()?,
            PXConfigKey::JwtCookieUserIdFieldName => {
                self.jwt_cookie_user_id_field_name = map.next_value()?
            }
            PXConfigKey::JwtCookieAdditionalFieldNames => {
                self.jwt_cookie_additional_field_names = map.next_value()?
            }
            PXConfigKey::JwtHeaderName => self.jwt_header_name = map.next_value()?,
            PXConfigKey::JwtHeaderUserIdFieldName => {
                self.jwt_header_user_id_field_name = map.next_value()?
            }
            PXConfigKey::JwtHeaderAdditionalFieldNames => {
                self.jwt_header_additional_field_names = map.next_value()?
            }
            PXConfigKey::LoggerAuthToken => self.logger_auth_token = map.next_value()?,
            PXConfigKey::LoginCredentialsExtractionEnabled => {
                self.login_credentials_extraction_enabled = map.next_value()?
            }
            PXConfigKey::LoginCredentialsExtraction => {
                let v: serde_json::Value = map.next_value()?;
                self.login_credentials_extraction =
                    parse_ci_endpoints_from_value(&v).map_err(serde::de::Error::custom)?;
                rebuild_prepared_ci_endpoints(self);
            }
            PXConfigKey::CredentialsIntelligenceVersion => {
                self.credentials_intelligence_version = map.next_value()?
            }
            PXConfigKey::CompromisedCredentialsHeader => {
                self.compromised_credentials_header = map.next_value()?
            }
            PXConfigKey::SendRawUsernameOnAdditionalS2sActivity => {
                self.send_raw_username_on_additional_s2s_activity = map.next_value()?
            }
            PXConfigKey::AdditionalS2sActivityEnabled => {
                self.additional_s2s_activity_enabled = map.next_value()?
            }
            PXConfigKey::AdditionalS2sActivityHeaderEnabled => {
                self.additional_s2s_activity_header_enabled = map.next_value()?
            }
            PXConfigKey::LoginSuccessfulReportingMethod => {
                self.login_successful_reporting_method = map.next_value()?
            }
            PXConfigKey::LoginSuccessfulBodyRegex => {
                self.login_successful_body_regex = map.next_value()?
            }
            PXConfigKey::LoginSuccessfulHeaderName => {
                self.login_successful_header_name = map.next_value()?
            }
            PXConfigKey::LoginSuccessfulHeaderValue => {
                self.login_successful_header_value = map.next_value()?
            }
            PXConfigKey::LoginSuccessfulStatus => {
                self.login_successful_status = map.next_value()?
            }
        }
        Ok(())
    }

    pub(crate) fn set_from_value(
        &mut self,
        key: PXConfigKey,
        v: &serde_json::Value,
    ) -> Result<(), serde_json::Error> {
        match key {
            PXConfigKey::AppId => self.app_id = serde_json::from_value(v.clone())?,
            PXConfigKey::CookieSecret => self.cookie_secret = serde_json::from_value(v.clone())?,
            PXConfigKey::AuthToken => self.auth_token = serde_json::from_value(v.clone())?,
            PXConfigKey::Debug => self.debug = serde_json::from_value(v.clone())?,
            PXConfigKey::BlockingScore => self.blocking_score = serde_json::from_value(v.clone())?,
            PXConfigKey::ModuleEnabled => self.module_enabled = serde_json::from_value(v.clone())?,
            PXConfigKey::ModuleMode => self.module_mode = serde_json::from_value(v.clone())?,
            PXConfigKey::SensitiveHeaders => {
                self.sensitive_headers = serde_json::from_value(v.clone())?
            }
            PXConfigKey::SensitiveRoutes => {
                self.sensitive_routes = serde_json::from_value(v.clone())?
            }
            PXConfigKey::SensitiveRoutesRegex => {
                let pats: Vec<String> = serde_json::from_value(v.clone())?;
                self.sensitive_routes_regex = compile_regex_vec(pats, key.as_ref());
            }
            PXConfigKey::FilterByRoute => self.filter_by_route = serde_json::from_value(v.clone())?,
            PXConfigKey::FilterByExtension => {
                self.filter_by_extension = serde_json::from_value(v.clone())?
            }
            PXConfigKey::FilterByUserAgent => {
                self.filter_by_user_agent = serde_json::from_value(v.clone())?
            }
            PXConfigKey::FilterByIp => self.filter_by_ip = serde_json::from_value(v.clone())?,
            PXConfigKey::FilterByHttpMethod => {
                self.filter_by_http_method = serde_json::from_value(v.clone())?
            }
            PXConfigKey::CustomCookieHeader => {
                self.custom_cookie_header = serde_json::from_value(v.clone())?
            }
            PXConfigKey::EnforcedRoutes => {
                self.enforced_routes = serde_json::from_value(v.clone())?
            }
            PXConfigKey::MonitoredRoutes => {
                self.monitored_routes = serde_json::from_value(v.clone())?
            }
            PXConfigKey::BypassMonitorHeader => {
                self.bypass_monitor_header = serde_json::from_value(v.clone())?
            }
            PXConfigKey::FirstPartyEnabled => {
                self.first_party_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::CustomLogo => self.custom_logo = serde_json::from_value(v.clone())?,
            PXConfigKey::JsRef => self.js_ref = serde_json::from_value(v.clone())?,
            PXConfigKey::CssRef => self.css_ref = serde_json::from_value(v.clone())?,
            PXConfigKey::HumanSapiHost => self.human_sapi_host = serde_json::from_value(v.clone())?,
            PXConfigKey::HumanSapiBackend => {
                self.human_sapi_backend = serde_json::from_value(v.clone())?
            }
            PXConfigKey::HumanCollectorHost => {
                self.human_collector_host = serde_json::from_value(v.clone())?
            }
            PXConfigKey::HumanCollectorBackend => {
                self.human_collector_backend = serde_json::from_value(v.clone())?
            }
            PXConfigKey::HumanClientHost => {
                self.human_client_host = serde_json::from_value(v.clone())?
            }
            PXConfigKey::HumanClientBackend => {
                self.human_client_backend = serde_json::from_value(v.clone())?
            }
            PXConfigKey::HumanCaptchaHost => {
                self.human_captcha_host = serde_json::from_value(v.clone())?
            }
            PXConfigKey::HumanCaptchaBackend => {
                self.human_captcha_backend = serde_json::from_value(v.clone())?
            }
            PXConfigKey::IpHeaders => self.ip_headers = serde_json::from_value(v.clone())?,
            PXConfigKey::LogEndpoint => self.log_endpoint = serde_json::from_value(v.clone())?,
            PXConfigKey::DataEnrichmentHeaderName => {
                self.data_enrichment_header_name = serde_json::from_value(v.clone())?
            }
            PXConfigKey::ExtractedCookies => {
                self.extracted_cookies = serde_json::from_value(v.clone())?
            }
            PXConfigKey::CorsSupportEnabled => {
                self.cors_support_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::CorsPreflightRequestFilterEnabled => {
                self.cors_preflight_request_filter_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::GraphqlEnabled => {
                self.graphql_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::GraphqlRoutes => {
                let pats: Vec<String> = serde_json::from_value(v.clone())?;
                self.graphql_routes = compile_regex_vec(pats, key.as_ref());
            }
            PXConfigKey::SensitiveGraphqlOperationNames => {
                self.sensitive_graphql_operation_names = serde_json::from_value(v.clone())?
            }
            PXConfigKey::SensitiveGraphqlOperationTypes => {
                self.sensitive_graphql_operation_types = serde_json::from_value(v.clone())?
            }
            PXConfigKey::GraphqlBodyMaxLength => {
                self.graphql_body_max_length = serde_json::from_value(v.clone())?
            }
            PXConfigKey::GraphqlKeywords => {
                let pats: Vec<String> = serde_json::from_value(v.clone())?;
                self.graphql_keywords = compile_regex_vec(pats, key.as_ref());
            }
            PXConfigKey::S2sTimeout => self.s2s_timeout = serde_json::from_value(v.clone())?,
            PXConfigKey::TokenVersion => self.token_version = serde_json::from_value(v.clone())?,
            PXConfigKey::CustomFirstPartyCaptchaEndpoint => {
                self.custom_first_party_captcha_endpoint = serde_json::from_value(v.clone())?
            }
            PXConfigKey::CustomFirstPartySensorEndpoint => {
                self.custom_first_party_sensor_endpoint = serde_json::from_value(v.clone())?
            }
            PXConfigKey::CustomFirstPartyXhrEndpoint => {
                self.custom_first_party_xhr_endpoint = serde_json::from_value(v.clone())?
            }
            PXConfigKey::UserAgentMaxLength => {
                self.user_agent_max_length = serde_json::from_value(v.clone())?
            }
            PXConfigKey::RiskCookieMaxLength => {
                self.risk_cookie_max_length = serde_json::from_value(v.clone())?
            }
            PXConfigKey::RiskCookieMinIterations => {
                self.risk_cookie_min_iterations = serde_json::from_value(v.clone())?
            }
            PXConfigKey::RiskCookieMaxIterations => {
                self.risk_cookie_max_iterations = serde_json::from_value(v.clone())?
            }
            PXConfigKey::AgenticTrustEnabled => {
                self.agentic_trust_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::AgenticTrustMcpEndpointPath => {
                self.agentic_trust_mcp_endpoint_path = serde_json::from_value(v.clone())?
            }
            PXConfigKey::SecuredPxhdEnabled => {
                self.secured_pxhd_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::PxhdDomain => self.pxhd_domain = serde_json::from_value(v.clone())?,
            PXConfigKey::JwtCookieName => self.jwt_cookie_name = serde_json::from_value(v.clone())?,
            PXConfigKey::JwtCookieUserIdFieldName => {
                self.jwt_cookie_user_id_field_name = serde_json::from_value(v.clone())?
            }
            PXConfigKey::JwtCookieAdditionalFieldNames => {
                self.jwt_cookie_additional_field_names = serde_json::from_value(v.clone())?
            }
            PXConfigKey::JwtHeaderName => self.jwt_header_name = serde_json::from_value(v.clone())?,
            PXConfigKey::JwtHeaderUserIdFieldName => {
                self.jwt_header_user_id_field_name = serde_json::from_value(v.clone())?
            }
            PXConfigKey::JwtHeaderAdditionalFieldNames => {
                self.jwt_header_additional_field_names = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoggerAuthToken => {
                self.logger_auth_token = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoginCredentialsExtractionEnabled => {
                self.login_credentials_extraction_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoginCredentialsExtraction => {
                self.login_credentials_extraction = parse_ci_endpoints_from_value(v)?;
                rebuild_prepared_ci_endpoints(self);
            }
            PXConfigKey::CredentialsIntelligenceVersion => {
                self.credentials_intelligence_version = serde_json::from_value(v.clone())?
            }
            PXConfigKey::CompromisedCredentialsHeader => {
                self.compromised_credentials_header = serde_json::from_value(v.clone())?
            }
            PXConfigKey::SendRawUsernameOnAdditionalS2sActivity => {
                self.send_raw_username_on_additional_s2s_activity =
                    serde_json::from_value(v.clone())?
            }
            PXConfigKey::AdditionalS2sActivityEnabled => {
                self.additional_s2s_activity_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::AdditionalS2sActivityHeaderEnabled => {
                self.additional_s2s_activity_header_enabled = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoginSuccessfulReportingMethod => {
                self.login_successful_reporting_method = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoginSuccessfulBodyRegex => {
                self.login_successful_body_regex = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoginSuccessfulHeaderName => {
                self.login_successful_header_name = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoginSuccessfulHeaderValue => {
                self.login_successful_header_value = serde_json::from_value(v.clone())?
            }
            PXConfigKey::LoginSuccessfulStatus => {
                self.login_successful_status = serde_json::from_value(v.clone())?
            }
        }
        Ok(())
    }

    /// Apply a single raw string value from the ConfigStore (or KVStore) to
    /// the matching field. Non-string types are parsed using the same
    /// fallbacks as the previous ad-hoc loader.
    pub(crate) fn set_from_raw(&mut self, key: PXConfigKey, raw: &str) {
        let raw = strip_json_quotes(raw);
        match key {
            PXConfigKey::AppId => self.app_id = raw.to_owned(),
            PXConfigKey::CookieSecret => self.cookie_secret = raw.to_owned(),
            PXConfigKey::AuthToken => self.auth_token = raw.to_owned(),
            PXConfigKey::Debug => self.debug = raw.parse().unwrap_or(self.debug),
            PXConfigKey::BlockingScore => {
                self.blocking_score = raw.parse().unwrap_or(self.blocking_score)
            }
            PXConfigKey::ModuleEnabled => {
                self.module_enabled = raw.parse().unwrap_or(self.module_enabled)
            }
            PXConfigKey::ModuleMode => self.module_mode = raw.parse().unwrap_or(self.module_mode),
            PXConfigKey::SensitiveHeaders => self.sensitive_headers = parse_vec(raw),
            PXConfigKey::SensitiveRoutes => self.sensitive_routes = parse_vec(raw),
            PXConfigKey::SensitiveRoutesRegex => {
                self.sensitive_routes_regex = parse_regex_vec(key.as_ref(), raw)
            }
            PXConfigKey::FilterByRoute => self.filter_by_route = parse_vec(raw),
            PXConfigKey::FilterByExtension => self.filter_by_extension = parse_vec(raw),
            PXConfigKey::FilterByUserAgent => self.filter_by_user_agent = parse_vec(raw),
            PXConfigKey::FilterByIp => self.filter_by_ip = parse_vec(raw),
            PXConfigKey::FilterByHttpMethod => self.filter_by_http_method = parse_vec(raw),
            PXConfigKey::CustomCookieHeader => self.custom_cookie_header = parse_string(raw),
            PXConfigKey::EnforcedRoutes => self.enforced_routes = parse_vec(raw),
            PXConfigKey::MonitoredRoutes => self.monitored_routes = parse_vec(raw),
            PXConfigKey::BypassMonitorHeader => self.bypass_monitor_header = parse_string(raw),
            PXConfigKey::FirstPartyEnabled => {
                self.first_party_enabled = raw.parse().unwrap_or(self.first_party_enabled)
            }
            PXConfigKey::CustomLogo => self.custom_logo = parse_string(raw),
            PXConfigKey::JsRef => self.js_ref = parse_string(raw),
            PXConfigKey::CssRef => self.css_ref = parse_string(raw),
            PXConfigKey::HumanSapiHost => self.human_sapi_host = parse_string(raw),
            PXConfigKey::HumanSapiBackend => self.human_sapi_backend = parse_string(raw),
            PXConfigKey::HumanCollectorHost => self.human_collector_host = parse_string(raw),
            PXConfigKey::HumanCollectorBackend => self.human_collector_backend = parse_string(raw),
            PXConfigKey::HumanClientHost => self.human_client_host = parse_string(raw),
            PXConfigKey::HumanClientBackend => self.human_client_backend = parse_string(raw),
            PXConfigKey::HumanCaptchaHost => self.human_captcha_host = parse_string(raw),
            PXConfigKey::HumanCaptchaBackend => self.human_captcha_backend = parse_string(raw),
            PXConfigKey::IpHeaders => self.ip_headers = parse_vec(raw),
            PXConfigKey::LogEndpoint => self.log_endpoint = raw.to_owned(),
            PXConfigKey::DataEnrichmentHeaderName => {
                self.data_enrichment_header_name = parse_string(raw)
            }
            PXConfigKey::ExtractedCookies => self.extracted_cookies = parse_vec(raw),
            PXConfigKey::CorsSupportEnabled => {
                self.cors_support_enabled = raw.parse().unwrap_or(self.cors_support_enabled)
            }
            PXConfigKey::CorsPreflightRequestFilterEnabled => {
                self.cors_preflight_request_filter_enabled = raw
                    .parse()
                    .unwrap_or(self.cors_preflight_request_filter_enabled)
            }
            PXConfigKey::GraphqlEnabled => {
                self.graphql_enabled = raw.parse().unwrap_or(self.graphql_enabled)
            }
            PXConfigKey::GraphqlRoutes => self.graphql_routes = parse_regex_vec(key.as_ref(), raw),
            PXConfigKey::SensitiveGraphqlOperationNames => {
                self.sensitive_graphql_operation_names = parse_vec(raw)
            }
            PXConfigKey::SensitiveGraphqlOperationTypes => {
                self.sensitive_graphql_operation_types = parse_vec(raw)
            }
            PXConfigKey::GraphqlBodyMaxLength => {
                self.graphql_body_max_length = raw.parse().unwrap_or(self.graphql_body_max_length)
            }
            PXConfigKey::GraphqlKeywords => {
                self.graphql_keywords = parse_regex_vec(key.as_ref(), raw)
            }
            PXConfigKey::S2sTimeout => self.s2s_timeout = raw.parse().unwrap_or(self.s2s_timeout),
            PXConfigKey::TokenVersion => {
                self.token_version = raw.parse().unwrap_or(self.token_version)
            }
            PXConfigKey::CustomFirstPartyCaptchaEndpoint => {
                self.custom_first_party_captcha_endpoint = parse_string(raw)
            }
            PXConfigKey::CustomFirstPartySensorEndpoint => {
                self.custom_first_party_sensor_endpoint = parse_string(raw)
            }
            PXConfigKey::CustomFirstPartyXhrEndpoint => {
                self.custom_first_party_xhr_endpoint = parse_string(raw)
            }
            PXConfigKey::UserAgentMaxLength => {
                self.user_agent_max_length = raw.parse().unwrap_or(self.user_agent_max_length)
            }
            PXConfigKey::RiskCookieMaxLength => {
                self.risk_cookie_max_length = raw.parse().unwrap_or(self.risk_cookie_max_length)
            }
            PXConfigKey::RiskCookieMinIterations => {
                self.risk_cookie_min_iterations =
                    raw.parse().unwrap_or(self.risk_cookie_min_iterations)
            }
            PXConfigKey::RiskCookieMaxIterations => {
                self.risk_cookie_max_iterations =
                    raw.parse().unwrap_or(self.risk_cookie_max_iterations)
            }
            PXConfigKey::AgenticTrustEnabled => {
                self.agentic_trust_enabled = raw.parse().unwrap_or(self.agentic_trust_enabled)
            }
            PXConfigKey::AgenticTrustMcpEndpointPath => {
                self.agentic_trust_mcp_endpoint_path = parse_string(raw)
            }
            PXConfigKey::SecuredPxhdEnabled => {
                self.secured_pxhd_enabled = raw.parse().unwrap_or(self.secured_pxhd_enabled)
            }
            PXConfigKey::PxhdDomain => self.pxhd_domain = parse_string(raw),
            PXConfigKey::JwtCookieName => self.jwt_cookie_name = parse_string(raw),
            PXConfigKey::JwtCookieUserIdFieldName => {
                self.jwt_cookie_user_id_field_name = parse_string(raw)
            }
            PXConfigKey::JwtCookieAdditionalFieldNames => {
                self.jwt_cookie_additional_field_names = parse_vec(raw)
            }
            PXConfigKey::JwtHeaderName => self.jwt_header_name = parse_string(raw),
            PXConfigKey::JwtHeaderUserIdFieldName => {
                self.jwt_header_user_id_field_name = parse_string(raw)
            }
            PXConfigKey::JwtHeaderAdditionalFieldNames => {
                self.jwt_header_additional_field_names = parse_vec(raw)
            }
            PXConfigKey::LoggerAuthToken => self.logger_auth_token = raw.to_owned(),
            PXConfigKey::LoginCredentialsExtractionEnabled => {
                self.login_credentials_extraction_enabled = raw
                    .parse()
                    .unwrap_or(self.login_credentials_extraction_enabled)
            }
            PXConfigKey::LoginCredentialsExtraction => {
                self.login_credentials_extraction = parse_ci_endpoints(raw);
                rebuild_prepared_ci_endpoints(self);
            }
            PXConfigKey::CredentialsIntelligenceVersion => {
                self.credentials_intelligence_version = parse_string(raw)
            }
            PXConfigKey::CompromisedCredentialsHeader => {
                self.compromised_credentials_header = parse_string(raw)
            }
            PXConfigKey::SendRawUsernameOnAdditionalS2sActivity => {
                self.send_raw_username_on_additional_s2s_activity = raw
                    .parse()
                    .unwrap_or(self.send_raw_username_on_additional_s2s_activity)
            }
            PXConfigKey::AdditionalS2sActivityEnabled => {
                self.additional_s2s_activity_enabled =
                    raw.parse().unwrap_or(self.additional_s2s_activity_enabled)
            }
            PXConfigKey::AdditionalS2sActivityHeaderEnabled => {
                self.additional_s2s_activity_header_enabled = raw
                    .parse()
                    .unwrap_or(self.additional_s2s_activity_header_enabled)
            }
            PXConfigKey::LoginSuccessfulReportingMethod => {
                self.login_successful_reporting_method = parse_string(raw)
            }
            PXConfigKey::LoginSuccessfulBodyRegex => {
                self.login_successful_body_regex = parse_string(raw)
            }
            PXConfigKey::LoginSuccessfulHeaderName => {
                self.login_successful_header_name = parse_string(raw)
            }
            PXConfigKey::LoginSuccessfulHeaderValue => {
                self.login_successful_header_value = parse_string(raw)
            }
            PXConfigKey::LoginSuccessfulStatus => {
                self.login_successful_status = parse_status_vec(raw)
            }
        }
    }

    /// Register runtime callback for custom credential extraction.
    pub fn set_ci_extract_credentials_fn(&mut self, f: PXExtractCredentialsFn) {
        self.ci_extract_credentials_fn = Some(f);
    }

    /// Register runtime callback for custom login-success reporting.
    pub fn set_ci_login_successful_fn(&mut self, f: PXLoginSuccessfulFn) {
        self.ci_login_successful_fn = Some(f);
    }
}