bao_stealth 0.4.4

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
// REQ-STL-004: Stealth runtime JS hook injection  @trace REQ-STL-004
use crate::canvas::CanvasNoise;
use crate::navigator::{NavigatorProfile, ScreenProfile};
use crate::profile::{
    BatteryConfig, ClientRectsConfig, ConnectionConfig, FontConfig, IframeConfig,
    MediaDevicesConfig, PermissionsConfig, PluginConfig, ScreenDisplayConfig, SpeechConfig,
    TimingConfig, WebGLContextConfig, WebRtcMode,
};
use crate::webgl_audio::{AudioProfile, WebGLProfile};

/// Segment table (M9 install_* 宏收敛, e165, REQ-BRW-049; repays the e152
/// audit §二 finding that the 15 hook-segment names were hand-repeated four
/// times — struct fields, per-segment getters, and `combined_js`'s capacity
/// + concatenation). The bare field list below is the single source for
/// those three mechanical mirrors; the constructor mapping (`field =>
/// builder(args)`) stays explicit in `from_profile` because the builder
/// argument shapes are per-segment data, not boilerplate.
///
/// Byte-parity contract: the generated getters and `combined_js` are the
/// statement-for-statement equivalents of the hand-written forms they
/// replaced — same getter bodies, same segment order with `\n` separators
/// between segments (no trailing newline after the last), same capacity
/// formula (sum of segment lens + 16 slack). Pinned by the face-lock suite
/// (JS-injection profile-consistency tests) and the e165 pre/post capture
/// diff (48/48 artifacts byte-identical).
macro_rules! stealth_hook_segments {
    ( $first:ident $(, $rest:ident )* $(,)? ) => {
        pub struct StealthHooks {
            $first: String,
            $( $rest: String, )*
        }

        impl StealthHooks {
            pub fn $first(&self) -> &str {
                &self.$first
            }

            $(
                pub fn $rest(&self) -> &str {
                    &self.$rest
                }
            )*

            pub fn combined_js(&self) -> String {
                // Byte-parity with the hand-written form: '\n' BETWEEN
                // segments only — the last segment gets NO trailing newline
                // (pinned by the e165 capture diff).
                let mut out =
                    String::with_capacity(16 + self.$first.len() $( + self.$rest.len() )*);
                out.push_str(&self.$first);
                $(
                    out.push('\n');
                    out.push_str(&self.$rest);
                )*
                out
            }
        }
    };
}

stealth_hook_segments! {
    audio_js,
    navigator_js,
    font_js,
    battery_js,
    webrtc_js,
    timing_js,
    clientrects_js,
    screen_display_js,
    plugin_js,
    speech_js,
    media_devices_js,
    permissions_js,
    webgl_context_js,
    connection_js,
    iframe_js,
}

impl StealthHooks {
    pub fn from_profile(
        // Canvas noise JS segment RETIRED (user ruling 2026-09-09, BRW-004 C13):
        // the four canvas read-out JS hooks (toDataURL / toBlob / 2d getImageData /
        // Offscreen 2d getImageData) stacked a SECOND noise layer on top of the
        // paint-thread single choke point (CanvasCommand::GetImageData, commit
        // 6bcf30af) — Window getImageData/toDataURL/toBlob got double noise
        // while the convertToBlob/transferToImageBitmap family got single
        // noise: a cross-path inconsistency detectors can flag. Noise now
        // flows exclusively through the paint layer. The parameter stays
        // because engine_props (frozen caller) and the profile plumbing still
        // feed the canvas seed downstream to the servo rendering layer via
        // canvas_seed()/canvas_amplitude().
        _canvas: &CanvasNoise,
        audio: &AudioProfile,
        navigator: &NavigatorProfile,
        screen: &ScreenProfile,
        webgl: &WebGLProfile,
        font: &FontConfig,
        battery: &BatteryConfig,
        webrtc_mode: WebRtcMode,
        timing: &TimingConfig,
        clientrects: &ClientRectsConfig,
        screen_display: &ScreenDisplayConfig,
        plugin: &PluginConfig,
        speech: &SpeechConfig,
        media_devices: &MediaDevicesConfig,
        permissions: &PermissionsConfig,
        webgl_context: &WebGLContextConfig,
        connection: &ConnectionConfig,
        iframe: &IframeConfig,
    ) -> Self {
        StealthHooks {
            audio_js: Self::build_audio_js(audio),
            navigator_js: Self::build_navigator_js(navigator, screen, webgl),
            font_js: Self::build_font_js(font),
            battery_js: Self::build_battery_js(battery),
            webrtc_js: Self::build_webrtc_js(webrtc_mode),
            timing_js: Self::build_timing_js(timing),
            clientrects_js: Self::build_clientrects_js(clientrects),
            screen_display_js: Self::build_screen_display_js(screen_display),
            plugin_js: Self::build_plugin_js(plugin, navigator),
            speech_js: Self::build_speech_js(speech),
            media_devices_js: Self::build_media_devices_js(media_devices),
            permissions_js: Self::build_permissions_js(permissions),
            webgl_context_js: Self::build_webgl_context_js(webgl_context),
            connection_js: Self::build_connection_js(connection),
            iframe_js: Self::build_iframe_js(iframe),
        }
    }

    // ── Canvas hooks ──────────────────────────────────────────────
    // RETIRED (user ruling 2026-09-09, BRW-004 C13): the four canvas read-out
    // JS hooks (toDataURL / toBlob / CanvasRenderingContext2D.getImageData /
    // OffscreenCanvasRenderingContext2D.getImageData) were removed. Canvas
    // noise is applied exclusively at the paint-thread single choke point
    // (vendor canvas_paint_thread.rs, CanvasCommand::GetImageData — commit
    // 6bcf30af), which covers every read-out path (window/worker getImageData,
    // toDataURL, toBlob, convertToBlob, transferToImageBitmap,
    // createImageBitmap, texImage2D-from-canvas, createPattern) with one
    // layer of the same-seed deterministic noise. The old JS layer stacked a
    // second layer on the Window getImageData/toDataURL/toBlob family only —
    // a cross-path inconsistency. Do NOT reintroduce JS-layer canvas noise.

    // ── Audio hooks ───────────────────────────────────────────────

    fn build_audio_js(audio: &AudioProfile) -> String {
        let seed = audio.seed();
        let amplitude = audio.noise_amplitude();

        format!(
            r#"(function() {{
  var seed = {seed}n;
  var amplitude = {amplitude};

  function detNoise(index) {{
    var state = seed;
    state ^= BigInt(index) * 0x517CC1B727220A95n;
    state = BigInt.asUintN(64, state * 0x2545F4914F6CDD1Dn);
    state ^= state >> 33n;
    return Number(BigInt.asUintN(64, state)) / 18446744073709551615 - 0.5;
  }}

  // Worker-realm guard (REQ-BRW-004 C13/C15): AudioBuffer is [Exposed=Window]
  // — a bare prototype reference throws ReferenceError in a worker realm and
  // kills the rest of the hooks blob. OfflineAudioContext below is already
  // typeof-guarded.
  if (typeof AudioBuffer !== 'undefined') {{
    var origGetChannelData = AudioBuffer.prototype.getChannelData;
    AudioBuffer.prototype.getChannelData = function(channel) {{
      var data = origGetChannelData.call(this, channel);
      if (seed > 0n && amplitude > 0) {{
        for (var i = 0; i < data.length; i++) {{
          data[i] += detNoise(i) * amplitude;
        }}
      }}
      return data;
    }};
  }}

  if (typeof OfflineAudioContext !== 'undefined') {{
    var origStartRendering = OfflineAudioContext.prototype.startRendering;
    OfflineAudioContext.prototype.startRendering = function() {{
      var self = this;
      return origStartRendering.call(this).then(function(buffer) {{
        if (seed > 0n && amplitude > 0) {{
          for (var ch = 0; ch < buffer.numberOfChannels; ch++) {{
            var data = buffer.getChannelData(ch);
            for (var i = 0; i < data.length; i++) {{
              data[i] += detNoise(ch * 1000000 + i) * amplitude;
            }}
          }}
        }}
        return buffer;
      }});
    }};
  }}
}})();"#,
            seed = seed,
            amplitude = amplitude,
        )
    }

    // ── Navigator/Screen/WebGL hooks ──────────────────────────────

    fn build_navigator_js(
        nav: &NavigatorProfile,
        screen: &ScreenProfile,
        webgl: &WebGLProfile,
    ) -> String {
        let languages_json =
            serde_json::to_string(&nav.languages).unwrap_or_else(|_| r#"["en-US","en"]"#.into());
        let extensions_json =
            serde_json::to_string(&webgl.extensions).unwrap_or_else(|_| "[]".into());

        format!(
            r#"(function() {{
  // BCE (error.rs:74 residue): every defineProperty below must tolerate a
  // refused redefine — on servo's Page Realm the WebIDL [LegacyUnforgeable]
  // navigator/screen members (and any property already installed
  // configurable:false by a prior install) throw
  // "TypeError: can't redefine non-configurable property". A mid-template
  // throw aborted the whole hooks blob AND left the exception pending on
  // the ScriptThread cx (detonating servo's error.rs:74 assert). A refused
  // define means the target state is already in effect — swallow it.
  var __bao_def = function(obj, name, desc) {{
    try {{ Object.defineProperty(obj, name, desc); }} catch (e) {{ /* refused redefine — target state already in effect */ }}
  }};
  // Chromium-parity placement (e148 oracle, Chrome 150): navigator/screen
  // members are accessors on the INTERFACE PROTOTYPE with enumerable and
  // configurable both true; the instances carry zero own names. Defining on
  // the instance instead put every covered member into
  // Object.getOwnPropertyNames(navigator) — an engine-distinguishing
  // signal. Plain-object realms (no DOM): the prototype IS Object.prototype
  // — defining there would pollute every object, so fall back to the
  // instance.
  var __bao_target = function(o) {{
    try {{
      var p = Object.getPrototypeOf(o);
      return (p && p !== Object.prototype) ? p : o;
    }} catch (e) {{ return o; }}
  }};
  var nav = (typeof navigator !== 'undefined') ? navigator : null;
  var scr = (typeof screen !== 'undefined') ? screen : null;
  var win = (typeof window !== 'undefined') ? window : (typeof globalThis !== 'undefined' ? globalThis : null);
  var __nav_t = nav ? __bao_target(nav) : null;
  var __scr_t = scr ? __bao_target(scr) : null;

  // e148-R1: the proto targeting stays (with Face A PERMANENT these defines
  // throw "can't redefine non-configurable property" and are swallowed by
  // __bao_def — the native getters survive, and the navigator INSTANCE
  // never gains own props; with configurable targets this define REPLACED
  // the native getters and SIGSEGV'd under PagePool churn — see
  // define_stealth_getter's bisect note).
  if (__nav_t) {{
  __bao_def(__nav_t, 'userAgent', {{ get: function() {{ return {ua:?}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'platform', {{ get: function() {{ return {platform:?}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'hardwareConcurrency', {{ get: function() {{ return {hwc}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'language', {{ get: function() {{ return {lang:?}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'languages', {{ get: function() {{ return {langs}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'vendor', {{ get: function() {{ return {vendor:?}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'deviceMemory', {{ get: function() {{ return {dm}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'maxTouchPoints', {{ get: function() {{ return {mtp}; }}, enumerable: true, configurable: true }});
  __bao_def(__nav_t, 'webdriver', {{ get: function() {{ return false; }}, enumerable: true, configurable: true }});
  }}

  if (__scr_t) {{
  __bao_def(__scr_t, 'width', {{ get: function() {{ return {sw}; }}, enumerable: true, configurable: true }});
  __bao_def(__scr_t, 'height', {{ get: function() {{ return {sh}; }}, enumerable: true, configurable: true }});
  __bao_def(__scr_t, 'availWidth', {{ get: function() {{ return {aw}; }}, enumerable: true, configurable: true }});
  __bao_def(__scr_t, 'availHeight', {{ get: function() {{ return {ah}; }}, enumerable: true, configurable: true }});
  __bao_def(__scr_t, 'colorDepth', {{ get: function() {{ return {cd}; }}, enumerable: true, configurable: true }});
  __bao_def(__scr_t, 'pixelDepth', {{ get: function() {{ return {pd}; }}, enumerable: true, configurable: true }});
  }}
  // devicePixelRatio: OWN accessor on window — Chrome parity (the global's
  // own descriptor), same attrs.
  if (win) __bao_def(win, 'devicePixelRatio', {{ get: function() {{ return {dpr}; }}, enumerable: true, configurable: true }});

  if (typeof WebGLRenderingContext === 'undefined') return;
  var origGetParameter = WebGLRenderingContext.prototype.getParameter;
  WebGLRenderingContext.prototype.getParameter = function(param) {{
    var dbgRenderer = 0x9246;
    var dbgVendor = 0x9245;
    if (param === dbgRenderer) return {renderer:?};
    if (param === dbgVendor) return {wgl_vendor:?};
    var maxTexSize = 0x0D33;
    var maxRbSize = 0x84E8;
    var maxViewport = 0x0D3A;
    if (param === maxTexSize) return {mts};
    if (param === maxRbSize) return {mrbs};
    if (param === maxViewport) return new Int32Array([{vp0}, {vp1}]);
    return origGetParameter.call(this, param);
  }};

  var origGetSupportedExtensions = WebGLRenderingContext.prototype.getSupportedExtensions;
  WebGLRenderingContext.prototype.getSupportedExtensions = function() {{
    return {exts};
  }};

  if (typeof WebGL2RenderingContext !== 'undefined') {{
    var origGetParameter2 = WebGL2RenderingContext.prototype.getParameter;
    WebGL2RenderingContext.prototype.getParameter = function(param) {{
      var dbgRenderer = 0x9246;
      var dbgVendor = 0x9245;
      if (param === dbgRenderer) return {renderer:?};
      if (param === dbgVendor) return {wgl_vendor:?};
      var maxTexSize = 0x0D33;
      var maxRbSize = 0x84E8;
      var maxViewport = 0x0D3A;
      if (param === maxTexSize) return {mts};
      if (param === maxRbSize) return {mrbs};
      if (param === maxViewport) return new Int32Array([{vp0}, {vp1}]);
      return origGetParameter2.call(this, param);
    }};

    var origGetSupportedExtensions2 = WebGL2RenderingContext.prototype.getSupportedExtensions;
    WebGL2RenderingContext.prototype.getSupportedExtensions = function() {{
      return {exts};
    }};
  }}
}})();"#,
            ua = nav.user_agent,
            platform = nav.platform,
            hwc = nav.hardware_concurrency,
            lang = nav.language,
            langs = languages_json,
            vendor = nav.vendor,
            dm = nav.device_memory,
            mtp = nav.max_touch_points,
            sw = screen.width,
            sh = screen.height,
            aw = screen.avail_width,
            ah = screen.avail_height,
            cd = screen.color_depth,
            pd = screen.pixel_depth,
            dpr = screen.device_pixel_ratio,
            renderer = webgl.renderer,
            wgl_vendor = webgl.vendor,
            mts = webgl.max_texture_size,
            mrbs = webgl.max_renderbuffer_size,
            vp0 = webgl.max_viewport_dims[0],
            vp1 = webgl.max_viewport_dims[1],
            exts = extensions_json,
        )
    }

    // ── Font fingerprint protection ──────────────────────────────

    fn build_font_js(font: &FontConfig) -> String {
        let seed = font.seed;
        let extra_count = font.extra_font_count;
        let hidden_fonts_json =
            serde_json::to_string(&font.hidden_fonts).unwrap_or_else(|_| "[]".into());

        format!(
            r#"(function() {{
  var SEED = {seed}n;
  var EXTRA_COUNT = {extra_count};
  var HIDDEN_FONTS = {hidden_fonts};

  // Deterministic xorshift64 PRNG
  function xorshift64(state) {{
    state = BigInt.asUintN(64, state);
    state ^= state << 13n;
    state = BigInt.asUintN(64, state);
    state ^= state >> 7n;
    state = BigInt.asUintN(64, state);
    state ^= state << 17n;
    return BigInt.asUintN(64, state);
  }}

  function detRand(index) {{
    var s = SEED ^ (BigInt(index) * 0x2545F4914F6CDD1Dn);
    s = xorshift64(s);
    return Number(s) / 18446744073709551615;
  }}

  if (typeof document !== 'undefined' && document.fonts) {{
    var origCheck = document.fonts.check.bind(document.fonts);
    document.fonts.check = function(font, text) {{
      for (var i = 0; i < HIDDEN_FONTS.length; i++) {{
        if (font.indexOf(HIDDEN_FONTS[i]) !== -1) return false;
      }}
      return origCheck(font, text);
    }};

    var origSize = Object.getOwnPropertyDescriptor(Document.prototype, 'fonts');
    if (origSize && origSize.get) {{
      var origGetter = origSize.get;
      Object.defineProperty(document, 'fonts', {{
        get: function() {{
          var fontsObj = origGetter.call(document);
          var origFontsSize = Object.getOwnPropertyDescriptor(FontData.prototype, 'size');
          if (origFontsSize && origFontsSize.get) {{
            var origSizeGetter = origFontsSize.get;
            Object.defineProperty(fontsObj, 'size', {{
              get: function() {{
                return origSizeGetter.call(fontsObj) + EXTRA_COUNT;
              }},
              configurable: true
            }});
          }}
          return fontsObj;
        }},
        configurable: true
      }});
    }}
  }}
}})();"#,
            seed = seed,
            extra_count = extra_count,
            hidden_fonts = hidden_fonts_json,
        )
    }

    // ── Battery API simulation ───────────────────────────────────

    fn build_battery_js(battery: &BatteryConfig) -> String {
        let charging = battery.charging;
        let level = battery.level;
        let charging_time = battery.charging_time;
        let discharging_time = if battery.discharging_time.is_infinite() {
            "Infinity".to_string()
        } else {
            format!("{}", battery.discharging_time)
        };

        format!(
            r#"(function() {{
  var fixedBattery = {{
    charging: {charging},
    chargingTime: {charging_time},
    dischargingTime: {discharging_time},
    level: {level},
    addEventListener: function() {{}},
    removeEventListener: function() {{}},
    dispatchEvent: function() {{ return true; }},
    onchargingchange: null,
    onchargingtimechange: null,
    ondischargingtimechange: null,
    onlevelchange: null
  }};

  if (typeof navigator !== 'undefined' && navigator.getBattery) {{
    navigator.getBattery = function() {{
      return Promise.resolve(fixedBattery);
    }};
  }}
}})();"#,
            charging = charging,
            charging_time = charging_time,
            discharging_time = discharging_time,
            level = level,
        )
    }

    // ── WebRTC leak protection ───────────────────────────────────

    fn build_webrtc_js(mode: WebRtcMode) -> String {
        match mode {
            WebRtcMode::None => r#"(function() {
  if (typeof RTCPeerConnection !== 'undefined') {
    window.RTCPeerConnection = function() {
      throw new DOMException('WebRTC is disabled', 'NotAllowedError');
    };
    Object.defineProperty(window, 'RTCPeerConnection', {
      value: function() {
        throw new DOMException('WebRTC is disabled', 'NotAllowedError');
      },
      configurable: false,
      writable: false
    });
  }
  if (typeof webkitRTCPeerConnection !== 'undefined') {
    window.webkitRTCPeerConnection = function() {
      throw new DOMException('WebRTC is disabled', 'NotAllowedError');
    };
  }
})();"#
                .to_string(),

            WebRtcMode::Default => r#"(function() {
  if (typeof RTCPeerConnection !== 'undefined') {
    var origAddEventListener = RTCPeerConnection.prototype.addEventListener;
    RTCPeerConnection.prototype.addEventListener = function(type, listener, options) {
      if (type === 'icecandidate') {
        var filteredListener = function(event) {
          if (event.candidate) {
            var c = event.candidate.candidate || '';
            // Allow mDNS candidates (end with .local) and relay candidates
            if (c.indexOf('.local') !== -1 || c.indexOf('relay') !== -1) {
              listener.call(this, event);
            }
            // Block srflx and host candidates to prevent IP leaks
          } else {
            listener.call(this, event);
          }
        };
        return origAddEventListener.call(this, type, filteredListener, options);
      }
      return origAddEventListener.call(this, type, listener, options);
    };
  }
})();"#
                .to_string(),

            WebRtcMode::Strict => r#"(function() {
  if (typeof RTCPeerConnection !== 'undefined') {
    var origAddEventListener = RTCPeerConnection.prototype.addEventListener;
    RTCPeerConnection.prototype.addEventListener = function(type, listener, options) {
      if (type === 'icecandidate') {
        var filteredListener = function(event) {
          if (event.candidate) {
            var c = event.candidate.candidate || '';
            // Strict: only allow relay candidates
            if (c.indexOf('relay') !== -1) {
              listener.call(this, event);
            }
          } else {
            listener.call(this, event);
          }
        };
        return origAddEventListener.call(this, type, filteredListener, options);
      }
      return origAddEventListener.call(this, type, listener, options);
    };

    // Also override createOffer/createAnswer to strip local IPs from SDP
    var origCreateOffer = RTCPeerConnection.prototype.createOffer;
    RTCPeerConnection.prototype.createOffer = function(options) {
      return origCreateOffer.call(this, options).then(function(desc) {
        desc.sdp = desc.sdp.replace(/a=candidate:.*typ\s+(srflx|host).*\r?\n/g, '');
        return desc;
      });
    };

    var origCreateAnswer = RTCPeerConnection.prototype.createAnswer;
    RTCPeerConnection.prototype.createAnswer = function(options) {
      return origCreateAnswer.call(this, options).then(function(desc) {
        desc.sdp = desc.sdp.replace(/a=candidate:.*typ\s+(srflx|host).*\r?\n/g, '');
        return desc;
      });
    };
  }
})();"#
                .to_string(),
        }
    }

    // ── Performance timing precision ─────────────────────────────

    fn build_timing_js(timing: &TimingConfig) -> String {
        let precision_us = timing.precision_us;
        let precision_ms = precision_us as f64 / 1000.0;

        format!(
            r#"(function() {{
  var PRECISION_MS = {precision_ms};

  function roundToPrecision(t) {{
    return Math.round(t / PRECISION_MS) * PRECISION_MS;
  }}

  if (typeof performance !== 'undefined') {{
    var origNow = performance.now.bind(performance);
    performance.now = function() {{
      return roundToPrecision(origNow());
    }};
  }}

  var origDateNow = Date.now;
  Date.now = function() {{
    return Math.round(roundToPrecision(origDateNow()));
  }};

  if (typeof Event !== 'undefined') {{
    var origTimeStamp = Object.getOwnPropertyDescriptor(Event.prototype, 'timeStamp');
    if (origTimeStamp && origTimeStamp.get) {{
      var origGetter = origTimeStamp.get;
      Object.defineProperty(Event.prototype, 'timeStamp', {{
        get: function() {{
          return roundToPrecision(origGetter.call(this));
        }},
        configurable: true
      }});
    }}
  }}
}})();"#,
            precision_ms = precision_ms,
        )
    }

    // ── ClientRects noise ────────────────────────────────────────

    fn build_clientrects_js(config: &ClientRectsConfig) -> String {
        let delta = config.noise_delta;
        let seed = config.seed;

        format!(
            r#"(function() {{
  var DELTA = {delta};
  var SEED = {seed}n;

  function xorshift64(state) {{
    state = BigInt.asUintN(64, state);
    state ^= state << 13n;
    state = BigInt.asUintN(64, state);
    state ^= state >> 7n;
    state = BigInt.asUintN(64, state);
    state ^= state << 17n;
    return BigInt.asUintN(64, state);
  }}

  function detNoise(element, field) {{
    var hash = SEED;
    if (typeof element === 'object' && element !== null) {{
      var id = element.id || element.tagName || '';
      for (var i = 0; i < id.length; i++) {{
        hash ^= BigInt(id.charCodeAt(i)) * BigInt(i + 1 + 0x517CC1B727220A95n);
        hash = xorshift64(hash);
      }}
    }}
    hash ^= BigInt(field) * 0x6C62272E07BB0142n;
    hash = xorshift64(hash);
    return (Number(hash) / 18446744073709551615 - 0.5) * 2 * DELTA;
  }}

  var cache = new WeakMap();
  var frameCounter = 0;

  function applyNoiseToRect(rect, element) {{
    if (!element || DELTA <= 0) return rect;
    var result = {{
      x: rect.x + detNoise(element, 0),
      y: rect.y + detNoise(element, 1),
      width: rect.width + detNoise(element, 2),
      height: rect.height + detNoise(element, 3),
      top: rect.top + detNoise(element, 4),
      right: rect.right + detNoise(element, 5),
      bottom: rect.bottom + detNoise(element, 6),
      left: rect.left + detNoise(element, 7),
      toJSON: function() {{
        return {{ x: this.x, y: this.y, width: this.width, height: this.height, top: this.top, right: this.right, bottom: this.bottom, left: this.left }};
      }}
    }};
    return result;
  }}

  if (typeof Element !== 'undefined') {{
    var origGetBoundingClientRect = Element.prototype.getBoundingClientRect;
    Element.prototype.getBoundingClientRect = function() {{
      var rect = origGetBoundingClientRect.call(this);
      return applyNoiseToRect(rect, this);
    }};

    var origGetClientRects = Element.prototype.getClientRects;
    Element.prototype.getClientRects = function() {{
      var rectList = origGetClientRects.call(this);
      var result = [];
      for (var i = 0; i < rectList.length; i++) {{
        result.push(applyNoiseToRect(rectList[i], this));
      }}
      return result;
    }};
  }}
}})();"#,
            delta = delta,
            seed = seed,
        )
    }

    // ── Screen/Display fingerprint ───────────────────────────────

    fn build_screen_display_js(config: &ScreenDisplayConfig) -> String {
        let width = config.width;
        let height = config.height;
        let color_depth = config.color_depth;
        let dpr = config.device_pixel_ratio;

        format!(
            r#"(function() {{
  var WIDTH = {width};
  var HEIGHT = {height};
  var COLOR_DEPTH = {color_depth};
  var DPR = {dpr};

  if (typeof screen !== 'undefined') {{
    Object.defineProperty(screen, 'width', {{ get: function() {{ return WIDTH; }}, configurable: true }});
    Object.defineProperty(screen, 'height', {{ get: function() {{ return HEIGHT; }}, configurable: true }});
    Object.defineProperty(screen, 'availWidth', {{ get: function() {{ return WIDTH; }}, configurable: true }});
    Object.defineProperty(screen, 'availHeight', {{ get: function() {{ return HEIGHT - 40; }}, configurable: true }});
    Object.defineProperty(screen, 'colorDepth', {{ get: function() {{ return COLOR_DEPTH; }}, configurable: true }});
    Object.defineProperty(screen, 'pixelDepth', {{ get: function() {{ return COLOR_DEPTH; }}, configurable: true }});
  }}

  if (typeof window !== 'undefined') {{
    Object.defineProperty(window, 'devicePixelRatio', {{ get: function() {{ return DPR; }}, configurable: true }});
    Object.defineProperty(window, 'outerWidth', {{ get: function() {{ return WIDTH; }}, configurable: true }});
    Object.defineProperty(window, 'outerHeight', {{ get: function() {{ return HEIGHT; }}, configurable: true }});
    Object.defineProperty(window, 'innerWidth', {{ get: function() {{ return WIDTH; }}, configurable: true }});
    Object.defineProperty(window, 'innerHeight', {{ get: function() {{ return HEIGHT - 80; }}, configurable: true }});
    Object.defineProperty(window, 'screenX', {{ get: function() {{ return 0; }}, configurable: true }});
    Object.defineProperty(window, 'screenY', {{ get: function() {{ return 0; }}, configurable: true }});
    Object.defineProperty(window, 'screenLeft', {{ get: function() {{ return 0; }}, configurable: true }});
    Object.defineProperty(window, 'screenTop', {{ get: function() {{ return 0; }}, configurable: true }});
  }}
}})();"#,
            width = width,
            height = height,
            color_depth = color_depth,
            dpr = dpr,
        )
    }

    // ── Plugin/MimeType spoofing ────────────────────────────────

    /// Chrome page-surface spoof segment: navigator.plugins / navigator.mimeTypes
    /// PLUS the `window.chrome` object (e130, REQ-BRW-002 rendering-face API gap
    /// closure). The two belong to one segment on purpose: they are the same
    /// "Chrome-specific page surface" family, and the fingerprint evaluation
    /// carrier (fingerprint_website_eval_e2e) consumes exactly this one
    /// StealthHooks segment for its new-document payload, so the chrome object
    /// must ride in the same bytes. The chrome section is build-time UA-gated
    /// (`navigator.user_agent` contains "Chrome"): real Firefox exposes NO
    /// window.chrome, so its presence under a Firefox UA is itself a detection
    /// signal (constitution: per-cell indistinguishability with the browser the
    /// UA claims).
    fn build_plugin_js(config: &PluginConfig, navigator_profile: &NavigatorProfile) -> String {
        let plugins_json = serde_json::to_string(&config.plugins).unwrap_or_else(|_| "[]".into());
        let mime_types_json =
            serde_json::to_string(&config.mime_types).unwrap_or_else(|_| "[]".into());
        // Clamp plugin_count to actual plugins length to avoid fingerprint-detectable
        // inconsistency where navigator.plugins.length reports fewer items than are
        // actually accessible by index.
        let plugin_count = config.plugin_count.min(config.plugins.len() as u32);
        // Chrome-family UA gate for the window.chrome section (see doc above).
        let chrome_surface = navigator_profile.user_agent.contains("Chrome");

        // e124 rewrite (battery-red root cause): the previous payload returned a
        // PLAIN ARRAY for navigator.plugins and then ran
        // `Object.defineProperty(arr, 'length', {get, configurable: true})` on it —
        // an Array's `length` is non-configurable by spec, so EVERY
        // navigator.plugins read threw
        // `TypeError: can't redefine non-configurable property "length"`
        // (the payload only defines the getter at install time; the throw fires on
        // first read, so page-creation installs never noticed). Detection pages
        // that probe plugins (bot.sannysoft.com's Plugins Length row) caught the
        // exception mid-script and aborted their whole detection table. The spoof
        // now builds spec-shaped fakes instead:
        //   - navigator.plugins  : Object.create(PluginArray.prototype) with an OWN
        //     `length` getter (fresh object — configurable target), indexed entries,
        //     item/namedItem/refresh and Symbol.toStringTag 'PluginArray'
        //     (`instanceof PluginArray` passes; Object.prototype.toString tags
        //     correctly).
        //   - each plugin        : Object.create(Plugin.prototype) +
        //     Symbol.toStringTag 'Plugin' (`toString()` returns '[object Plugin]').
        //   - navigator.mimeTypes: MimeTypeArray.prototype carrier, same shape.
        // Index getters close over a `let`-captured slot (the old `var` loop
        // captured the loop variable by reference — every index read returned
        // items[length] === undefined).
        format!(
            r#"(function() {{
  var PLUGIN_COUNT = {plugin_count};
  var PLUGIN_NAMES = {plugins};
  var MIME_TYPES = {mime_types};

  function makePlugin(name, filename, description, mimes) {{
    var p = Object.create(Plugin.prototype);
    Object.defineProperty(p, 'name', {{ get: function() {{ return name; }}, enumerable: true }});
    Object.defineProperty(p, 'filename', {{ get: function() {{ return filename; }}, enumerable: true }});
    Object.defineProperty(p, 'description', {{ get: function() {{ return description; }}, enumerable: true }});
    Object.defineProperty(p, 'length', {{ get: function() {{ return mimes.length; }}, enumerable: true, configurable: true }});
    for (let mi = 0; mi < mimes.length; mi++) {{
      let m = mimes[mi];
      Object.defineProperty(p, String(mi), {{ get: function() {{ return m; }}, enumerable: true, configurable: true }});
    }}
    try {{ Object.defineProperty(p, Symbol.toStringTag, {{ value: 'Plugin' }}); }} catch (e) {{}}
    return p;
  }}

  function makeMimeType(type, suffixes, description, enabledPlugin) {{
    var m = Object.create(MimeType.prototype);
    Object.defineProperty(m, 'type', {{ get: function() {{ return type; }}, enumerable: true }});
    Object.defineProperty(m, 'suffixes', {{ get: function() {{ return suffixes; }}, enumerable: true }});
    Object.defineProperty(m, 'description', {{ get: function() {{ return description; }}, enumerable: true }});
    if (enabledPlugin) {{
      Object.defineProperty(m, 'enabledPlugin', {{ get: function() {{ return enabledPlugin; }}, enumerable: true }});
    }}
    try {{ Object.defineProperty(m, Symbol.toStringTag, {{ value: 'MimeType' }}); }} catch (e) {{}}
    return m;
  }}

  if (typeof navigator !== 'undefined' && typeof Plugin !== 'undefined' && typeof MimeType !== 'undefined') {{
    var pluginObjs = PLUGIN_NAMES.map(function(name) {{
      var mimesForPlugin = MIME_TYPES.slice(0, Math.min(MIME_TYPES.length, PLUGIN_NAMES.length > 1 ? 1 : MIME_TYPES.length));
      return makePlugin(name, 'internal-pdf-viewer', name, mimesForPlugin);
    }});
    // Wire each MimeType's enabledPlugin back to its owning fake (Chrome
    // shape); the mime fakes are rebuilt so every plugin gets its own pair.
    for (let pi = 0; pi < pluginObjs.length; pi++) {{
      let plugin = pluginObjs[pi];
      let ownMimes = MIME_TYPES.map(function(t) {{
        return makeMimeType(t, t === 'application/pdf' ? 'pdf' : 'pdf', '', plugin);
      }});
      Object.defineProperty(plugin, 'length', {{ get: function() {{ return ownMimes.length; }}, enumerable: true }});
      for (let oi = 0; oi < ownMimes.length; oi++) {{
        let om = ownMimes[oi];
        Object.defineProperty(plugin, String(oi), {{ get: function() {{ return om; }}, enumerable: true }});
      }}
    }}

    var pluginsCarrier = Object.create(PluginArray.prototype);
    Object.defineProperty(pluginsCarrier, 'length', {{ get: function() {{ return PLUGIN_COUNT; }}, enumerable: true }});
    for (let i = 0; i < pluginObjs.length; i++) {{
      let entry = pluginObjs[i];
      Object.defineProperty(pluginsCarrier, String(i), {{ get: function() {{ return entry; }}, enumerable: true }});
      try {{
        Object.defineProperty(pluginsCarrier, entry.name, {{ get: function() {{ return entry; }}, enumerable: true }});
      }} catch (e) {{}}
    }}
    pluginsCarrier.item = function(i) {{ return pluginObjs[i] || null; }};
    pluginsCarrier.namedItem = function(name) {{
      for (var j = 0; j < pluginObjs.length; j++) {{
        if (pluginObjs[j] && pluginObjs[j].name === name) return pluginObjs[j];
      }}
      return null;
    }};
    pluginsCarrier.refresh = function() {{}};
    try {{ Object.defineProperty(pluginsCarrier, Symbol.toStringTag, {{ value: 'PluginArray' }}); }} catch (e) {{}}

    var mimeCarrier = Object.create(MimeTypeArray.prototype);
    var allMimes = [];
    for (let p = 0; p < pluginObjs.length; p++) {{
      let pl = pluginObjs[p];
      for (let q = 0; q < pl.length; q++) {{ allMimes.push(pl[q]); }}
    }}
    Object.defineProperty(mimeCarrier, 'length', {{ get: function() {{ return allMimes.length; }}, enumerable: true }});
    for (let k = 0; k < allMimes.length; k++) {{
      let km = allMimes[k];
      Object.defineProperty(mimeCarrier, String(k), {{ get: function() {{ return km; }}, enumerable: true }});
      try {{
        Object.defineProperty(mimeCarrier, km.type, {{ get: function() {{ return km; }}, enumerable: true }});
      }} catch (e) {{}}
    }}
    mimeCarrier.item = function(i) {{ return allMimes[i] || null; }};
    mimeCarrier.namedItem = function(type) {{
      for (var r = 0; r < allMimes.length; r++) {{
        if (allMimes[r] && allMimes[r].type === type) return allMimes[r];
      }}
      return null;
    }};
    try {{ Object.defineProperty(mimeCarrier, Symbol.toStringTag, {{ value: 'MimeTypeArray' }}); }} catch (e) {{}}

    Object.defineProperty(navigator, 'plugins', {{
      get: function() {{ return pluginsCarrier; }},
      configurable: true
    }});

    Object.defineProperty(navigator, 'mimeTypes', {{
      get: function() {{ return mimeCarrier; }},
      configurable: true
    }});
  }}
{chrome_section}
}})();"#,
            plugin_count = plugin_count,
            plugins = plugins_json,
            mime_types = mime_types_json,
            chrome_section = if chrome_surface { Self::CHROME_SURFACE_JS.trim() } else { "" },
        )
    }

    /// `window.chrome` spoof — real Chrome vanilla-page shape (own enumerable
    /// data property of Window carrying loadTimes / csi / app, in that key
    /// order). Its own realm guards make it inert outside page realms (real
    /// Chrome workers have no window.chrome either) and idempotent across
    /// re-injections.
    ///
    /// e135 oracle (real Chrome 149/150 stable, headless + headful — probes
    /// under /tmp/e135-chrome-probe): every loadTimes/csi timestamp is a
    /// REAL navigation-timing value (requestTime=navigationStart,
    /// commitLoadTime=responseStart, finishDocumentLoadTime=
    /// domContentLoadedEventEnd, finishLoadTime=loadEventEnd, firstPaintTime
    /// = the first-paint entry — seconds-truncated, 0 until the event
    /// fired), csi's onload key is `onloadT`, and the vanilla page carries
    /// NO runtime member (runtime exists only in extension contexts; the
    /// e124-era engine_props face already deletes it as a ChromeDriver
    /// signal — this face agrees with it now).
    ///
    /// e141 native-toString facade: real Chrome answers every toString
    /// channel with the `[native code]` form and INHERITS toString (no own
    /// property — oracle /tmp/e141-tostring-probe, Chrome 150 headless:
    /// loadTimes/csi own props [length, name, prototype], name '', `new`
    /// yields a plain object; app methods own props [length, name], no
    /// prototype, `new` throws). A per-function own toString would lose the
    /// adversarial channel `Function.prototype.toString.call(f)` (it
    /// bypasses own properties) and would itself surface as an
    /// own-property differential, so every spoofed function is exposed
    /// through a Proxy carrier instead: the engine renders its anonymous
    /// `[native code]` form through all three channels for callable
    /// proxies (the string is engine-generated — there is no patch text to
    /// find), and the trap-less proxy forwards every introspection to a
    /// target whose own-property shape mirrors the oracle table above.
    /// Residual, unreachable from JS in either engine (bound/proxy
    /// carriers render anonymous in V8 too): real Chrome shows the NAMED
    /// native form (`function getDetails() { [native code] }`) for app
    /// methods.
    const CHROME_SURFACE_JS: &str = r#"
  // window.chrome (e130 shape, e135 oracle real-valued): bot.sannysoft.com's
  // "Chrome (New)" row fails on plain absence; deeper probes (creepjs et al.)
  // compare the member set, so a bare {} is not enough. Member set and every
  // timestamp mirror the real vanilla-page API — navigation-timing deep
  // cross-validation cannot separate them from the native one.
  if (typeof window !== 'undefined' && typeof Plugin !== 'undefined' && typeof MimeType !== 'undefined'
      && !(typeof window.chrome !== 'undefined' && window.chrome)) {
    function baoChromeLoadTimes() {
      var t = (typeof performance !== 'undefined' && performance.timing) ? performance.timing : null;
      if (!t) { return {}; }
      var firstPaintMs = 0;
      try {
        var paints = performance.getEntriesByType('paint');
        for (var i = 0; i < paints.length; i++) {
          if (paints[i].name === 'first-paint') { firstPaintMs = t.navigationStart + paints[i].startTime; break; }
        }
      } catch (e) {}
      // connection family follows the page's egress protocol: https rides
      // the stealth TLS stack (h2 ALPN), plain http is the HTTP/1.1 bridge,
      // non-network schemes carry no negotiated protocol
      var proto = (window.location && window.location.protocol) || '';
      var https = proto === 'https:';
      var network = proto === 'https:' || proto === 'http:';
      var navType = 'Other';
      try {
        var nt = (performance.navigation && typeof performance.navigation.type === 'number') ? performance.navigation.type : 0;
        if (nt === 1) { navType = 'Reload'; } else if (nt === 2) { navType = 'BackForward'; }
      } catch (e) {}
      return {
        requestTime: t.navigationStart / 1000,
        startLoadTime: t.navigationStart / 1000,
        commitLoadTime: t.responseStart / 1000,
        finishDocumentLoadTime: t.domContentLoadedEventEnd / 1000,
        finishLoadTime: t.loadEventEnd / 1000,
        firstPaintTime: firstPaintMs / 1000,
        firstPaintAfterLoadTime: 0,
        navigationType: navType,
        wasFetchedViaSpdy: https,
        wasNpnNegotiated: https,
        npnNegotiatedProtocol: https ? 'h2' : (network ? 'unknown' : ''),
        wasAlternateProtocolAvailable: false,
        connectionInfo: network ? (https ? 'h2' : 'http/1.1') : 'unknown'
      };
    }
    function baoChromeCsi() {
      var t = (typeof performance !== 'undefined' && performance.timing) ? performance.timing : null;
      var start = t ? t.navigationStart : 0;
      var onload = t ? t.loadEventEnd : 0;
      var pageT = (typeof performance !== 'undefined' && performance.now)
        ? performance.now() / 1000
        : (start ? Math.max(0, Date.now() - start) / 1000 : 0);
      return { startE: start, onloadT: onload, pageT: pageT, tran: 15 };
    }
    // e141 native-toString facade carrier: every spoofed function is
    // exposed as a Proxy over a shape-matched plain target. The engine
    // itself renders the anonymous [native code] form for callable proxies
    // on every channel — Function.prototype.toString.call(f), f.toString()
    // and ''+f are all engine-generated and mutually equal, so the
    // adversarial F.p.toString.call channel (which bypasses any own
    // toString a per-function patch would install) is covered with zero
    // patch text in the page. The trap-less proxy forwards every
    // introspection trap to the target: constructible carriers carry own
    // [name, prototype, length] with name '' (oracle: chrome.loadTimes /
    // chrome.csi — `new` yields a plain object); method carriers use an
    // arrow target (own [name, length], no prototype, `new` throws —
    // oracle: the four chrome.app methods).
    function baoMakeNative(impl, name, constructible) {
      var target;
      if (constructible) {
        // plain-function target: own [name, prototype, length], `new` works
        target = function() {};
      } else {
        // arrow target: own [name, length] only — no prototype property,
        // not constructible (`new` throws), mirroring the app methods
        target = () => undefined;
      }
      Object.defineProperty(target, 'name', { value: name, configurable: true });
      return new Proxy(target, {
        apply: function(t, thisArg, args) { return impl.apply(thisArg, args); }
      });
    }
    var baoChrome = {
      loadTimes: baoMakeNative(baoChromeLoadTimes, '', true),
      csi: baoMakeNative(baoChromeCsi, '', true),
      app: {
        isInstalled: false,
        getDetails: baoMakeNative(function() { return null; }, 'getDetails', false),
        getIsInstalled: baoMakeNative(function() { return false; }, 'getIsInstalled', false),
        installState: baoMakeNative(function(callback) {
          if (typeof callback === 'function') {
            setTimeout(function() { callback('not_installed'); }, 0);
          }
        }, 'installState', false),
        runningState: baoMakeNative(function() { return 'cannot_run'; }, 'runningState', false),
        InstallState: { DISABLED: 'disabled', INSTALLED: 'installed', NOT_INSTALLED: 'not_installed' },
        RunningState: { CANNOT_RUN: 'cannot_run', READY_TO_RUN: 'ready_to_run', RUNNING: 'running' }
      }
    };
    try {
      Object.defineProperty(window, 'chrome', { value: baoChrome, writable: true, enumerable: true, configurable: false });
    } catch (e) {}
  }"#;

    // ── SpeechSynthesis voices ───────────────────────────────────

    fn build_speech_js(config: &SpeechConfig) -> String {
        if !config.enabled {
            return String::new();
        }
        let voices_json = serde_json::to_string(&config.voices).unwrap_or_else(|_| "[]".into());

        format!(
            r#"(function() {{
  var VOICE_NAMES = {voices};

  function makeVoice(name, lang, localService, isDefault) {{
    var v = Object.create(SpeechSynthesisVoice.prototype);
    Object.defineProperty(v, 'voiceURI', {{ get: function() {{ return name; }}, enumerable: true }});
    Object.defineProperty(v, 'name', {{ get: function() {{ return name; }}, enumerable: true }});
    Object.defineProperty(v, 'lang', {{ get: function() {{ return lang; }}, enumerable: true }});
    Object.defineProperty(v, 'localService', {{ get: function() {{ return localService; }}, enumerable: true }});
    Object.defineProperty(v, 'isDefault', {{ get: function() {{ return isDefault; }}, enumerable: true }});
    return v;
  }}

  if (typeof navigator !== 'undefined' && navigator.speechSynthesis) {{
    var voiceList = VOICE_NAMES.map(function(name, idx) {{
      var langMap = {{
        'Google US English': 'en-US',
        'Google UK English Female': 'en-GB',
        'Google UK English Male': 'en-GB',
        'Google Deutsch': 'de-DE',
        'Google Français': 'fr-FR',
        'Google Español': 'es-ES',
        'Google Italiano': 'it-IT',
        'Google Japanese': 'ja-JP',
        'Google Nederlands': 'nl-NL',
        'Google Polski': 'pl-PL',
        'Google Português do Brasil': 'pt-BR',
        'Google Pútonghuà': 'zh-CN'
      }};
      var lang = langMap[name] || 'en-US';
      return makeVoice(name, lang, false, idx === 0);
    }});

    voiceList.push(makeVoice('Microsoft David - English (United States)', 'en-US', true, false));
    voiceList.push(makeVoice('Microsoft Zira - English (United States)', 'en-US', true, false));

    var origGetVoices = navigator.speechSynthesis.getVoices;
    navigator.speechSynthesis.getVoices = function() {{
      return voiceList;
    }};

    Object.defineProperty(navigator.speechSynthesis, 'speaking', {{ get: function() {{ return false; }}, configurable: true }});
    Object.defineProperty(navigator.speechSynthesis, 'pending', {{ get: function() {{ return false; }}, configurable: true }});
  }}
}})();"#,
            voices = voices_json,
        )
    }

    // ── MediaDevices enumeration ─────────────────────────────────

    fn build_media_devices_js(config: &MediaDevicesConfig) -> String {
        if !config.enabled {
            return String::new();
        }
        let audio_input_count = config.audio_input_count;
        let video_input_count = config.video_input_count;
        let audio_output_count = config.audio_output_count;

        format!(
            r#"(function() {{
  var AUDIO_IN = {audio_input_count};
  var VIDEO_IN = {video_input_count};
  var AUDIO_OUT = {audio_output_count};

  function makeDevice(kind, label, deviceId, groupId) {{
    var d = Object.create(MediaDeviceInfo.prototype);
    Object.defineProperty(d, 'kind', {{ get: function() {{ return kind; }}, enumerable: true }});
    Object.defineProperty(d, 'label', {{ get: function() {{ return label; }}, enumerable: true }});
    Object.defineProperty(d, 'deviceId', {{ get: function() {{ return deviceId; }}, enumerable: true }});
    Object.defineProperty(d, 'groupId', {{ get: function() {{ return groupId; }}, enumerable: true }});
    d.toJSON = function() {{
      return {{ kind: kind, label: label, deviceId: deviceId, groupId: groupId }};
    }};
    return d;
  }}

  if (typeof navigator !== 'undefined' && navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {{
    var origEnumerate = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
    navigator.mediaDevices.enumerateDevices = function() {{
      return origEnumerate().then(function(realDevices) {{
        var hasLabels = realDevices.some(function(d) {{ return d.label && d.label.length > 0; }});
        if (hasLabels) return realDevices;

        var devices = [];
        for (var i = 0; i < AUDIO_IN; i++) {{
          devices.push(makeDevice('audioinput', '', 'audioinput-' + i, 'group-' + i));
        }}
        for (var i = 0; i < VIDEO_IN; i++) {{
          devices.push(makeDevice('videoinput', '', 'videoinput-' + i, 'group-' + (AUDIO_IN + i)));
        }}
        for (var i = 0; i < AUDIO_OUT; i++) {{
          devices.push(makeDevice('audiooutput', '', 'audiooutput-' + i, 'group-' + (AUDIO_IN + VIDEO_IN + i)));
        }}
        return devices;
      }}).catch(function() {{
        var devices = [];
        for (var i = 0; i < AUDIO_IN; i++) {{
          devices.push(makeDevice('audioinput', '', 'audioinput-' + i, 'group-' + i));
        }}
        for (var i = 0; i < VIDEO_IN; i++) {{
          devices.push(makeDevice('videoinput', '', 'videoinput-' + i, 'group-' + (AUDIO_IN + i)));
        }}
        for (var i = 0; i < AUDIO_OUT; i++) {{
          devices.push(makeDevice('audiooutput', '', 'audiooutput-' + i, 'group-' + (AUDIO_IN + VIDEO_IN + i)));
        }}
        return devices;
      }});
    }};
  }}
}})();"#,
            audio_input_count = audio_input_count,
            video_input_count = video_input_count,
            audio_output_count = audio_output_count,
        )
    }

    // ── Permissions API ──────────────────────────────────────────
    //
    // RETIRED (e130, REQ-BRW-002 rendering-face API gap closure): this JS
    // wrapper around `navigator.permissions.query` predates servo shipping
    // the Permissions API — while the API was absent the wrapper was a
    // structural no-op (its `navigator.permissions && navigator.permissions.query`
    // guard never fired). The servo vendor tree ships the full native
    // implementation (`dom/permission/`, `dom_permissions_enabled` pref —
    // flipped on at the bao embedder surface, src/bao_browser/src/lib.rs):
    // `query()` resolves a REAL PermissionStatus DOM object (EventTarget
    // interface, spec-shaped `state`), and states follow the spec defaults
    // ("prompt" on secure contexts — Chrome's default posture). Re-activating
    // the JS wrapper in the realms where combined_js is evaluated
    // (page-creation installs + worker scopes) would REPLACE that native
    // surface with a plain object whose promises fail
    // `instanceof PermissionStatus`, and would leave navigated pages (which
    // never see combined_js) on the native path — a cross-path inconsistency
    // between realms of the same browser, the same defect class that retired
    // the canvas read-out JS hooks (user ruling 2026-09-09, BRW-004 C13).
    // The PermissionsConfig stays on the profile surface (frozen plumbing —
    // from_profile signature unchanged); only the hook payload is empty.

    fn build_permissions_js(_config: &PermissionsConfig) -> String {
        String::new()
    }

    // ── WebGL context attributes ─────────────────────────────────

    fn build_webgl_context_js(config: &WebGLContextConfig) -> String {
        if !config.enabled {
            return String::new();
        }
        let antialias = config.antialias;
        let depth = config.depth;
        let stencil = config.stencil;
        let alpha = config.alpha;
        let premultiplied_alpha = config.premultiplied_alpha;
        let preserve_drawing_buffer = config.preserve_drawing_buffer;
        let power_preference = &config.power_preference;
        let fail_if_major_performance_caveat = config.fail_if_major_performance_caveat;

        format!(
            r#"(function() {{
  var CONTEXT_ATTRS = {{
    antialias: {antialias},
    depth: {depth},
    stencil: {stencil},
    alpha: {alpha},
    premultipliedAlpha: {premultiplied_alpha},
    preserveDrawingBuffer: {preserve_drawing_buffer},
    powerPreference: {power_preference:?},
    failIfMajorPerformanceCaveat: {fail_if_major_performance_caveat}
  }};

  if (typeof WebGLRenderingContext !== 'undefined') {{
    var origGetContextAttributes = WebGLRenderingContext.prototype.getContextAttributes;
    WebGLRenderingContext.prototype.getContextAttributes = function() {{
      if (origGetContextAttributes) {{
        try {{
          var real = origGetContextAttributes.call(this);
          if (real) {{
            return {{
              antialias: CONTEXT_ATTRS.antialias,
              depth: CONTEXT_ATTRS.depth,
              stencil: CONTEXT_ATTRS.stencil,
              alpha: CONTEXT_ATTRS.alpha,
              premultipliedAlpha: CONTEXT_ATTRS.premultipliedAlpha,
              preserveDrawingBuffer: CONTEXT_ATTRS.preserveDrawingBuffer,
              powerPreference: CONTEXT_ATTRS.powerPreference,
              failIfMajorPerformanceCaveat: CONTEXT_ATTRS.failIfMajorPerformanceCaveat
            }};
          }}
        }} catch(e) {{}}
      }}
      return CONTEXT_ATTRS;
    }};
  }}

  if (typeof WebGL2RenderingContext !== 'undefined') {{
    var origGetContextAttributes2 = WebGL2RenderingContext.prototype.getContextAttributes;
    WebGL2RenderingContext.prototype.getContextAttributes = function() {{
      if (origGetContextAttributes2) {{
        try {{
          var real = origGetContextAttributes2.call(this);
          if (real) {{
            return {{
              antialias: CONTEXT_ATTRS.antialias,
              depth: CONTEXT_ATTRS.depth,
              stencil: CONTEXT_ATTRS.stencil,
              alpha: CONTEXT_ATTRS.alpha,
              premultipliedAlpha: CONTEXT_ATTRS.premultipliedAlpha,
              preserveDrawingBuffer: CONTEXT_ATTRS.preserveDrawingBuffer,
              powerPreference: CONTEXT_ATTRS.powerPreference,
              failIfMajorPerformanceCaveat: CONTEXT_ATTRS.failIfMajorPerformanceCaveat
            }};
          }}
        }} catch(e) {{}}
      }}
      return CONTEXT_ATTRS;
    }};
  }}
}})();"#,
            antialias = antialias,
            depth = depth,
            stencil = stencil,
            alpha = alpha,
            premultiplied_alpha = premultiplied_alpha,
            preserve_drawing_buffer = preserve_drawing_buffer,
            power_preference = power_preference,
            fail_if_major_performance_caveat = fail_if_major_performance_caveat,
        )
    }

    // ── navigator.connection ─────────────────────────────────────

    fn build_connection_js(config: &ConnectionConfig) -> String {
        if !config.enabled {
            return String::new();
        }
        let effective_type = &config.effective_type;
        let downlink = config.downlink;
        let rtt = config.rtt;
        let save_data = config.save_data;

        format!(
            r#"(function() {{
  var EFFECTIVE_TYPE = {effective_type:?};
  var DOWNLINK = {downlink};
  var RTT = {rtt};
  var SAVE_DATA = {save_data};

  if (typeof navigator !== 'undefined') {{
    var connObj = {{
      effectiveType: EFFECTIVE_TYPE,
      downlink: DOWNLINK,
      rtt: RTT,
      saveData: SAVE_DATA,
      type: 'wifi',
      onchange: null,
      addEventListener: function(type, listener) {{
        if (type === 'change') this.onchange = listener;
      }},
      removeEventListener: function(type) {{
        if (type === 'change') this.onchange = null;
      }},
      dispatchEvent: function() {{ return true; }}
    }};

    if (navigator.connection) {{
      try {{
        Object.defineProperty(navigator.connection, 'effectiveType', {{ get: function() {{ return EFFECTIVE_TYPE; }}, configurable: true }});
        Object.defineProperty(navigator.connection, 'downlink', {{ get: function() {{ return DOWNLINK; }}, configurable: true }});
        Object.defineProperty(navigator.connection, 'rtt', {{ get: function() {{ return RTT; }}, configurable: true }});
        Object.defineProperty(navigator.connection, 'saveData', {{ get: function() {{ return SAVE_DATA; }}, configurable: true }});
      }} catch(e) {{
        Object.defineProperty(navigator, 'connection', {{ get: function() {{ return connObj; }}, configurable: true }});
      }}
    }} else {{
      Object.defineProperty(navigator, 'connection', {{ get: function() {{ return connObj; }}, configurable: true }});
    }}
  }}
}})();"#,
            effective_type = effective_type,
            downlink = downlink,
            rtt = rtt,
            save_data = save_data,
        )
    }

    // ── iframe contentWindow normalization ───────────────────────

    fn build_iframe_js(config: &IframeConfig) -> String {
        if !config.enabled {
            return String::new();
        }

        r#"(function() {
  if (typeof HTMLIFrameElement === 'undefined') return;

  var origContentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  var origContentDocument = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentDocument');

  if (origContentWindow && origContentWindow.get) {
    var origCWGetter = origContentWindow.get;
    Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', {
      get: function() {
        var win = origCWGetter.call(this);
        if (!win) return null;
        try {
          var doc = win.document;
          return win;
        } catch(e) {
          return win;
        }
      },
      configurable: true
    });
  }

  if (origContentDocument && origContentDocument.get) {
    var origCDGetter = origContentDocument.get;
    Object.defineProperty(HTMLIFrameElement.prototype, 'contentDocument', {
      get: function() {
        try {
          return origCDGetter.call(this);
        } catch(e) {
          return null;
        }
      },
      configurable: true
    });
  }
})();"#.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::canvas::CanvasNoise;
    use crate::navigator::{NavigatorProfile, ScreenProfile};
    use crate::profile::StealthProfile;
    use crate::webgl_audio::{AudioProfile, WebGLProfile};

    fn firefox_hooks() -> StealthHooks {
        let profile = StealthProfile::firefox_default();
        StealthHooks::from_profile(
            &profile.canvas,
            &profile.audio,
            &profile.navigator,
            &profile.screen,
            &profile.webgl,
            &profile.font,
            &profile.battery,
            profile.webrtc_mode,
            &profile.timing,
            &profile.clientrects,
            &profile.screen_display,
            &profile.plugin,
            &profile.speech,
            &profile.media_devices,
            &profile.permissions,
            &profile.webgl_context,
            &profile.connection,
            &profile.iframe,
        )
    }

    fn chrome_hooks() -> StealthHooks {
        let profile = StealthProfile::chrome_default();
        StealthHooks::from_profile(
            &profile.canvas,
            &profile.audio,
            &profile.navigator,
            &profile.screen,
            &profile.webgl,
            &profile.font,
            &profile.battery,
            profile.webrtc_mode,
            &profile.timing,
            &profile.clientrects,
            &profile.screen_display,
            &profile.plugin,
            &profile.speech,
            &profile.media_devices,
            &profile.permissions,
            &profile.webgl_context,
            &profile.connection,
            &profile.iframe,
        )
    }

    // ── Canvas JS segment retirement (user ruling 2026-09-09, BRW-004 C13) ──
    // The four canvas read-out JS hooks are RETIRED: canvas noise flows
    // exclusively through the paint-thread single choke point
    // (CanvasCommand::GetImageData, commit 6bcf30af). These assertions pin
    // the zero-residue state of the combined hook blob.

    #[test]
    fn canvas_js_segment_retired_zero_interception_in_combined() {
        let hooks = firefox_hooks();
        let combined = hooks.combined_js();
        // The retired four segments' unique interception signatures — none may
        // survive in the injected blob.
        for residue in [
            "HTMLCanvasElement.prototype.toDataURL",
            "origToDataURL",
            "HTMLCanvasElement.prototype.toBlob",
            "origToBlob",
            "CanvasRenderingContext2D.prototype.getImageData",
            "origGetImageData",
            "OffscreenCanvasRenderingContext2D.prototype.getImageData",
            "origOffscreenGetImageData",
            "addNoiseToImageData",
        ] {
            assert!(
                !combined.contains(residue),
                "retired canvas JS hook residue in combined blob: {residue}"
            );
        }
    }

    #[test]
    fn canvas_js_segment_retired_worker_and_window_blobs_clean() {
        // W1a's worker-safety typeof guards existed only to let the canvas
        // blob install inside a DedicatedWorkerGlobalScope; with the segment
        // retired, the canvas-specific guards must be gone too (the audio
        // segment keeps its own AudioBuffer guard).
        let hooks = firefox_hooks();
        let combined = hooks.combined_js();
        assert!(
            !combined.contains("typeof HTMLCanvasElement"),
            "canvas blob typeof guards retired with the segment"
        );
        assert!(
            !combined.contains("typeof OffscreenCanvasRenderingContext2D"),
            "Offscreen canvas patch retired with the segment"
        );
        // The audio segment's worker guard is NOT collateral damage.
        assert!(
            combined.contains("typeof AudioBuffer !== 'undefined'"),
            "audio worker-realm guard must survive the canvas retirement"
        );
    }

    #[test]
    fn from_profile_keeps_canvas_seed_parameter_for_paint_layer() {
        // The from_profile signature still accepts the CanvasNoise profile:
        // the paint-layer seed plumbing (engine_props canvas_seed()/
        // canvas_amplitude() → servo set_canvas_noise_seed) is unchanged by
        // the JS segment retirement. Compile-level pin + non-empty blob.
        let canvas = CanvasNoise::new(4242);
        let audio = AudioProfile::new(42);
        let nav = NavigatorProfile::firefox();
        let screen = ScreenProfile::new(1920, 1080, 1.0);
        let webgl = WebGLProfile::firefox();
        let font = FontConfig::new(42);
        let battery = BatteryConfig::default();
        let timing = TimingConfig::default();
        let clientrects = ClientRectsConfig::default();
        let screen_display = ScreenDisplayConfig::default();
        let plugin = PluginConfig::default();
        let speech = SpeechConfig::default();
        let media_devices = MediaDevicesConfig::default();
        let permissions = PermissionsConfig::default();
        let webgl_context = WebGLContextConfig::default();
        let connection = ConnectionConfig::default();
        let iframe = IframeConfig::default();
        let hooks = StealthHooks::from_profile(
            &canvas,
            &audio,
            &nav,
            &screen,
            &webgl,
            &font,
            &battery,
            WebRtcMode::Default,
            &timing,
            &clientrects,
            &screen_display,
            &plugin,
            &speech,
            &media_devices,
            &permissions,
            &webgl_context,
            &connection,
            &iframe,
        );
        assert_eq!(canvas.seed(), 4242);
        assert!(
            !hooks.combined_js().is_empty(),
            "non-canvas hooks must still generate"
        );
    }

    #[test]
    fn audio_js_contains_getchanneldata_override() {
        let hooks = firefox_hooks();
        let js = hooks.audio_js();
        assert!(
            js.contains("AudioBuffer.prototype.getChannelData"),
            "audio JS must override getChannelData"
        );
        assert!(
            js.contains("origGetChannelData"),
            "audio JS must store original getChannelData"
        );
    }

    #[test]
    fn audio_js_contains_startrendering_override() {
        let hooks = firefox_hooks();
        let js = hooks.audio_js();
        assert!(
            js.contains("OfflineAudioContext.prototype.startRendering"),
            "audio JS must override startRendering"
        );
    }

    #[test]
    fn audio_js_contains_noise_algorithm() {
        let hooks = firefox_hooks();
        let js = hooks.audio_js();
        assert!(
            js.contains("detNoise"),
            "audio JS must have deterministic noise function"
        );
        assert!(
            js.contains("0x517CC1B727220A95n"),
            "audio JS must contain the index-multiply constant"
        );
    }

    #[test]
    fn audio_js_worker_safe_guards_audiobuffer() {
        // REQ-BRW-004 C13/C15: AudioBuffer is [Exposed=Window]; the audio blob
        // must not ReferenceError in a worker realm.
        let hooks = firefox_hooks();
        let js = hooks.audio_js();
        assert!(
            js.contains("typeof AudioBuffer !== 'undefined'"),
            "audio JS must guard AudioBuffer behind typeof (worker realm has no such global)"
        );
    }

    #[test]
    fn navigator_js_contains_user_agent_defineproperty() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("__bao_def(__nav_t, 'userAgent'"),
            "navigator JS must define userAgent"
        );
        // BCE (error.rs:74): every define goes through the __bao_def
        // swallow-guard — a refused non-configurable define must NOT leave
        // a pending exception on the ScriptThread context.
        assert!(
            js.contains("var __bao_def = function(obj, name, desc)"),
            "navigator JS defines must be guarded by __bao_def"
        );
    }

    #[test]
    fn navigator_js_contains_platform_defineproperty() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("__bao_def(__nav_t, 'platform'"),
            "navigator JS must define platform"
        );
    }

    #[test]
    fn navigator_js_contains_hardware_concurrency_defineproperty() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("__bao_def(__nav_t, 'hardwareConcurrency'"),
            "navigator JS must define hardwareConcurrency"
        );
    }

    #[test]
    fn navigator_js_contains_webdriver_false() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("__bao_def(__nav_t, 'webdriver'") && js.contains("return false"),
            "navigator JS must set webdriver to false"
        );
    }

    #[test]
    fn navigator_js_contains_screen_overrides() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("__bao_def(__scr_t, 'width'"),
            "navigator JS must define screen.width"
        );
        assert!(
            js.contains("__bao_def(__scr_t, 'height'"),
            "navigator JS must define screen.height"
        );
        assert!(
            js.contains("__bao_def(win, 'devicePixelRatio'"),
            "navigator JS must define window.devicePixelRatio"
        );
    }

    #[test]
    fn navigator_js_contains_webgl_getparameter_override() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("WebGLRenderingContext.prototype.getParameter"),
            "navigator JS must override WebGL getParameter"
        );
    }

    #[test]
    fn navigator_js_contains_webgl_getsupportedextensions_override() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("WebGLRenderingContext.prototype.getSupportedExtensions"),
            "navigator JS must override getSupportedExtensions"
        );
    }

    #[test]
    fn navigator_js_contains_webgl2_overrides() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("WebGL2RenderingContext.prototype.getParameter"),
            "navigator JS must override WebGL2 getParameter"
        );
        assert!(
            js.contains("WebGL2RenderingContext.prototype.getSupportedExtensions"),
            "navigator JS must override WebGL2 getSupportedExtensions"
        );
    }

    #[test]
    fn combined_js_concatenates_all() {
        let hooks = firefox_hooks();
        let combined = hooks.combined_js();
        // Canvas JS segment retired (user ruling 2026-09-09): noise via the
        // paint layer — the combined blob must carry NO canvas interception.
        assert!(
            !combined.contains("HTMLCanvasElement.prototype.toDataURL"),
            "combined JS must NOT contain retired canvas hooks"
        );
        assert!(
            combined.contains("AudioBuffer.prototype.getChannelData"),
            "combined JS must contain audio hooks"
        );
        assert!(
            combined.contains("__bao_def(__nav_t, 'userAgent'"),
            "combined JS must contain navigator hooks"
        );
        assert!(
            combined.contains("document.fonts.check"),
            "combined JS must contain font hooks"
        );
        assert!(
            combined.contains("navigator.getBattery"),
            "combined JS must contain battery hooks"
        );
        assert!(
            combined.contains("RTCPeerConnection"),
            "combined JS must contain WebRTC hooks"
        );
        assert!(
            combined.contains("performance.now"),
            "combined JS must contain timing hooks"
        );
        assert!(
            combined.contains("getBoundingClientRect"),
            "combined JS must contain clientrects hooks"
        );
        assert!(
            combined.contains("screen_display_js") || combined.contains("screen, 'width'"),
            "combined JS must contain screen/display hooks"
        );
        assert!(
            combined.contains("PLUGIN_COUNT"),
            "combined JS must contain plugin hooks"
        );
        assert!(
            combined.contains("getVoices"),
            "combined JS must contain speech hooks"
        );
        assert!(
            combined.contains("enumerateDevices"),
            "combined JS must contain media devices hooks"
        );
        // e130: the permissions JS wrapper is RETIRED — servo's native
        // Permissions API (dom_permissions_enabled, flipped at the bao
        // embedder surface) owns the query() surface with a real
        // PermissionStatus. The wrapper's assignment must stay gone.
        assert!(
            !combined.contains("navigator.permissions.query ="),
            "combined JS must NOT wrap the native navigator.permissions.query (e130 retirement)"
        );
        assert!(
            combined.contains("getContextAttributes"),
            "combined JS must contain WebGL context hooks"
        );
        assert!(
            combined.contains("effectiveType"),
            "combined JS must contain connection hooks"
        );
        assert!(
            combined.contains("contentWindow"),
            "combined JS must contain iframe hooks"
        );
        // e130: the Chrome page-surface spoof (plugins + window.chrome) rides
        // in the plugin segment; this test's profile is FIREFOX, so the
        // window.chrome section must be build-time gated OUT (real Firefox
        // exposes none).
        assert!(
            !combined.contains("Object.defineProperty(window, 'chrome'"),
            "combined JS (firefox profile) must NOT define window.chrome"
        );
    }

    // ── e130: window.chrome page-surface spoof ──────────────────────

    #[test]
    fn chrome_profile_plugin_js_carries_window_chrome() {
        let hooks = chrome_hooks();
        let js = hooks.plugin_js();
        assert!(
            js.contains("Object.defineProperty(window, 'chrome'"),
            "chrome-profile plugin payload must define window.chrome (sannysoft Chrome row)"
        );
        // e135 oracle (real Chrome 149/150, headless + headful): the
        // vanilla-page chrome own-key set is exactly [loadTimes, csi, app]
        // — in that order — with NO runtime member (extension contexts
        // only; carrying one is a ChromeDriver-class detection vector).
        for member in ["loadTimes", "csi", "app"] {
            assert!(
                js.contains(&format!("{}:", member)),
                "window.chrome spoof must carry the {} member (real Chrome shape)",
                member
            );
        }
        let load_times_idx = js.find("loadTimes:").expect("loadTimes key");
        let csi_idx = js.find("csi:").expect("csi key");
        let app_idx = js.find("app:").expect("app key");
        assert!(
            load_times_idx < csi_idx && csi_idx < app_idx,
            "window.chrome member order must be loadTimes, csi, app (real own-key order)"
        );
        assert!(
            !js.contains("runtime:"),
            "window.chrome must NOT carry a runtime member — real vanilla-page Chrome has \
             none and its presence is an automation signal (engine_props deletes it)"
        );
        // app member set: installState + runningState both present (running
        // state returns 'cannot_run' on a vanilla page).
        assert!(
            js.contains("installState"),
            "window.chrome.app must carry installState (documented vanilla-page shape)"
        );
        assert!(
            js.contains("runningState"),
            "window.chrome.app must carry runningState (e135 oracle member)"
        );
        assert!(
            js.contains("'cannot_run'"),
            "window.chrome.app.runningState must return 'cannot_run' (vanilla page)"
        );
        // Worker-safety: the section must be inert outside page realms (real
        // Chrome workers have no window.chrome) — internal window guard.
        assert!(
            js.contains("typeof window !== 'undefined'"),
            "window.chrome section must guard on typeof window (worker realms)"
        );
    }

    // ── e135: loadTimes/csi real-value derivation (oracle Chrome 149/150) ──

    #[test]
    fn chrome_surface_loadtimes_csi_derive_from_real_timing() {
        let hooks = chrome_hooks();
        let js = hooks.plugin_js();
        // loadTimes timestamps must come from the page's own navigation
        // timing (per-field mapping locked):
        //   requestTime/startLoadTime ← navigationStart
        //   commitLoadTime            ← responseStart
        //   finishDocumentLoadTime    ← domContentLoadedEventEnd
        //   finishLoadTime            ← loadEventEnd
        //   firstPaintTime            ← first-paint paint-timing entry
        for source in [
            "t.navigationStart / 1000",
            "t.responseStart / 1000",
            "t.domContentLoadedEventEnd / 1000",
            "t.loadEventEnd / 1000",
        ] {
            assert!(
                js.contains(source),
                "loadTimes must derive its timestamps from the real timing field ({})",
                source
            );
        }
        assert!(
            js.contains("getEntriesByType('paint')"),
            "firstPaintTime must come from the paint-timing entries (0 before first paint)"
        );
        // csi: the real API's onload key is `onloadT` (NOT onloadE) and
        // pageT is the elapsed time at call, not a load-delta.
        assert!(
            js.contains("onloadT:"),
            "csi must use the real key onloadT (oracle: startE/onloadT/pageT/tran)"
        );
        assert!(
            !js.contains("onloadE:"),
            "csi must NOT use the wrong key onloadE — real Chrome has onloadT"
        );
        assert!(
            js.contains("performance.now() / 1000"),
            "csi.pageT must be the elapsed time at call (performance.now based)"
        );
        // Synthetic fixed offsets are gone — real values only.
        for synthetic in ["+ 0.048", "+ 0.212", "+ 0.247", "+ 0.156"] {
            assert!(
                !js.contains(synthetic),
                "loadTimes must not carry the synthetic fixed offset {} (navigation-timing \
                 cross-validation detects it)",
                synthetic
            );
        }
        // Connection family follows the page protocol instead of a
        // hardcoded h2 (real Chrome reports http/1.1 + no-NPN on plain http).
        assert!(
            js.contains("'http/1.1'") && js.contains("'unknown'"),
            "loadTimes connection family must cover the plain-http shape (http/1.1 + unknown)"
        );
        // installState invokes its callback asynchronously (oracle: the
        // callback does not fire synchronously).
        assert!(
            js.contains("setTimeout(function() { callback('not_installed'); }, 0);"),
            "app.installState must invoke its callback asynchronously (oracle form)"
        );
    }

    #[test]
    fn firefox_profile_plugin_js_has_no_window_chrome() {
        let hooks = firefox_hooks();
        let js = hooks.plugin_js();
        assert!(
            !js.contains("Object.defineProperty(window, 'chrome'"),
            "firefox-profile plugin payload must NOT define window.chrome — real Firefox \
             exposes none, presence under a Firefox UA is itself a detection signal"
        );
    }

    #[test]
    fn permissions_js_retired_empty() {
        // e130: the JS wrapper around navigator.permissions.query is retired —
        // servo's native Permissions API (real PermissionStatus objects) owns
        // the surface. Both profiles must produce an empty payload.
        assert!(
            chrome_hooks().permissions_js().is_empty(),
            "permissions_js must be retired (empty) for the chrome profile"
        );
        assert!(
            firefox_hooks().permissions_js().is_empty(),
            "permissions_js must be retired (empty) for the firefox profile"
        );
    }

    #[test]
    fn different_profiles_produce_different_audio_js() {
        let ff = firefox_hooks();
        let ch = chrome_hooks();
        assert_ne!(
            ff.audio_js(),
            ch.audio_js(),
            "Firefox and Chrome should produce different audio JS (different seeds)"
        );
    }

    #[test]
    fn different_profiles_produce_different_navigator_js() {
        let ff = firefox_hooks();
        let ch = chrome_hooks();
        assert_ne!(
            ff.navigator_js(),
            ch.navigator_js(),
            "Firefox and Chrome should produce different navigator JS (different UA/vendor)"
        );
    }

    #[test]
    fn firefox_profile_user_agent_in_js() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("Firefox/128.0"),
            "Firefox navigator JS must contain Firefox user agent string"
        );
    }

    #[test]
    fn chrome_profile_user_agent_in_js() {
        let hooks = chrome_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("Chrome/128.0.0.0"),
            "Chrome navigator JS must contain Chrome user agent string"
        );
    }

    #[test]
    fn firefox_vendor_empty_in_js() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("return \"\"") || js.contains("return ''"),
            "Firefox navigator JS must have empty vendor"
        );
    }

    #[test]
    fn chrome_vendor_google_in_js() {
        let hooks = chrome_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("Google Inc."),
            "Chrome navigator JS must have Google Inc. vendor"
        );
    }

    #[test]
    fn audio_noise_algorithm_matches_rust_constants() {
        let hooks = firefox_hooks();
        let js = hooks.audio_js();
        assert!(
            js.contains("0x517CC1B727220A95n"),
            "Audio JS must use same index-multiply constant as Rust AudioProfile"
        );
        assert!(
            js.contains("0x2545F4914F6CDD1Dn"),
            "Audio JS must use same multiply constant as Rust AudioProfile"
        );
    }

    #[test]
    fn audio_js_amplitude_matches_profile() {
        let audio = AudioProfile::new(42);
        let js = StealthHooks::build_audio_js(&audio);
        assert!(
            js.contains("1e-7") || js.contains("0.0000001"),
            "Audio JS must contain the default noise amplitude 1e-7"
        );
    }

    #[test]
    fn custom_audio_seed_appears_in_js() {
        let audio = AudioProfile::new(7777);
        let js = StealthHooks::build_audio_js(&audio);
        assert!(
            js.contains("7777n"),
            "Audio JS must contain the custom seed as BigInt"
        );
    }

    #[test]
    fn navigator_js_firefox_screen_values() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("1920") && js.contains("1080"),
            "Navigator JS must contain default screen dimensions"
        );
    }

    #[test]
    fn navigator_js_firefox_webgl_vendor() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("Mozilla"),
            "Firefox navigator JS must contain WebGL vendor 'Mozilla'"
        );
    }

    #[test]
    fn navigator_js_chrome_webgl_vendor() {
        let hooks = chrome_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.contains("Google Inc. (NVIDIA)"),
            "Chrome navigator JS must contain WebGL vendor"
        );
    }

    #[test]
    fn hooks_from_profile_custom_screen() {
        let canvas = CanvasNoise::new(42);
        let audio = AudioProfile::new(42);
        let nav = NavigatorProfile::firefox();
        let screen = ScreenProfile::new(800, 600, 2.0);
        let webgl = WebGLProfile::firefox();
        let font = FontConfig::new(42);
        let battery = BatteryConfig::default();
        let timing = TimingConfig::default();
        let clientrects = ClientRectsConfig::default();
        let screen_display = ScreenDisplayConfig::default();
        let plugin = PluginConfig::default();
        let speech = SpeechConfig::default();
        let media_devices = MediaDevicesConfig::default();
        let permissions = PermissionsConfig::default();
        let webgl_context = WebGLContextConfig::default();
        let connection = ConnectionConfig::default();
        let iframe = IframeConfig::default();
        let hooks = StealthHooks::from_profile(
            &canvas,
            &audio,
            &nav,
            &screen,
            &webgl,
            &font,
            &battery,
            WebRtcMode::Default,
            &timing,
            &clientrects,
            &screen_display,
            &plugin,
            &speech,
            &media_devices,
            &permissions,
            &webgl_context,
            &connection,
            &iframe,
        );
        let js = hooks.navigator_js();
        assert!(
            js.contains("800") && js.contains("600"),
            "Custom screen dimensions must appear in navigator JS"
        );
        assert!(
            js.contains("2"),
            "Custom device pixel ratio must appear in navigator JS"
        );
    }

    #[test]
    fn audio_js_is_valid_iife() {
        let hooks = firefox_hooks();
        let js = hooks.audio_js();
        assert!(
            js.starts_with("(function() {") || js.starts_with("(function(){{"),
            "Audio JS must be an IIFE"
        );
        assert!(js.ends_with("})();"), "Audio JS must end with IIFE closure");
    }

    #[test]
    fn navigator_js_is_valid_iife() {
        let hooks = firefox_hooks();
        let js = hooks.navigator_js();
        assert!(
            js.starts_with("(function() {") || js.starts_with("(function(){{"),
            "Navigator JS must be an IIFE"
        );
        assert!(
            js.ends_with("})();"),
            "Navigator JS must end with IIFE closure"
        );
    }

    // ── New dimension tests ──────────────────────────────────────

    #[test]
    fn font_js_contains_fonts_check_override() {
        let hooks = firefox_hooks();
        let js = hooks.font_js();
        assert!(
            js.contains("document.fonts.check"),
            "font JS must override document.fonts.check"
        );
    }

    #[test]
    fn font_js_contains_seed() {
        let hooks = firefox_hooks();
        let js = hooks.font_js();
        assert!(
            js.contains("42n"),
            "font JS must contain the seed as BigInt"
        );
    }

    #[test]
    fn font_js_is_valid_iife() {
        let hooks = firefox_hooks();
        let js = hooks.font_js();
        assert!(
            js.starts_with("(function() {") || js.starts_with("(function(){{"),
            "Font JS must be an IIFE"
        );
        assert!(js.ends_with("})();"), "Font JS must end with IIFE closure");
    }

    #[test]
    fn battery_js_contains_getbattery_override() {
        let hooks = firefox_hooks();
        let js = hooks.battery_js();
        assert!(
            js.contains("navigator.getBattery"),
            "battery JS must override navigator.getBattery"
        );
        assert!(
            js.contains("Promise.resolve"),
            "battery JS must return a resolved Promise"
        );
    }

    #[test]
    fn battery_js_default_values() {
        let hooks = firefox_hooks();
        let js = hooks.battery_js();
        assert!(
            js.contains("charging: true"),
            "battery JS must have charging=true by default"
        );
        assert!(
            js.contains("level: 1"),
            "battery JS must have level=1 by default"
        );
        assert!(
            js.contains("Infinity"),
            "battery JS must have dischargingTime=Infinity by default"
        );
    }

    #[test]
    fn battery_js_is_valid_iife() {
        let hooks = firefox_hooks();
        let js = hooks.battery_js();
        assert!(
            js.starts_with("(function() {") || js.starts_with("(function(){{"),
            "Battery JS must be an IIFE"
        );
        assert!(
            js.ends_with("})();"),
            "Battery JS must end with IIFE closure"
        );
    }

    #[test]
    fn webrtc_js_default_mode_filters_candidates() {
        let hooks = firefox_hooks();
        let js = hooks.webrtc_js();
        assert!(
            js.contains("RTCPeerConnection"),
            "WebRTC JS must reference RTCPeerConnection"
        );
        assert!(
            js.contains("icecandidate"),
            "WebRTC Default mode must filter ICE candidates"
        );
    }

    #[test]
    fn webrtc_js_none_mode_throws_error() {
        let js = StealthHooks::build_webrtc_js(WebRtcMode::None);
        assert!(
            js.contains("NotAllowedError"),
            "WebRTC None mode must throw NotAllowedError"
        );
        assert!(
            js.contains("WebRTC is disabled"),
            "WebRTC None mode must have descriptive error message"
        );
    }

    #[test]
    fn webrtc_js_strict_mode_strips_sdp() {
        let js = StealthHooks::build_webrtc_js(WebRtcMode::Strict);
        assert!(
            js.contains("createOffer"),
            "WebRTC Strict mode must override createOffer"
        );
        assert!(
            js.contains("createAnswer"),
            "WebRTC Strict mode must override createAnswer"
        );
        assert!(
            js.contains("srflx"),
            "WebRTC Strict mode must strip srflx candidates from SDP"
        );
    }

    /// Test aid helper: asserts a hook JS producer emits a well-formed IIFE.
    /// Extracted during the REQ-ARCH-1 duplicate hygiene wave, shared by the
    /// consolidated `webrtc_and_timing_js_are_valid_iife` case (the former
    /// per-hook `*_is_valid_iife` bodies were byte-identical after identifier
    /// normalization).
    fn assert_iife_js(js: &str, label: &str) {
        assert!(
            js.starts_with("(function() {") || js.starts_with("(function(){{"),
            "{label} JS must be an IIFE"
        );
        assert!(js.ends_with("})();"), "{label} JS must end with IIFE closure");
    }

    #[test]
    fn webrtc_and_timing_js_are_valid_iife() {
        let hooks = firefox_hooks();
        assert_iife_js(&hooks.webrtc_js(), "WebRTC");
        assert_iife_js(&hooks.timing_js(), "Timing");
    }

    #[test]
    fn timing_js_contains_performance_now_override() {
        let hooks = firefox_hooks();
        let js = hooks.timing_js();
        assert!(
            js.contains("performance.now"),
            "timing JS must override performance.now"
        );
        assert!(js.contains("Date.now"), "timing JS must override Date.now");
        assert!(
            js.contains("timeStamp"),
            "timing JS must override Event.timeStamp"
        );
    }

    #[test]
    fn timing_js_default_precision() {
        let hooks = firefox_hooks();
        let js = hooks.timing_js();
        assert!(
            js.contains("0.1"),
            "timing JS must contain default precision 0.1ms"
        );
    }

    #[test]
    fn clientrects_js_contains_getboundingclientrect_override() {
        let hooks = firefox_hooks();
        let js = hooks.clientrects_js();
        assert!(
            js.contains("getBoundingClientRect"),
            "clientrects JS must override getBoundingClientRect"
        );
        assert!(
            js.contains("getClientRects"),
            "clientrects JS must override getClientRects"
        );
    }

    #[test]
    fn clientrects_js_contains_noise_delta() {
        let hooks = firefox_hooks();
        let js = hooks.clientrects_js();
        assert!(
            js.contains("0.5"),
            "clientrects JS must contain default noise delta 0.5"
        );
    }

    #[test]
    fn clientrects_js_is_valid_iife() {
        let hooks = firefox_hooks();
        let js = hooks.clientrects_js();
        assert!(
            js.starts_with("(function() {") || js.starts_with("(function(){{"),
            "ClientRects JS must be an IIFE"
        );
        assert!(
            js.ends_with("})();"),
            "ClientRects JS must end with IIFE closure"
        );
    }

    #[test]
    fn screen_display_js_contains_screen_overrides() {
        let hooks = firefox_hooks();
        let js = hooks.screen_display_js();
        assert!(
            js.contains("screen, 'width'"),
            "screen display JS must override screen.width"
        );
        assert!(
            js.contains("screen, 'height'"),
            "screen display JS must override screen.height"
        );
        assert!(
            js.contains("devicePixelRatio"),
            "screen display JS must override devicePixelRatio"
        );
    }

    #[test]
    fn screen_display_js_default_values() {
        let hooks = firefox_hooks();
        let js = hooks.screen_display_js();
        assert!(
            js.contains("1920") && js.contains("1080"),
            "screen display JS must contain default 1920x1080"
        );
        assert!(
            js.contains("24"),
            "screen display JS must contain default colorDepth 24"
        );
    }

    #[test]
    fn screen_display_js_is_valid_iife() {
        let hooks = firefox_hooks();
        let js = hooks.screen_display_js();
        assert!(
            js.starts_with("(function() {") || js.starts_with("(function(){{"),
            "Screen display JS must be an IIFE"
        );
        assert!(
            js.ends_with("})();"),
            "Screen display JS must end with IIFE closure"
        );
    }

    #[test]
    fn different_profiles_produce_different_font_js() {
        let ff = firefox_hooks();
        let ch = chrome_hooks();
        assert_ne!(
            ff.font_js(),
            ch.font_js(),
            "Firefox and Chrome should produce different font JS (different seeds)"
        );
    }

    #[test]
    fn different_profiles_produce_different_clientrects_js() {
        let ff = firefox_hooks();
        let ch = chrome_hooks();
        assert_ne!(
            ff.clientrects_js(),
            ch.clientrects_js(),
            "Firefox and Chrome should produce different clientrects JS (different seeds)"
        );
    }

    // ── e141: chrome.* native-toString facade ──────────────────────

    #[test]
    fn chrome_surface_spoofed_functions_ride_native_carriers() {
        let hooks = chrome_hooks();
        let js = hooks.plugin_js();
        // loadTimes/csi: constructible carriers with name '' (oracle: own
        // [name, prototype, length], `new` yields a plain object).
        for carrier in [
            "baoMakeNative(baoChromeLoadTimes, '', true)",
            "baoMakeNative(baoChromeCsi, '', true)",
        ] {
            assert!(
                js.contains(carrier),
                "loadTimes/csi must ride the constructible native carrier ({})",
                carrier
            );
        }
        // app methods: non-constructible arrow carriers with the method
        // name (oracle: own [name, length], no prototype, `new` throws).
        for method in ["getDetails", "getIsInstalled", "installState", "runningState"] {
            assert!(
                js.contains(&format!("'{}', false)", method)),
                "app.{} must ride the non-constructible native carrier",
                method
            );
        }
        // Code-only view of the section (line comments stripped) for the
        // no-facade-implementation locks.
        let code_only: String = StealthHooks::CHROME_SURFACE_JS
            .lines()
            .map(|l| match l.find("//") {
                Some(idx) => &l[..idx],
                None => l,
            })
            .collect::<Vec<_>>()
            .join("\n");
        // The facade must NOT be an own-property toString patch: real Chrome
        // INHERITS toString on every chrome.* function (oracle round1 —
        // getOwnPropertyDescriptor(f, 'toString') is undefined), and an own
        // toString would also lose the adversarial
        // Function.prototype.toString.call channel.
        assert!(
            !code_only.contains("toString"),
            "the chrome surface must not install any toString facade of its own — \
             the carrier's engine-rendered native form covers every channel"
        );
        // And no global monkey-patch: Function.prototype.toString must stay
        // the pristine engine builtin (a global patch would itself be a
        // detection vector).
        assert!(
            !code_only.contains("Function.prototype.toString"),
            "the chrome surface must not touch Function.prototype.toString"
        );
    }

    /// e141 JS-level oracle-parity lock: evaluates the real
    /// CHROME_SURFACE_JS against a stubbed page environment inside
    /// SpiderMonkey and asserts the facade's observable surface matches the
    /// live-Chrome oracle table (probes under /tmp/e141-tostring-probe,
    /// Chrome 150 headless).
    #[test]
    fn chrome_surface_native_tostring_facade_oracle_parity() {
        use bao_engine::context::JsContext;
        use bao_engine::value::JsValue;

        let mut ctx = JsContext::for_test().expect("JsContext");
        // Stubs for the section's page-realm guards + real-value
        // derivations; the probe reports as one JSON string so a single
        // eval carries the whole oracle-parity table.
        let probe = format!(
            r#"(function() {{
  var window = {{ location: {{ protocol: 'https:' }} }};
  var Plugin = function() {{}};
  var MimeType = function() {{}};
  var performance = {{
    timing: {{ navigationStart: 1759000000000, responseStart: 1759000000100,
               domContentLoadedEventEnd: 1759000000500, loadEventEnd: 1759000000900 }},
    getEntriesByType: function(t) {{ return t === 'paint' ? [{{ name: 'first-paint', startTime: 200 }}] : []; }},
    navigation: {{ type: 1 }},
    now: function() {{ return 1234.5; }}
  }};
  var pumped = [];
  var setTimeout = function(fn, ms) {{ pumped.push(fn); }};
{section}
  var ch = window.chrome;
  var fns = {{
    loadTimes: ch.loadTimes, csi: ch.csi,
    getDetails: ch.app.getDetails, getIsInstalled: ch.app.getIsInstalled,
    installState: ch.app.installState, runningState: ch.app.runningState
  }};
  var R = {{ channels: {{}}, constructible: {{}}, nameShape: {{}} }};
  var leaks = [];
  Object.keys(fns).forEach(function(k) {{
    var f = fns[k];
    var call = Function.prototype.toString.call(f);
    var method = f.toString();
    var coerce = '' + f;
    R.channels[k] = {{
      native: call.indexOf('[native code]') !== -1 && method.indexOf('[native code]') !== -1
        && coerce.indexOf('[native code]') !== -1,
      equal: call === method && method === coerce,
      ownToString: !!Object.getOwnPropertyDescriptor(f, 'toString')
    }};
    if (call.indexOf('bao') !== -1 || method.indexOf('bao') !== -1 || coerce.indexOf('bao') !== -1) {{
      leaks.push(k);
    }}
    R.constructible[k] = {{
      new: (function() {{ try {{ new f(); return 'yes'; }} catch (e) {{ return 'throws'; }} }})(),
      hasPrototype: Object.getOwnPropertyNames(f).indexOf('prototype') !== -1
    }};
    R.nameShape[k] = {{
      name: f.name, length: f.length,
      own: JSON.stringify(Object.getOwnPropertyNames(f))
    }};
  }});
  R.leaks = leaks;
  R.chromeKeys = Object.keys(ch);
  R.appKeys = Object.keys(ch.app);
  R.values = {{
    loadTimes: ch.loadTimes(),
    csi: ch.csi(),
    getDetails: ch.app.getDetails(),
    getIsInstalled: ch.app.getIsInstalled(),
    runningState: ch.app.runningState()
  }};
  ch.app.installState(function(s) {{ R.installStateCb = s; }});
  R.installStateAsync = pumped.length === 1;
  if (pumped.length) {{ pumped[0](); }}
  R.globalUntouched = {{
    plainSrcVisible: Function.prototype.toString.call(function marker() {{ return 2; }})
      .indexOf('return 2') !== -1,
    selfNative: Function.prototype.toString.call(Function.prototype.toString)
      .indexOf('[native code]') !== -1
  }};
  return JSON.stringify(R);
}})();"#,
            section = StealthHooks::CHROME_SURFACE_JS.trim()
        );
        let raw = match ctx.eval(&probe, "<e141-chrome-facade>") {
            Ok(JsValue::String(s)) => s,
            other => panic!("probe eval failed: {:?}", other),
        };
        JsContext::shutdown_thread_sm();

        let r: serde_json::Value = serde_json::from_str(&raw).expect("probe JSON");
        // Three channels, every surface function: engine-rendered native
        // form, mutually equal, no own toString, no 'bao' identifier leak.
        for k in [
            "loadTimes",
            "csi",
            "getDetails",
            "getIsInstalled",
            "installState",
            "runningState",
        ] {
            let c = &r["channels"][k];
            assert_eq!(
                c["native"].as_bool(),
                Some(true),
                "{}: every toString channel must render the [native code] form",
                k
            );
            assert_eq!(
                c["equal"].as_bool(),
                Some(true),
                "{}: F.p.toString.call / f.toString() / ''+f must be mutually equal",
                k
            );
            assert_eq!(
                c["ownToString"].as_bool(),
                Some(false),
                "{}: toString must stay inherited (real Chrome has no own toString)",
                k
            );
        }
        assert_eq!(
            r["leaks"].as_array().map(Vec::as_slice),
            Some(&[] as &[serde_json::Value]),
            "no surface function may leak the bao* identifier through any channel"
        );
        // Oracle constructibility table: loadTimes/csi constructible with a
        // prototype own prop; the four app methods non-constructible
        // without one.
        for k in ["loadTimes", "csi"] {
            assert_eq!(
                r["constructible"][k]["new"].as_str(),
                Some("yes"),
                "{}: real Chrome's `new` yields a plain object (oracle round2)",
                k
            );
            assert_eq!(
                r["constructible"][k]["hasPrototype"].as_bool(),
                Some(true),
                "{}: own props carry [name, prototype, length] (oracle)",
                k
            );
            assert_eq!(
                r["nameShape"][k]["name"].as_str(),
                Some(""),
                "{}: real name is ''",
                k
            );
            assert_eq!(
                r["nameShape"][k]["length"].as_u64(),
                Some(0),
                "{}: real length is 0",
                k
            );
        }
        for (k, name) in [
            ("getDetails", "getDetails"),
            ("getIsInstalled", "getIsInstalled"),
            ("installState", "installState"),
            ("runningState", "runningState"),
        ] {
            assert_eq!(
                r["constructible"][k]["new"].as_str(),
                Some("throws"),
                "{}: real app methods are not constructors (oracle round2)",
                k
            );
            assert_eq!(
                r["constructible"][k]["hasPrototype"].as_bool(),
                Some(false),
                "{}: own props are [name, length] only (oracle round3)",
                k
            );
            assert_eq!(
                r["nameShape"][k]["name"].as_str(),
                Some(name),
                "{}: real name",
                k
            );
            assert_eq!(
                r["nameShape"][k]["length"].as_u64(),
                Some(0),
                "{}: real length is 0",
                k
            );
        }
        // Member sets keep the e135 shape (order included).
        assert_eq!(
            r["chromeKeys"],
            serde_json::json!(["loadTimes", "csi", "app"]),
            "chrome own-key order must stay loadTimes, csi, app"
        );
        assert_eq!(
            r["appKeys"],
            serde_json::json!(["isInstalled", "getDetails", "getIsInstalled", "installState",
                               "runningState", "InstallState", "RunningState"]),
            "app member set must stay the e135 shape"
        );
        // Values are still the e135 real-value derivations.
        assert_eq!(
            r["values"]["loadTimes"]["requestTime"].as_f64(),
            Some(1759000000.0),
            "requestTime = navigationStart/1000"
        );
        assert_eq!(
            r["values"]["loadTimes"]["navigationType"], "Reload",
            "navigationType follows performance.navigation.type"
        );
        let csi = &r["values"]["csi"];
        assert_eq!(csi["startE"].as_u64(), Some(1759000000000u64));
        assert_eq!(csi["onloadT"].as_u64(), Some(1759000000900u64));
        assert_eq!(csi["tran"].as_u64(), Some(15));
        assert_eq!(r["values"]["getDetails"], serde_json::Value::Null);
        assert_eq!(
            r["values"]["getIsInstalled"].as_bool(),
            Some(false),
            "getIsInstalled() must return false (vanilla page)"
        );
        assert_eq!(
            r["values"]["runningState"].as_str(),
            Some("cannot_run"),
            "runningState() must return 'cannot_run' (vanilla page)"
        );
        assert_eq!(
            r["installStateAsync"].as_bool(),
            Some(true),
            "installState must queue its callback asynchronously"
        );
        assert_eq!(
            r["installStateCb"].as_str(),
            Some("not_installed"),
            "installState callback fires with 'not_installed'"
        );
        // The facade must not have touched the global surface.
        assert_eq!(
            r["globalUntouched"]["plainSrcVisible"].as_bool(),
            Some(true),
            "plain functions must still render their source (no global toString patch)"
        );
        assert_eq!(
            r["globalUntouched"]["selfNative"].as_bool(),
            Some(true),
            "Function.prototype.toString itself must stay the pristine native"
        );
    }
}