bun_runtime 0.1.2

Bao runtime integration — JS engine + Bun API + event loop
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
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
// @trace REQ-ENG-007 [entity:TlsProfile] [api:GET /api/node-compat]
use ::std::cell::{Cell, RefCell};
use ::std::collections::HashMap;
use ::std::net::{TcpListener, TcpStream, ToSocketAddrs};
use ::std::os::fd::AsRawFd;
use ::std::ptr::NonNull;
use ::std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use ::std::sync::{Arc, Mutex, OnceLock};
use ::std::time::{Duration, Instant};
use bun_core::ZBox;

use bao_boringssl_bridge::{
    KeyFormat, PeerCertInfo, SslClientHello, TlsClient, TlsConnection, TlsError, TlsServer,
    TlsState, pem_parse_certs, pem_parse_key, ssl_servername, SSL_SELECT_CERT_ERROR,
    SSL_SELECT_CERT_RETRY, SSL_SELECT_CERT_SUCCESS,
};
use bao_engine::context::RawValueRootGuard;
use bun_boringssl_sys::boringssl::*;
use mozjs::jsapi::*;
use mozjs::jsval::{DoubleValue, Int32Value, JSVal, ObjectValue, StringValue, UndefinedValue};
use mozjs::realm::AutoRealm;
use mozjs::rooted;
use mozjs::rust::wrappers2 as w2;

use crate::node_events::{
    ee_emit, ee_off, ee_on, ee_once, ee_prepend, ee_prepend_once, ee_remove_all,
};
use crate::require::cache_builtin;

// ─── SecureContextState — Rust-native TLS credential storage ──────────
//
// Stores parsed TLS credentials outside the JS heap to prevent
// sensitive key/cert data from being accessible via JS reflection.
// Stored as a SpiderMonkey PrivateValue on the SecureContext JS object.
//
// All certificate/key data is stored as DER bytes (Vec<u8>) or PEM strings.
// PEM strings are kept for TlsServer::new() which accepts PEM directly.

struct SecureContextState {
    key_der: Option<(KeyFormat, Vec<u8>)>,
    cert_ders: Vec<Vec<u8>>,   // DER-encoded certificates
    ca_certs: Vec<Vec<u8>>,    // DER-encoded CA certificates
    pem_certs: Option<String>, // PEM cert string for TlsServer::new()
    pem_key: Option<String>,   // PEM key string for TlsServer::new()
    /// ALPN protocols list — wire-format bytes (length-prefixed: 0x02h2\x08http/1.1)
    alpn_protos: Option<Vec<u8>>,
    /// Session data for resumption — serialized SSL_SESSION bytes
    session_data: Option<Vec<u8>>,
}

impl SecureContextState {
    fn new() -> Self {
        Self {
            key_der: None,
            cert_ders: Vec::new(),
            ca_certs: Vec::new(),
            pem_certs: None,
            pem_key: None,
            alpn_protos: None,
            session_data: None,
        }
    }
}

/// Check if a JSVal is a PrivateValue by testing is_double() with zero high bits.
/// SpiderMonkey encodes private values as doubles; this guard rejects non-private doubles.
#[inline]
fn val_is_private(v: &JSVal) -> bool {
    v.is_double() && (v.asBits_ & 0xFFFF000000000000) == 0
}

/// Store a `Box<SecureContextState>` as a private value on a JS object.
/// Creates the state if it doesn't exist yet.
unsafe fn sc_state_ensure(cx: *mut JSContext, obj: *mut JSObject) -> *mut SecureContextState {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut slot_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_scState".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut slot_val,
        },
    );

    if val_is_private(&slot_val) {
        let ptr = slot_val.to_private() as *mut SecureContextState;
        if !ptr.is_null() {
            return ptr;
        }
    }

    // Create new state
    let state = Box::new(SecureContextState::new());
    let ptr = Box::into_raw(state) as *const core::ffi::c_void;
    let pv = mozjs::jsval::PrivateValue(ptr);
    rooted!(&in(cx_ref) let pv_h = pv);
    JS_DefineProperty(
        cx,
        obj_root.handle().into(),
        c"_scState".as_ptr(),
        pv_h.handle().into(),
        0,
    );
    ptr as *mut SecureContextState
}

/// Parse PEM key string and store in SecureContextState.
unsafe fn sc_state_set_key(cx: *mut JSContext, obj: *mut JSObject, pem: &str) -> bool {
    let key = pem_parse_key(pem);
    if let Some(k) = key {
        let state = sc_state_ensure(cx, obj);
        (*state).key_der = Some(k);
        (*state).pem_key = Some(pem.to_string());
        true
    } else {
        false
    }
}

/// Parse PEM cert string and store in SecureContextState.
unsafe fn sc_state_set_cert(cx: *mut JSContext, obj: *mut JSObject, pem: &str) -> bool {
    let ders = pem_parse_certs(pem);
    if ders.is_empty() {
        return false;
    }
    let state = sc_state_ensure(cx, obj);
    (*state).cert_ders = ders;
    (*state).pem_certs = Some(pem.to_string());
    true
}

/// Parse PEM CA cert string and add to CA certificates in SecureContextState.
unsafe fn sc_state_add_ca(cx: *mut JSContext, obj: *mut JSObject, pem: &str) -> bool {
    let ders = pem_parse_certs(pem);
    if ders.is_empty() {
        return false;
    }
    let state = sc_state_ensure(cx, obj);
    (*state).ca_certs.extend(ders);
    true
}

/// Set ALPN protocols on the SecureContextState.
/// Accepts a JS array of protocol name strings, builds wire-format bytes.
unsafe fn sc_state_set_alpn_protos(
    cx: *mut JSContext,
    obj: *mut JSObject,
    protos_val: JSVal,
) -> bool {
    if !protos_val.is_object() {
        return false;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let arr_obj = protos_val.to_object());

    // Build wire-format ALPN list: each entry is length-prefixed
    let mut wire = Vec::new();
    let mut i: u32 = 0;
    loop {
        let mut elem = UndefinedValue();
        JS_GetElement(
            cx,
            arr_obj.handle().into(),
            i,
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut elem,
            },
        );
        if elem.is_undefined() {
            break;
        }
        if elem.is_string() {
            let proto = crate::js_to_rust_string(cx, elem);
            if proto.len() > 255 {
                continue; // ALPN protocol name too long
            }
            wire.push(proto.len() as u8);
            wire.extend_from_slice(proto.as_bytes());
        }
        i += 1;
    }

    if wire.is_empty() {
        return false;
    }

    let state = sc_state_ensure(cx, obj);
    (*state).alpn_protos = Some(wire);
    true
}

/// Set session data for resumption.
unsafe fn sc_state_set_session(
    cx: *mut JSContext,
    obj: *mut JSObject,
    session_bytes: &[u8],
) -> bool {
    let state = sc_state_ensure(cx, obj);
    (*state).session_data = Some(session_bytes.to_vec());
    true
}

/// Drop the SecureContextState stored on a JS object (for cleanup).
unsafe fn sc_state_drop(cx: *mut JSContext, obj: *mut JSObject) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut slot_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_scState".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut slot_val,
        },
    );

    if val_is_private(&slot_val) {
        let ptr = slot_val.to_private() as *mut SecureContextState;
        if !ptr.is_null() {
            let _ = Box::from_raw(ptr);
        }
        rooted!(&in(cx_ref) let undef = UndefinedValue());
        JS_DefineProperty(
            cx,
            obj_root.handle().into(),
            c"_scState".as_ptr(),
            undef.handle().into(),
            0,
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════
// TLS server driver — event-driven accept + handshake + SNI dispatch
// ═══════════════════════════════════════════════════════════════════════
//
// Root-cure for the silently-ignored `SNICallback` contract (node_tls.rs
// parsed it into `_sniCallback` and nothing ever called it) AND for the
// missing server data path (`listen()` previously only configured a
// `TlsServer` and stored `_listenPort`; no TCP listener was ever bound, no
// connection ever served).
//
// Architecture (mirrors the FetchTasklet / HTTPThread split):
//
//   JS thread                                  TLS driver thread (one per process)
//   ─────────────────                          ─────────────────────────────────
//   tls.createServer({key, cert,               poll() on [wake pipe, listeners,
//     SNICallback})                              conns]
//   listen(port) ── AddListener cmd ────────▶  accept → TlsConnection (base CTX)
//   ┌ ConcurrentTask (AnyTaskWithExtraContext)   SSL_do_handshake
//   │  (MiniEventLoop auto-wake)                 └─ select-certificate cb fires:
//   │                                              no JS SNICallback → SUCCESS
//   │                                               (default branch: static cert)
//   │                                              servername + SNICallback:
//   │   SniRequest event ◀── push event ──         push SniRequest, return RETRY
//   │   call SNICallback(servername, cb)           (handshake suspends:
//   │   cb(err|null, ctx|{key,cert})                TlsState::PendingCertificate)
//   │      │                                        conn parked until deadline
//   │      └─ sni_result + wake ──────────────▶   re-drive handshake → cb again:
//   │                                              build CTX from {cert,key},
//   │   SecureConnection/Data/End/Close ◀──        SSL_set_SSL_CTX → SUCCESS
//   │   events: build TLSSocket, emit
//   └ socket.write() → pending_writes queue ─▶   drained by driver thread only
//
// ssl_in_use (upstream 0825a8b3f) equivalence: in upstream's C stack the
// ALPN/SNI selection callbacks run JS *inside* SSL_read/SSL_do_handshake,
// so a socket.write() from the callback re-entered BoringSSL on the same
// SSL mid-handshake — the ssl_in_use protocol parks such writes and the
// parked-write machinery flushes them once the handshake completes, BEFORE
// anything written from `secureConnection`. In this Rust stack the
// re-entrancy is impossible by construction: the SSL object is only ever
// touched by the single driver thread (JS writes append to a
// Mutex-protected queue, never call SSL_write), and when the JS callback
// runs the driver has already returned from BoringSSL (the connection is
// parked in PendingCertificate, no BoringSSL call on the stack). The
// park-then-flush ORDERING semantics are preserved exactly: parked writes
// (including any issued from inside SNICallback) are flushed to the wire
// before the `secureConnection` event is dispatched.
//
// Node SNICallback semantics: Node allows the callback to resolve
// asynchronously; internally it defers the handshake. BoringSSL's
// `ssl_select_cert_retry` is the native equivalent used here, so both sync
// and async SNICallback invocations work — the handshake simply suspends
// until `cb` fires. A `cb` that never fires fails closed at the SNI
// deadline (fatal alert + `tlsClientError`), never silently.

/// SNI resolution deadline. A SNICallback that never calls back fails the
/// handshake (fatal alert + explicit `tlsClientError`) instead of parking
/// the connection forever.
const SNI_DEADLINE: Duration = Duration::from_secs(120);

/// Driver → JS-thread events, drained by the ConcurrentTask on the JS thread.
enum TlsEvent {
    /// TCP accepted; the JS TLSSocket object must be created and
    /// `connection` emitted (Node tls.Server inherits net.Server's
    /// `connection` event; in Bao the payload is the TLS socket object,
    /// matching Bun's observable behavior where writing it from inside the
    /// SNI/ALPN selection delivers TLS application data).
    Connection {
        conn_id: u64,
        shared: Arc<ConnShared>,
    },
    /// ClientHello carried a servername and a JS SNICallback is registered.
    SniRequest { conn_id: u64, servername: String },
    /// Handshake completed on `conn_id`. `info` is the full session
    /// snapshot captured while the driver still owns the SSL object — the
    /// JS thread never touches the SSL, so everything the TLSSocket surface
    /// reports afterwards rides on this event.
    SecureConnection { conn_id: u64, info: TlsSessionInfo },
    /// Decrypted application data.
    Data { conn_id: u64, bytes: Vec<u8> },
    /// Peer sent close_notify (clean TLS EOF).
    End { conn_id: u64 },
    /// Connection fully closed (after End, error, end() or destroy()).
    Close { conn_id: u64 },
    /// Handshake/protocol failure. Emitted as `tlsClientError`.
    ClientError { conn_id: u64, message: String },
    /// Server fully torn down (driver removed it): unroot JS refs, emit
    /// `close`, invoke the stored close callback.
    ServerClosed,
}

/// Handshake-completion snapshot (driver → JS thread): everything the JS
/// TLSSocket surface reports after the handshake, captured on the driver
/// thread while it still owns the SSL object. Plain data (Send) — no SSL
/// pointers cross threads.
struct TlsSessionInfo {
    servername: Option<String>,
    alpn: Option<Vec<u8>>,
    /// SSL_get_version (e.g. "TLSv1.3").
    protocol: Option<String>,
    /// SSL_CIPHER_get_name.
    cipher_name: Option<String>,
    /// SSL_CIPHER_get_version (BoringSSL: "TLSv1/SSLv3").
    cipher_version: Option<String>,
    /// Parsed peer leaf certificate (None when the peer sent none).
    peer_cert: Option<PeerCertInfo>,
}

/// Per-connection cross-thread state. The Mutex/atomic fields are the ONLY
/// shared surface between the JS thread (write/end/destroy/SNI resolution)
/// and the driver thread (owner of the SSL object).
struct ConnShared {
    /// JS → driver: plaintext to encrypt+send. Parked (not SSL_write'n)
    /// until the driver drains it — the ssl_in_use park-and-flush semantics.
    pending_writes: Mutex<Vec<Vec<u8>>>,
    /// JS → driver: graceful end — flush parked writes, send close_notify.
    want_end: AtomicBool,
    /// JS → driver: immediate destroy.
    want_destroy: AtomicBool,
    /// Driver → JS: connection closed; further writes are rejected.
    closed: AtomicBool,
    /// JS → driver: SNICallback resolution. `Ok((cert_pem, key_pem))` or
    /// `Err(message)` (callback error / missing credentials).
    sni_result: Mutex<Option<::std::result::Result<(String, String), String>>>,
}

impl ConnShared {
    fn new() -> Self {
        Self {
            pending_writes: Mutex::new(Vec::new()),
            want_end: AtomicBool::new(false),
            want_destroy: AtomicBool::new(false),
            closed: AtomicBool::new(false),
            sni_result: Mutex::new(None),
        }
    }
}

/// Which JS surface a `ServerShared` feeds. The driver treats both kinds
/// identically (a conn to drive + events to queue); only the JS-thread
/// tasklet branches on it.
enum ServerKind {
    /// `tls.createServer().listen()` — events are emitted on the server
    /// object; `server_obj_root` holds the server object.
    Listener,
    /// `tls.connect()` client connection — `server_obj_root` holds the
    /// pending Promise: SecureConnection resolves it with the socket,
    /// ClientError (pre-socket) rejects it.
    ClientConnect,
}

/// Server-wide cross-thread state. Fields marked JS-thread-only are never
/// touched from the driver thread (enforced by contract, same as
/// `PendingFetch` in fetch_async.rs).
struct ServerShared {
    server_id: u64,
    kind: ServerKind,
    /// JS-thread-only: context that owns the server object / promise.
    cx: *mut JSContext,
    /// JS-thread-only: heap-rooted server object (Listener) or pending
    /// Promise (ClientConnect). `RawValueRootGuard` pins the slot at a
    /// stable heap address and unroots on drop (liveness-guarded).
    server_obj_root: Option<RawValueRootGuard>,
    /// JS-thread-only: heap-rooted SNICallback function (present iff
    /// SNICallback was provided).
    sni_fn_root: Option<RawValueRootGuard>,
    /// JS-thread-only (ClientConnect): the conn's cross-thread handle — the
    /// SecureConnection tasklet needs it to build the JsConn entry.
    client_conn: Option<Arc<ConnShared>>,
    /// JS-thread-only: pointer to the JS thread's MiniEventLoop (captured
    /// at listen() time, valid for the thread's lifetime).
    mini_loop_ptr: *const bun_event_loop::MiniEventLoop::MiniEventLoop<'static>,
    /// ConcurrentTask carrier for the JS-thread event drain. Re-initialized
    /// before each enqueue (the task is dequeued before it runs).
    concurrent_task: bun_event_loop::AnyTaskWithExtraContext::AnyTaskWithExtraContext,
    /// Guards against duplicate ConcurrentTask scheduling (compare_exchange
    /// false→true before enqueue; reset at tasklet entry).
    task_scheduled: AtomicBool,
    /// Driver → JS event queue.
    events: Mutex<Vec<TlsEvent>>,
    /// close() requested; driver removes the listener and pushes
    /// `ServerClosed` as the final event.
    closing: AtomicBool,
    /// Cache of SNI-resolved SSL_CTXs, keyed by (cert_pem, key_pem). Driver
    /// thread only (inside the select-certificate callback), Mutex for
    /// cross-thread Sync. `SSL_set_SSL_CTX` up-refs the ctx, so eviction is
    /// safe while live SSLs hold references.
    sni_ctx_cache: Mutex<HashMap<(String, String), Arc<TlsServer>>>,
    /// Leaked wire-format ALPN list (re-registered on SNI-resolved CTXs —
    /// `SSL_set_SSL_CTX` swaps the whole ctx, so the ALPN select callback
    /// must be installed on the replacement too).
    alpn_wire: Option<&'static [u8]>,
}

// SAFETY: `cx` / `*_root` / `mini_loop_ptr` / `concurrent_task` are only
// dereferenced on the JS thread that created them (identical contract to
// `PendingFetch` in fetch_async.rs); the driver thread only touches the
// Mutex/atomic fields and `sni_ctx_cache` (whose contents are Send+Sync).
unsafe impl Send for ServerShared {}
unsafe impl Sync for ServerShared {}

/// Driver-thread-side per-connection state. Owned exclusively by the driver
/// thread — this is what makes BoringSSL re-entrancy structurally
/// impossible: no other thread ever calls into the SSL object.
struct DriverConn {
    conn_id: u64,
    stream: TcpStream,
    tls: TlsConnection,
    shared: Arc<ConnShared>,
    server: Arc<ServerShared>,
    /// Handshake state mirror of `TlsState` (driver-side transitions).
    parked_for_sni: bool,
    sni_requested: bool,
    sni_servername: Option<String>,
    sni_deadline: Option<Instant>,
    /// Outgoing ciphertext not yet written to the socket.
    out_buf: Vec<u8>,
    /// `secureConnection` event pushed (first Active observation).
    secure_reported: bool,
    /// Graceful shutdown requested: flush, send close_notify, close.
    finishing: bool,
    /// close_notify queued (out_buf may still hold it).
    close_notify_sent: bool,
}

/// Driver-thread-side per-server state.
struct DriverServer {
    server_id: u64,
    listener: TcpListener,
    base: TlsServer,
    shared: Arc<ServerShared>,
}

/// Commands JS thread → driver thread.
enum DriverCmd {
    AddListener(TcpListener, Arc<ServerShared>, TlsServer),
    /// A `tls.connect()` client connection whose TCP stream a connect
    /// worker just established — the driver owns the handshake from here
    /// (same exclusive-ownership transfer as `AddListener`'s `TlsServer`).
    /// `conn_shared` is the JS-thread-visible cross-thread handle (the JS
    /// socket's write/end/destroy need it).
    AddClientConn(u64, TcpStream, Arc<ServerShared>, Arc<ConnShared>, TlsConnection),
    RemoveServer(u64),
}

struct DriverHandle {
    /// Write end of the wake pipe; a byte written here breaks the driver's
    /// poll() so it picks up commands / queued writes promptly.
    wake_fd: i32,
    cmds: Mutex<Vec<DriverCmd>>,
}

static DRIVER: OnceLock<DriverHandle> = OnceLock::new();
/// Serializes driver bootstrap across concurrent listen() calls (the
/// OnceLock alone cannot distinguish "not yet initialized" from "init
/// failed"; the lock makes creation single-shot).
static DRIVER_INIT: Mutex<()> = Mutex::new(());
static NEXT_TLS_ID: AtomicU64 = AtomicU64::new(1);

// The connection the driver thread is currently driving a BoringSSL call
// on. Set around `TlsConnection::process()` so the select-certificate
// callback (which fires inside `SSL_do_handshake`) can find its conn.
thread_local! {
    static DRIVER_CURRENT_CONN: Cell<*mut DriverConn> = const { Cell::new(::std::ptr::null_mut()) };
}

// JS-thread registry: server_id → shared handle. Keeps the `ServerShared`
// (and its heap roots) alive until the `ServerClosed` tasklet unroots; the
// driver drops its own Arc when it removes the server.
thread_local! {
    static TLS_SERVER_REGISTRY: RefCell<HashMap<u64, Arc<ServerShared>>> =
        RefCell::new(HashMap::new());
}

/// JS-thread registry: conn_id → per-conn JS handle (rooted socket object +
/// the cross-thread ConnShared). Populated on `Connection` events, removed
/// on `Close` events.
struct JsConn {
    shared: Arc<ConnShared>,
    /// Heap-rooted socket object (RAII: unrooted when the entry is removed
    /// on the Close event).
    socket_root: Option<RawValueRootGuard>,
}

thread_local! {
    static TLS_CONNS: RefCell<HashMap<u64, JsConn>> = RefCell::new(HashMap::new());
}

fn tls_driver_wake() {
    if let Some(h) = DRIVER.get() {
        let byte = [1u8];
        // SAFETY: wake_fd is a live pipe write end (owned by the OnceLock).
        unsafe {
            let _ = libc::write(h.wake_fd, byte.as_ptr().cast::<core::ffi::c_void>(), 1);
        }
    }
}

/// Liveness probe for the BCE-007 unified registry (JS thread): true while
/// any TLS server is listening or any client connect share is live. Entries
/// leave the registry on ServerClosed / client Close, so an idle-closed TLS
/// state releases the event loop exactly like a closed HTTP server.
fn tls_liveness_probe() -> bool {
    TLS_SERVER_REGISTRY.with(|r| !r.borrow().is_empty())
}

/// Ensure the driver thread + wake pipe exist. `None` only on resource
/// exhaustion (pipe/thread creation failure) — callers fail closed.
fn tls_driver_acquire() -> Option<&'static DriverHandle> {
    if let Some(h) = DRIVER.get() {
        return Some(h);
    }
    // Serialize bootstrap: a concurrent winner installs the handle; losers
    // re-check under the lock and reuse it (no orphaned pipes/threads).
    let _init_guard = DRIVER_INIT.lock().unwrap();
    if let Some(h) = DRIVER.get() {
        return Some(h);
    }
    let mut fds = [-1i32; 2];
    // SAFETY: fds is a valid 2-int out-buffer for pipe(2).
    if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
        return None;
    }
    // The wake-drain loop reads until EAGAIN — the READ end must be
    // non-blocking or the drain would block (and deadlock the driver) once
    // the pipe empties. The write end stays blocking (a 64K pipe buffer
    // never fills with 1-byte wakes).
    // SAFETY: fds[0] is a live pipe read end; F_SETFL only adds flags.
    unsafe {
        let flags = libc::fcntl(fds[0], libc::F_GETFL);
        if flags < 0
            || libc::fcntl(fds[0], libc::F_SETFL, flags | libc::O_NONBLOCK) < 0
        {
            libc::close(fds[0]);
            libc::close(fds[1]);
            return None;
        }
    }
    let handle = DriverHandle {
        wake_fd: fds[1],
        cmds: Mutex::new(Vec::new()),
    };
    // SAFETY: fds[0] is the read end; the driver thread owns it exclusively.
    let spawned = ::std::thread::Builder::new()
        .name("bao-tls-driver".into())
        .spawn(move || tls_driver_main(fds[0]));
    match spawned {
        Ok(_) => {
            let _ = DRIVER.set(handle);
            DRIVER.get()
        }
        Err(_) => {
            // SAFETY: both fds were just created by pipe(2) and are unused.
            unsafe {
                libc::close(fds[0]);
                libc::close(fds[1]);
            }
            None
        }
    }
}

fn tls_push_event(shared: &Arc<ServerShared>, ev: TlsEvent) {
    shared.events.lock().unwrap().push(ev);
    tls_schedule_tasklet(shared);
}

/// Schedule the JS-thread event-drain tasklet (idempotent: the
/// compare_exchange admits exactly one enqueue per in-flight dispatch).
fn tls_schedule_tasklet(shared: &Arc<ServerShared>) {
    if shared
        .task_scheduled
        .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
        .is_err()
    {
        return;
    }
    let loop_ptr = shared.mini_loop_ptr;
    if loop_ptr.is_null() {
        // No JS event loop captured (listen() raced teardown). Reset so a
        // later attempt can retry; events remain queued.
        shared.task_scheduled.store(false, Ordering::Release);
        return;
    }
    // BCE-20260814-TLS-DRIVER-UAF: enqueue through the process-global
    // liveness registry instead of a raw `&mut *loop_ptr` +
    // `enqueue_task_concurrent`. The MiniEventLoop box is leaked, but its
    // uws loop is freed when the owning JS thread exits (bao_uloop's
    // thread-local BaoLoopState::drop) — this driver thread is a
    // process-lifetime singleton, so an event landing after that exit woke
    // freed loop memory (SIGSEGV in us_poll_fd, ~50% of
    // tls_sni_server_tests runs under load). The registry handshake makes
    // enqueue+wakeup mutually exclusive with the loop free.
    //
    // SAFETY: loop_ptr was captured on the JS thread via with_event_loop
    // (leaked allocation, stable memory); shared is kept alive by the JS
    // registry Arc until the ServerClosed tasklet removes it.
    unsafe {
        let shared_ptr = Arc::as_ptr(shared) as *mut ServerShared;
        let task_ptr = core::ptr::addr_of_mut!((*shared_ptr).concurrent_task);
        (*task_ptr).from(shared_ptr, tls_event_tasklet_shim);
        let mini = loop_ptr as *mut bun_event_loop::MiniEventLoop::MiniEventLoop<'static>;
        if !bun_event_loop::ConcurrentWakeup::enqueue_task_concurrent_cross_thread(
            mini,
            NonNull::new_unchecked(task_ptr),
        ) {
            // Owning JS thread exited: identical handling to the uncaptured
            // case — reset so a later attempt can retry; events remain
            // queued (nothing drains them, same as before the fix).
            shared.task_scheduled.store(false, Ordering::Release);
        }
    }
}

// ─── select-certificate callback (driver thread, inside BoringSSL) ─────

/// BoringSSL select-certificate callback: the SNICallback injection point.
/// Runs on the driver thread inside `SSL_do_handshake`.
unsafe extern "C" fn tls_select_cert_cb(client_hello: *const SslClientHello) -> core::ffi::c_int {
    let ssl = unsafe { (*client_hello).ssl };
    let conn_ptr = DRIVER_CURRENT_CONN.with(|c| c.get());
    if conn_ptr.is_null() {
        // No connection under drive — structurally unreachable (the callback
        // only fires inside the driver's process() window). Fail closed.
        log::error!("[tls] select-certificate callback without an active connection");
        return SSL_SELECT_CERT_ERROR;
    }
    // SAFETY: DRIVER_CURRENT_CONN is set around process() on this thread.
    let conn = unsafe { &mut *conn_ptr };

    if !conn.sni_requested {
        match ssl_servername(ssl) {
            Some(servername) => {
                conn.sni_requested = true;
                conn.sni_servername = Some(servername.clone());
                conn.sni_deadline = Some(Instant::now() + SNI_DEADLINE);
                tls_push_event(
                    &conn.server,
                    TlsEvent::SniRequest {
                        conn_id: conn.conn_id,
                        servername,
                    },
                );
                // Handshake suspends (TlsState::PendingCertificate) until
                // the JS SNICallback resolves via its `cb`.
                SSL_SELECT_CERT_RETRY
            }
            None => {
                // No SNI extension → default branch: static certificate.
                SSL_SELECT_CERT_SUCCESS
            }
        }
    } else {
        // Re-invocation after retry: the resolution must be in the slot
        // (the driver only re-drives the handshake once it is present).
        let result = conn.shared.sni_result.lock().unwrap().take();
        match result {
            Some(Ok((cert_pem, key_pem))) => match tls_sni_ctx_for(&conn.server, &cert_pem, &key_pem) {
                Ok(ctx) => {
                    // SAFETY: ctx is a live SSL_CTX* from a cached TlsServer
                    // (Arc keeps it alive; SSL_set_SSL_CTX up-refs it).
                    if unsafe { conn.tls.switch_ssl_ctx(ctx) } {
                        SSL_SELECT_CERT_SUCCESS
                    } else {
                        log::error!("[tls] SSL_set_SSL_CTX failed for SNI resolution");
                        tls_push_event(
                            &conn.server,
                            TlsEvent::ClientError {
                                conn_id: conn.conn_id,
                                message: "SNICallback: SSL_set_SSL_CTX failed".to_string(),
                            },
                        );
                        SSL_SELECT_CERT_ERROR
                    }
                }
                Err(msg) => {
                    log::error!("[tls] SNICallback credentials rejected: {}", msg);
                    tls_push_event(
                        &conn.server,
                        TlsEvent::ClientError {
                            conn_id: conn.conn_id,
                            message: format!("SNICallback credentials rejected: {}", msg),
                        },
                    );
                    SSL_SELECT_CERT_ERROR
                }
            },
            Some(Err(msg)) => {
                // Explicit dispatch failure → fail the handshake loudly,
                // surfacing the callback's own error to tlsClientError.
                log::error!("[tls] SNICallback returned an error: {}", msg);
                tls_push_event(
                    &conn.server,
                    TlsEvent::ClientError {
                        conn_id: conn.conn_id,
                        message: format!("SNICallback error: {}", msg),
                    },
                );
                SSL_SELECT_CERT_ERROR
            }
            None => SSL_SELECT_CERT_RETRY,
        }
    }
}

/// Build (or fetch from cache) the SSL_CTX for an SNI-resolved credential
/// pair. Driver thread only.
fn tls_sni_ctx_for(
    shared: &Arc<ServerShared>,
    cert_pem: &str,
    key_pem: &str,
) -> ::std::result::Result<*mut SSL_CTX, String> {
    let key = (cert_pem.to_string(), key_pem.to_string());
    let mut cache = shared.sni_ctx_cache.lock().unwrap();
    if let Some(existing) = cache.get(&key) {
        return Ok(existing.ctx());
    }
    let server = TlsServer::new(cert_pem, key_pem).map_err(|e| e.to_string())?;
    // The replacement ctx must serve the same ALPN selection as the base
    // (SSL_set_SSL_CTX swaps the whole ctx).
    if let Some(wire) = shared.alpn_wire {
        // SAFETY: wire is a leaked 'static slice; registration matches the
        // base CTX setup in tls_server_listen.
        unsafe {
            SSL_CTX_set_alpn_select_cb(
                server.ctx(),
                Some(alpn_select_callback),
                wire.as_ptr() as *mut core::ffi::c_void,
            );
        }
    }
    let ctx = server.ctx();
    cache.insert(key, Arc::new(server));
    Ok(ctx)
}

// ─── driver main loop ───────────────────────────────────────────────────

fn tls_driver_main(wake_read_fd: i32) {
    let mut servers: HashMap<u64, DriverServer> = HashMap::new();
    let mut conns: HashMap<u64, DriverConn> = HashMap::new();
    let mut remove_queue: Vec<u64> = Vec::new();

    // The spawner installs the DRIVER handle right after spawning this
    // thread; wait briefly for it instead of racing to a spurious exit.
    let bootstrap_deadline = Instant::now() + Duration::from_secs(5);
    let handle = loop {
        match DRIVER.get() {
            Some(h) => break h,
            None if Instant::now() < bootstrap_deadline => {
                ::std::thread::sleep(Duration::from_millis(1));
            }
            None => return,
        }
    };

    loop {
        // ── 1. take commands ────────────────────────────────────────────

        {
            let mut cmds = handle.cmds.lock().unwrap();
            for cmd in cmds.drain(..) {
                match cmd {
                    DriverCmd::AddListener(listener, shared, base) => {
                        let id = shared.server_id;
                        servers.insert(id, DriverServer {
                            server_id: id,
                            listener,
                            base,
                            shared,
                        });
                    }
                    DriverCmd::AddClientConn(conn_id, stream, shared, conn_shared, tls) => {
                        // The ClientHello is only produced by the first
                        // process() pass — drive the fresh conn once here so
                        // the poll loop's POLLOUT flush gets it on the wire
                        // (nothing else would wake an idle client conn).
                        stream
                            .set_nonblocking(true)
                            .expect("client stream nonblocking");
                        let mut conn = DriverConn {
                            conn_id,
                            stream,
                            tls,
                            shared: conn_shared,
                            server: shared,
                            parked_for_sni: false,
                            sni_requested: false,
                            sni_servername: None,
                            sni_deadline: None,
                            out_buf: Vec::new(),
                            secure_reported: false,
                            finishing: false,
                            close_notify_sent: false,
                        };
                        if !tls_conn_drive(&mut conn) {
                            // Handshake failed synchronously: ClientError is
                            // already queued (tls_conn_drive pushes it).
                            tls_conn_finish(&mut conn, true);
                        } else {
                            conns.insert(conn_id, conn);
                        }
                    }
                    DriverCmd::RemoveServer(id) => remove_queue.push(id),
                }
            }
        }
        for id in remove_queue.drain(..) {
            if let Some(ds) = servers.remove(&id) {
                // Mark closing; close all connections of this server.
                let dead: Vec<u64> = conns
                    .values()
                    .filter(|c| c.server.server_id == id)
                    .map(|c| c.conn_id)
                    .collect();
                for cid in dead {
                    if let Some(mut conn) = conns.remove(&cid) {
                        tls_conn_finish(&mut conn, /*notify=*/ true);
                    }
                }
                drop(ds.listener);
                tls_push_event(&ds.shared, TlsEvent::ServerClosed);
            }
        }
        // NOTE: no idle exit. The driver is a process-lifetime singleton
        // (the HTTPThread model): exiting when idle raced against the next
        // listen()'s AddListener command — the driver could observe
        // "no servers, no conns" after spawn but before the command landed
        // and exit, leaving every later listener unserved.

        // ── 2. build poll set ───────────────────────────────────────────
        enum Target {
            Wake,
            Listener(u64),
            Conn(u64),
        }
        let mut fds: Vec<libc::pollfd> = Vec::with_capacity(2 + servers.len() + conns.len());
        let mut targets: Vec<Target> = Vec::with_capacity(fds.capacity());
        fds.push(libc::pollfd {
            fd: wake_read_fd,
            events: libc::POLLIN,
            revents: 0,
        });
        targets.push(Target::Wake);
        for ds in servers.values() {
            fds.push(libc::pollfd {
                fd: ds.listener.as_raw_fd(),
                events: libc::POLLIN,
                revents: 0,
            });
            targets.push(Target::Listener(ds.server_id));
        }
        for conn in conns.values() {
            let mut events = 0;
            if !conn.parked_for_sni && !conn.finishing {
                events |= libc::POLLIN;
            }
            if !conn.out_buf.is_empty() {
                events |= libc::POLLOUT;
            }
            if events != 0 {
                fds.push(libc::pollfd {
                    fd: conn.stream.as_raw_fd(),
                    events,
                    revents: 0,
                });
                targets.push(Target::Conn(conn.conn_id));
            }
        }

        // ── 3. timeout: block indefinitely (the wake pipe covers commands
        //       and JS-side writes; conn fds cover I/O) unless an SNI
        //       deadline is pending — the parked conn needs no I/O wake,
        //       only the deadline check. ─────────────────────────────────
        let mut timeout_ms: i32 = -1;
        for conn in conns.values() {
            if conn.parked_for_sni {
                if let Some(deadline) = conn.sni_deadline {
                    let remain = deadline.saturating_duration_since(Instant::now());
                    let ms = remain.as_millis() as i32;
                    if timeout_ms < 0 || ms < timeout_ms {
                        timeout_ms = ms;
                    }
                }
            }
        }
        if timeout_ms != -1 && timeout_ms < 0 {
            timeout_ms = 0;
        }

        // ── 4. poll ─────────────────────────────────────────────────────
        // SAFETY: fds is a valid pollfd array for the duration of the call.
        let ready = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout_ms) };

        // ── 5. dispatch wake + commands first (writes/SNI may unblock
        //       conns regardless of socket readiness) ────────────────────
        if ready > 0 {
            if fds[0].revents != 0 {
                let mut buf = [0u8; 64];
                // SAFETY: drain the wake pipe (non-blocking is not set; the
                // pipe only ever holds a few bytes, and writers never block
                // on a 64-byte drain of a 64K pipe buffer).
                while unsafe { libc::read(wake_read_fd, buf.as_mut_ptr().cast(), buf.len()) } > 0 {}
            }
        }

        // ── 6. accept + socket I/O ─────────────────────────────────────
        if ready > 0 {
            for i in 1..fds.len() {
                let revents = fds[i].revents;
                if revents == 0 {
                    continue;
                }
                match &targets[i] {
                    Target::Wake => {}
                    Target::Listener(server_id) => {
                        if revents & libc::POLLIN != 0 {
                            tls_driver_accept(*server_id, &mut servers, &mut conns);
                        }
                    }
                    Target::Conn(conn_id) => {
                        let conn_id = *conn_id;
                        if conns.get(&conn_id).is_none() {
                            continue;
                        }
                        {
                            let conn = conns.get_mut(&conn_id).unwrap();
                            if revents & libc::POLLOUT != 0 {
                                tls_conn_flush_out(conn);
                            }
                        }
                        if revents & libc::POLLIN != 0 {
                            let conn = conns.get_mut(&conn_id).unwrap();
                            if !tls_conn_read_and_drive(conn) {
                                if let Some(mut conn) = conns.remove(&conn_id) {
                                    tls_conn_finish(&mut conn, true);
                                }
                                continue;
                            }
                        }
                        if revents & (libc::POLLERR | libc::POLLHUP | libc::POLLNVAL) != 0 {
                            // Error/hangup: drain any still-unread data,
                            // then tear the connection down.
                            let conn = conns.get_mut(&conn_id).unwrap();
                            if !tls_conn_read_and_drive(conn) {
                                if let Some(mut conn) = conns.remove(&conn_id) {
                                    tls_conn_finish(&mut conn, true);
                                }
                            }
                        }
                    }
                }
            }
        }

        // ── 7. service pass: resolve/flush/finish transitions that do not
        //       depend on socket readiness ──────────────────────────────
        let conn_ids: Vec<u64> = conns.keys().copied().collect();
        for conn_id in conn_ids {
            let Some(conn) = conns.get_mut(&conn_id) else {
                continue;
            };
            // destroy(): immediate teardown, close_notify not required.
            if conn.shared.want_destroy.load(Ordering::Acquire) {
                if let Some(mut conn) = conns.remove(&conn_id) {
                    tls_conn_finish(&mut conn, true);
                }
                continue;
            }
            // end(): flush parked writes, then close_notify, then close.
            if conn.shared.want_end.load(Ordering::Acquire) && !conn.finishing {
                conn.finishing = true;
                tls_conn_flush_pending_writes(conn);
                if !conn.close_notify_sent {
                    let _ = conn.tls.queue_close_notify();
                    conn.out_buf.extend(conn.tls.take_outgoing());
                    conn.close_notify_sent = true;
                }
            }
            if conn.parked_for_sni {
                let resolved = conn
                    .shared
                    .sni_result
                    .lock()
                    .unwrap()
                    .as_ref()
                    .map(|_| ());
                if resolved.is_some() {
                    conn.parked_for_sni = false;
                    if !tls_conn_drive(conn) {
                        if let Some(mut conn) = conns.remove(&conn_id) {
                            tls_conn_finish(&mut conn, true);
                        }
                        continue;
                    }
                } else if conn
                    .sni_deadline
                    .map(|d| Instant::now() >= d)
                    .unwrap_or(false)
                {
                    // SNICallback never resolved: fail closed, loudly.
                    tls_push_event(
                        &conn.server,
                        TlsEvent::ClientError {
                            conn_id,
                            message: format!(
                                "SNICallback for '{}' did not resolve within {}s",
                                conn.sni_servername.clone().unwrap_or_default(),
                                SNI_DEADLINE.as_secs()
                            ),
                        },
                    );
                    if let Some(mut conn) = conns.remove(&conn_id) {
                        tls_conn_finish(&mut conn, true);
                    }
                    continue;
                }
            }
            // Flush parked JS writes whenever the handshake is done.
            if conn.secure_reported && !conn.finishing {
                tls_conn_flush_pending_writes(conn);
            }
            if !conn.out_buf.is_empty() {
                tls_conn_flush_out(conn);
            }
            // finishing complete: close_notify flushed → close.
            if conn.finishing && conn.out_buf.is_empty() && conn.close_notify_sent {
                if let Some(mut conn) = conns.remove(&conn_id) {
                    tls_conn_finish(&mut conn, true);
                }
            }
        }
    }
}

/// Accept all pending connections on a ready listener.
fn tls_driver_accept(
    server_id: u64,
    servers: &mut HashMap<u64, DriverServer>,
    conns: &mut HashMap<u64, DriverConn>,
) {
    let Some(ds) = servers.get(&server_id) else {
        return;
    };
    loop {
        match ds.listener.accept() {
            Ok((stream, _addr)) => {
                let _ = stream.set_nonblocking(true);
                let conn_id = NEXT_TLS_ID.fetch_add(1, Ordering::Relaxed);
                let tls = match ds.base.accept() {
                    Ok(t) => t,
                    Err(e) => {
                        log::error!("[tls] accept: TlsConnection setup failed: {}", e);
                        continue;
                    }
                };
                let shared = Arc::new(ConnShared::new());
                conns.insert(
                    conn_id,
                    DriverConn {
                        conn_id,
                        stream,
                        tls,
                        shared: Arc::clone(&shared),
                        server: Arc::clone(&ds.shared),
                        parked_for_sni: false,
                        sni_requested: false,
                        sni_servername: None,
                        sni_deadline: None,
                        out_buf: Vec::new(),
                        secure_reported: false,
                        finishing: false,
                        close_notify_sent: false,
                    },
                );
                tls_push_event(
                    &ds.shared,
                    TlsEvent::Connection {
                        conn_id,
                        shared: Arc::clone(&shared),
                    },
                );
            }
            Err(e) if e.kind() == ::std::io::ErrorKind::WouldBlock => break,
            Err(_) => break,
        }
    }
}

/// Read available ciphertext, feed it, and drive the TLS state machine.
/// Returns false when the connection must be torn down.
fn tls_conn_read_and_drive(conn: &mut DriverConn) -> bool {
    let mut buf = [0u8; 16 * 1024];
    loop {
        // SAFETY: buf is a valid read buffer.
        let n = unsafe {
            libc::read(
                conn.stream.as_raw_fd(),
                buf.as_mut_ptr().cast::<core::ffi::c_void>(),
                buf.len(),
            )
        };
        if n > 0 {
            conn.tls.feed(&buf[..n as usize]);
            continue;
        }
        if n == 0 {
            // EOF: peer closed the write side. Drive once more to surface
            // any close_notify/remaining plaintext, then finish.
            let ok = tls_conn_drive(conn);
            if ok && conn.secure_reported && !conn.finishing {
                // Plain FIN without close_notify: abrupt close (no 'end').
                return false;
            }
            return ok;
        }
        let err = ::std::io::Error::last_os_error();
        match err.kind() {
            ::std::io::ErrorKind::WouldBlock => break,
            ::std::io::ErrorKind::Interrupted => continue,
            _ => return false,
        }
    }
    tls_conn_drive(conn)
}

/// One process() pass. Sets DRIVER_CURRENT_CONN so the select-certificate
/// callback can find this connection. Returns false on fatal error.
fn tls_conn_drive(conn: &mut DriverConn) -> bool {
    DRIVER_CURRENT_CONN.with(|c| c.set(conn as *mut DriverConn));
    let result = conn.tls.process();
    DRIVER_CURRENT_CONN.with(|c| c.set(::std::ptr::null_mut()));

    let res = match result {
        Ok(r) => r,
        Err(e) => {
            tls_push_event(
                &conn.server,
                TlsEvent::ClientError {
                    conn_id: conn.conn_id,
                    message: format!("TLS handshake/protocol error: {}", e),
                },
            );
            return false;
        }
    };
    conn.out_buf.extend(conn.tls.take_outgoing());

    match res.state {
        TlsState::PendingCertificate => {
            // Select-certificate callback returned retry (SNI dispatch in
            // flight). Park until the JS SNICallback resolves.
            conn.parked_for_sni = true;
            true
        }
        TlsState::Handshaking => true,
        TlsState::Active | TlsState::PeerClosed | TlsState::Closed => {
            if !conn.secure_reported {
                conn.secure_reported = true;
                // ssl_in_use park-and-flush ordering: parked writes
                // (including any issued from inside SNICallback) hit the
                // wire BEFORE the secureConnection event is dispatched, so
                // they also precede anything written from a
                // secureConnection listener.
                tls_conn_flush_pending_writes(conn);
                // Session snapshot while this thread still owns the SSL —
                // the JS surface (getProtocol/getCipher/getPeerCertificate)
                // reads only this, never the SSL object.
                let info = TlsSessionInfo {
                    servername: conn.sni_servername.clone().or_else(|| conn.tls.servername()),
                    alpn: conn.tls.alpn_protocol().map(|a| a.to_vec()),
                    protocol: conn.tls.protocol_version(),
                    cipher_name: conn.tls.cipher_name(),
                    cipher_version: conn.tls.cipher_version(),
                    peer_cert: conn.tls.peer_cert_info(),
                };
                tls_push_event(
                    &conn.server,
                    TlsEvent::SecureConnection {
                        conn_id: conn.conn_id,
                        info,
                    },
                );
            }
            if !res.plaintext.is_empty() {
                let mut bytes = Vec::new();
                for chunk in res.plaintext {
                    bytes.extend_from_slice(&chunk);
                }
                tls_push_event(
                    &conn.server,
                    TlsEvent::Data {
                        conn_id: conn.conn_id,
                        bytes,
                    },
                );
            }
            if res.state == TlsState::PeerClosed || res.state == TlsState::Closed {
                // Clean close_notify from the peer: emit End, answer with
                // our own close_notify, then close once flushed.
                tls_push_event(&conn.server, TlsEvent::End { conn_id: conn.conn_id });
                conn.finishing = true;
                let _ = conn.tls.queue_close_notify();
                conn.out_buf.extend(conn.tls.take_outgoing());
                conn.close_notify_sent = true;
            }
            true
        }
    }
}

/// Drain JS-parked plaintext writes into the SSL (driver thread only —
/// this is the ssl_in_use "retry parked write" equivalent).
fn tls_conn_flush_pending_writes(conn: &mut DriverConn) {
    let chunks: Vec<Vec<u8>> = {
        let mut g = conn.shared.pending_writes.lock().unwrap();
        ::std::mem::take(&mut *g)
    };
    for chunk in chunks {
        if chunk.is_empty() {
            continue;
        }
        match conn.tls.write(&chunk) {
            Ok(_) => {}
            Err(TlsError::NotReady) => {
                // Not ready (WANT_READ/WRITE): park the chunk back, retry
                // on a later pass.
                let mut g = conn.shared.pending_writes.lock().unwrap();
                g.insert(0, chunk);
                break;
            }
            Err(e) => {
                tls_push_event(
                    &conn.server,
                    TlsEvent::ClientError {
                        conn_id: conn.conn_id,
                        message: format!("TLS write failed: {}", e),
                    },
                );
            }
        }
    }
    conn.out_buf.extend(conn.tls.take_outgoing());
}

/// Write pending ciphertext to the socket (nonblocking; partial writes
/// keep the remainder for the POLLOUT pass).
fn tls_conn_flush_out(conn: &mut DriverConn) {
    while !conn.out_buf.is_empty() {
        // SAFETY: out_buf is a valid write buffer for the duration of the call.
        let n = unsafe {
            libc::write(
                conn.stream.as_raw_fd(),
                conn.out_buf.as_ptr().cast::<core::ffi::c_void>(),
                conn.out_buf.len(),
            )
        };
        if n > 0 {
            conn.out_buf.drain(..n as usize);
            continue;
        }
        if n == 0 {
            break;
        }
        let err = ::std::io::Error::last_os_error();
        match err.kind() {
            ::std::io::ErrorKind::WouldBlock => break,
            ::std::io::ErrorKind::Interrupted => continue,
            _ => {
                conn.out_buf.clear();
                break;
            }
        }
    }
}

/// Final teardown: mark closed, push the Close event (JS unroots the
/// socket and emits `close`).
fn tls_conn_finish(conn: &mut DriverConn, notify: bool) {
    conn.shared.closed.store(true, Ordering::Release);
    if notify {
        tls_push_event(&conn.server, TlsEvent::Close { conn_id: conn.conn_id });
    }
}

// ─── JS-thread event drain (ConcurrentTask) ─────────────────────────────

/// `AnyTaskWithExtraContext` callback bridge (must be a safe fn).
fn tls_event_tasklet_shim(ctx: *mut ServerShared, _parent: *mut ()) {
    // SAFETY: ctx was set to the Arc'd ServerShared pointer at schedule
    // time; the JS-thread registry keeps the allocation alive until the
    // ServerClosed event is processed (the last event).
    unsafe { tls_event_tasklet(ctx) };
}

unsafe fn tls_event_tasklet(ptr: *mut ServerShared) {
    // SAFETY: ptr is the Arc'd ServerShared; this tasklet is its final JS-
    // thread consumer (the registry Arc keeps it alive until ServerClosed).
    let s = unsafe { &mut *ptr };
    // Allow re-scheduling while we drain (mirrors resolve_tasklet step 1).
    s.task_scheduled.store(false, Ordering::Release);

    let events = {
        let mut g = s.events.lock().unwrap();
        ::std::mem::take(&mut *g)
    };
    if events.is_empty() {
        return;
    }

    let cx = s.cx;
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let server_val = s
        .server_obj_root
        .as_ref()
        .map(|g| g.get(0))
        .unwrap_or_else(UndefinedValue);
    if !server_val.is_object() {
        // Server object / Promise unreachable (unrooted earlier): drop events.
        return;
    }
    rooted!(&in(cx_ref) let server_root = server_val.to_object());

    // Enter the server object's realm for the whole drain (standard SM
    // embedding rule — the tasklet runs outside any JS activation). For
    // ClientConnect shares this is the pending Promise's realm.
    {
        let mut realm = AutoRealm::new_from_handle(cx_ref, server_root.handle());
        let realm_cx: &mut mozjs::context::JSContext = &mut realm;

        for ev in events {
            match ev {
                TlsEvent::Connection { conn_id, shared } => {
                    let socket = tls_build_socket_js(realm_cx.raw_cx(), conn_id);
                    if socket.is_null() {
                        log::error!("[tls] failed to build TLSSocket object for conn {}", conn_id);
                        continue;
                    }
                    let socket_val = ObjectValue(socket);
                    // RAII heap-root: the guard pins the slot at a stable
                    // heap address the GC updates in place and unroots when
                    // the JsConn entry drops (Close event). Registration
                    // failure (OOM) keeps the degraded no-entry path.
                    if let Some(guard) = RawValueRootGuard::new(
                        cx,
                        ::std::slice::from_ref(&socket_val),
                        c"TLSSocket.object",
                    ) {
                        let live = guard.get(0);
                        TLS_CONNS.with(|m| {
                            m.borrow_mut().insert(
                                conn_id,
                                JsConn {
                                    shared,
                                    socket_root: Some(guard),
                                },
                            );
                        });
                        tls_emit_js(cx, server_root.get(), "connection", &[live]);
                    }
                }
                TlsEvent::SniRequest { conn_id, servername } => {
                    let sni_fn_val = s
                        .sni_fn_root
                        .as_ref()
                        .map(|g| g.get(0))
                        .unwrap_or_else(UndefinedValue);
                    if !sni_fn_val.is_object() {
                        // has_sni was true at listen() — the root only
                        // disappears at ServerClosed. Unreachable; fail the
                        // handshake via the driver deadline if it ever fires.
                        log::error!("[tls] SniRequest without a rooted SNICallback (conn {})", conn_id);
                        continue;
                    }
                    tls_dispatch_sni_callback(
                        cx,
                        realm_cx,
                        server_root.get(),
                        sni_fn_val,
                        conn_id,
                        &servername,
                    );
                }
                TlsEvent::SecureConnection { conn_id, info } => {
                    let TlsSessionInfo {
                        servername,
                        alpn,
                        protocol,
                        cipher_name,
                        cipher_version,
                        peer_cert,
                    } = info;
                    // ClientConnect: the socket object is created HERE (the
                    // client side has no Connection event) and the pending
                    // Promise resolves with it.
                    let is_client = matches!(s.kind, ServerKind::ClientConnect);
                    let mut socket_ptr = tls_socket_ptr_for(conn_id);
                    if socket_ptr.is_null() && is_client {
                        let socket = tls_build_socket_js(realm_cx.raw_cx(), conn_id);
                        if socket.is_null() {
                            log::error!("[tls] failed to build client TLSSocket for conn {}", conn_id);
                            tls_reject_promise(cx, realm_cx, server_root.get(), "tls: failed to build socket object");
                            continue;
                        }
                        let socket_val = ObjectValue(socket);
                        match RawValueRootGuard::new(
                            cx,
                            ::std::slice::from_ref(&socket_val),
                            c"TLSSocket.object",
                        ) {
                            Some(guard) => {
                                let live = guard.get(0);
                                let shared = s
                                    .client_conn
                                    .as_ref()
                                    .map(Arc::clone)
                                    .unwrap_or_else(|| Arc::new(ConnShared::new()));
                                TLS_CONNS.with(|m| {
                                    m.borrow_mut().insert(
                                        conn_id,
                                        JsConn {
                                            shared,
                                            socket_root: Some(guard),
                                        },
                                    );
                                });
                                socket_ptr = live.to_object();
                            }
                            None => {
                                tls_reject_promise(cx, realm_cx, server_root.get(), "tls: failed to root socket object");
                                continue;
                            }
                        }
                    }
                    if socket_ptr.is_null() {
                        tls_emit_js(cx, server_root.get(), "secureConnection", &[]);
                        continue;
                    }
                    // Enrich the socket with the negotiated session truth.
                    rooted!(&in(realm_cx) let sock = socket_ptr);
                    if let Some(name) = &servername {
                        tls_define_str_prop(cx, sock.get(), "servername", name);
                    }
                    if let Some(proto) = &alpn {
                        let p = String::from_utf8_lossy(proto).to_string();
                        tls_define_str_prop(cx, sock.get(), "_alpnProtocol", &p);
                    }
                    if let Some(p) = &protocol {
                        tls_define_str_prop(cx, sock.get(), "_tlsProtocol", p);
                    }
                    if let Some(n) = &cipher_name {
                        tls_define_str_prop(cx, sock.get(), "_tlsCipherName", n);
                    }
                    if let Some(v) = &cipher_version {
                        tls_define_str_prop(cx, sock.get(), "_tlsCipherVersion", v);
                    }
                    if let Some(cert) = &peer_cert {
                        tls_define_peer_cert_prop(cx, realm_cx, sock.get(), cert);
                    }
                    let socket_val = TLS_CONNS
                        .with(|m| {
                            m.borrow()
                                .get(&conn_id)
                                .and_then(|e| e.socket_root.as_ref().map(|g| g.get(0)))
                        })
                        .unwrap_or_else(|| ObjectValue(socket_ptr));
                    if is_client {
                        // Strip the `then` forwarder BEFORE resolving: the
                        // value handed to ResolvePromise is the socket, and
                        // a thenable would be assimilated via socket.then →
                        // promise.then → resolve-waiting-on-itself (deadlock).
                        // After this point the socket is a plain Node-shaped
                        // TLSSocket (no then — Node parity).
                        rooted!(&in(realm_cx) let sock_h = socket_ptr);
                        rooted!(&in(realm_cx) let undef = UndefinedValue());
                        JS_DefineProperty(
                            cx,
                            sock_h.handle().into(),
                            c"then".as_ptr(),
                            undef.handle().into(),
                            0,
                        );
                        rooted!(&in(realm_cx) let sv = socket_val);
                        JS::ResolvePromise(cx, server_root.handle().into(), sv.handle().into());
                        // Node parity: the client TLSSocket emits
                        // 'secureConnect' once the handshake completes.
                        tls_emit_js(cx, socket_ptr, "secureConnect", &[]);
                    } else {
                        tls_emit_js(cx, server_root.get(), "secureConnection", &[socket_val]);
                    }
                }
                TlsEvent::Data { conn_id, bytes } => {
                    let socket_val =
                        TLS_CONNS.with(|m| m.borrow().get(&conn_id).and_then(|e| e.socket_root.as_ref().map(|g| g.get(0))));
                    let Some(socket_val) = socket_val else { continue };
                    let payload = tls_bytes_to_array_buffer(cx, &bytes);
                    if payload.is_null() {
                        continue;
                    }
                    tls_emit_js(cx, socket_val.to_object(), "data", &[ObjectValue(payload)]);
                }
                TlsEvent::End { conn_id } => {
                    let socket_val =
                        TLS_CONNS.with(|m| m.borrow().get(&conn_id).and_then(|e| e.socket_root.as_ref().map(|g| g.get(0))));
                    let Some(socket_val) = socket_val else { continue };
                    tls_emit_js(cx, socket_val.to_object(), "end", &[]);
                }
                TlsEvent::Close { conn_id } => {
                    let entry = TLS_CONNS.with(|m| m.borrow_mut().remove(&conn_id));
                    if let Some(entry) = entry {
                        let socket_val = entry
                            .socket_root
                            .as_ref()
                            .map(|g| g.get(0))
                            .unwrap_or_else(UndefinedValue);
                        if socket_val.is_object() {
                            tls_emit_js(cx, socket_val.to_object(), "close", &[]);
                        }
                        // The guard's Drop unroots (liveness-guarded).
                        drop(entry);
                    }
                    if matches!(s.kind, ServerKind::ClientConnect) {
                        // Final JS-thread consumer on the client path (no
                        // ServerClosed event): release the Promise root and
                        // drop the registry Arc.
                        drop(s.server_obj_root.take());
                        TLS_SERVER_REGISTRY.with(|r| {
                            r.borrow_mut().remove(&s.server_id);
                        });
                    }
                }
                TlsEvent::ClientError { conn_id, message } => {
                    let err_obj = tls_build_error_js(cx, &message);
                    let socket_val =
                        TLS_CONNS.with(|m| m.borrow().get(&conn_id).and_then(|e| e.socket_root.as_ref().map(|g| g.get(0))));
                    if matches!(s.kind, ServerKind::ClientConnect) {
                        if let Some(sv) = socket_val.filter(|v| v.is_object()) {
                            // Node emits 'error' on the client TLSSocket —
                            // the early-socket shape now ALWAYS has a socket
                            // registered, handshake failures included.
                            tls_emit_js(cx, sv.to_object(), "error", &[ObjectValue(err_obj)]);
                        }
                        // Reject the pending Promise in every failure mode
                        // (connect-refused, handshake failure, post-handshake
                        // protocol error). Rejecting an already-settled
                        // Promise is a no-op, so this composes with the
                        // legacy promise shape.
                        tls_reject_promise(cx, realm_cx, server_root.get(), &message);
                    } else if let Some(sv) = socket_val.filter(|v| v.is_object()) {
                        tls_emit_js(cx, server_root.get(), "tlsClientError", &[ObjectValue(err_obj), sv]);
                    } else {
                        tls_emit_js(cx, server_root.get(), "tlsClientError", &[ObjectValue(err_obj)]);
                    }
                }
                TlsEvent::ServerClosed => {
                    tls_emit_js(cx, server_root.get(), "close", &[]);
                    // Invoke the stored close callback if present.
                    let mut cb_val = UndefinedValue();
                    JS_GetProperty(
                        cx,
                        server_root.handle().into(),
                        c"_closeCb".as_ptr(),
                        MutableHandle::<Value> {
                            _phantom_0: ::std::marker::PhantomData,
                            ptr: &mut cb_val,
                        },
                    );
                    if cb_val.is_object() {
                        rooted!(&in(realm_cx) let cb_root = cb_val);
                        let mut rval = UndefinedValue();
                        JS_CallFunctionValue(
                            cx,
                            server_root.handle().into(),
                            cb_root.handle().into(),
                            &HandleValueArray::empty(),
                            MutableHandle::<Value> {
                                _phantom_0: ::std::marker::PhantomData,
                                ptr: &mut rval,
                            },
                        );
                        JS_ClearPendingException(cx);
                    }
                    // Unroot the JS references (RAII drops, liveness-guarded);
                    // the JS-thread registry drops the final Arc (this tasklet
                    // is the last consumer).
                    drop(s.sni_fn_root.take());
                    drop(s.server_obj_root.take());
                    TLS_SERVER_REGISTRY.with(|r| {
                        r.borrow_mut().remove(&s.server_id);
                    });
                }
            }
        }
    }
}

/// Reject a pending Promise with a JS Error object carrying `message`.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn tls_reject_promise(
    cx: *mut JSContext,
    cx_ref: &mut mozjs::context::JSContext,
    promise: *mut JSObject,
    message: &str,
) {
    let err_obj = tls_build_error_js(cx, message);
    if err_obj.is_null() {
        return;
    }
    rooted!(&in(cx_ref) let promise_root = promise);
    rooted!(&in(cx_ref) let ev = ObjectValue(err_obj));
    // SAFETY: both handles are live roots of this realm.
    unsafe {
        JS::RejectPromise(cx, promise_root.handle().into(), ev.handle().into());
    }
}

/// Look up the cross-thread ConnShared for a conn_id (JS thread).
fn tls_conn_shared_for(conn_id: u64) -> Option<Arc<ConnShared>> {
    TLS_CONNS.with(|m| m.borrow().get(&conn_id).map(|e| Arc::clone(&e.shared)))
}

/// Current JS socket object pointer for a conn_id (unrooted handle for
/// immediate property definitions — the rooted copy lives in the map).
fn tls_socket_ptr_for(conn_id: u64) -> *mut JSObject {
    TLS_CONNS.with(|m| {
        m.borrow()
            .get(&conn_id)
            .and_then(|e| e.socket_root.as_ref().map(|g| g.get(0)))
            .filter(|v| v.is_object())
            .map(|v| v.to_object())
            .unwrap_or(::std::ptr::null_mut())
    })
}

/// Build the JS TLSSocket object for an accepted connection (proto chain
/// from the tls module's TLSSocket.prototype).
unsafe fn tls_build_socket_js(cx: *mut JSContext, conn_id: u64) -> *mut JSObject {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let tls_mod = crate::gc_store::gc_store_get(cx, "builtin:tls").unwrap_or(::std::ptr::null_mut());
    if tls_mod.is_null() {
        return ::std::ptr::null_mut();
    }
    rooted!(&in(cx_ref) let mod_root = tls_mod);
    let mut ctor_val = UndefinedValue();
    JS_GetProperty(
        cx,
        mod_root.handle().into(),
        c"TLSSocket".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut ctor_val,
        },
    );
    if !ctor_val.is_object() {
        return ::std::ptr::null_mut();
    }
    rooted!(&in(cx_ref) let ctor = ctor_val.to_object());
    let mut proto_val = UndefinedValue();
    JS_GetProperty(
        cx,
        ctor.handle().into(),
        c"prototype".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut proto_val,
        },
    );
    if !proto_val.is_object() {
        return ::std::ptr::null_mut();
    }
    rooted!(&in(cx_ref) let proto = proto_val.to_object());
    let obj = w2::JS_NewObjectWithGivenProto(cx_ref, ::std::ptr::null(), proto.handle().into());
    if obj.is_null() {
        return ::std::ptr::null_mut();
    }
    rooted!(&in(cx_ref) let obj_root = obj);

    rooted!(&in(cx_ref) let cid = DoubleValue(conn_id as f64));
    JS_DefineProperty(
        cx,
        obj_root.handle().into(),
        c"_connId".as_ptr(),
        cid.handle().into(),
        0,
    );
    rooted!(&in(cx_ref) let auth = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        obj_root.handle().into(),
        c"authorized".as_ptr(),
        auth.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    rooted!(&in(cx_ref) let enc = mozjs::jsval::BooleanValue(true));
    JS_DefineProperty(
        cx,
        obj_root.handle().into(),
        c"encrypted".as_ptr(),
        enc.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    rooted!(&in(cx_ref) let destroyed = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        obj_root.handle().into(),
        c"destroyed".as_ptr(),
        destroyed.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    obj_root.get()
}

/// Define a string property on an object (best-effort helper).
unsafe fn tls_define_str_prop(cx: *mut JSContext, obj: *mut JSObject, name: &str, value: &str) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let c_name = ZBox::from_bytes(name.as_bytes());
    let c_val = ZBox::from_bytes(value.as_bytes());
    let js_str = JS_NewStringCopyZ(cx, c_val.as_ptr());
    if js_str.is_null() {
        return;
    }
    rooted!(&in(cx_ref) let sv = mozjs::jsval::StringValue(&*js_str));
    JS_DefineProperty(
        cx,
        obj_root.handle().into(),
        c_name.as_ptr(),
        sv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
}

/// Build an error object with a `message` property (house pattern from
/// fetch_async::reject_with_message).
unsafe fn tls_build_error_js(cx: *mut JSContext, message: &str) -> *mut JSObject {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let err_obj = w2::JS_NewPlainObject(cx_ref));
    if err_obj.is_null() {
        return ::std::ptr::null_mut();
    }
    tls_define_str_prop(cx, err_obj.get(), "message", message);
    err_obj.get()
}

/// Build an ArrayBuffer payload from bytes (house pattern from
/// node_net::net_read — ownership transfers to the ArrayBuffer).
unsafe fn tls_bytes_to_array_buffer(cx: *mut JSContext, bytes: &[u8]) -> *mut JSObject {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    let len = bytes.len();
    let layout = ::std::alloc::Layout::from_size_align(len.max(1), 1)
        .unwrap_or_else(|_| ::std::alloc::Layout::from_size_align(1, 1).unwrap());
    // SAFETY: layout has non-zero size (clamped above).
    let alloc = unsafe { ::std::alloc::alloc(layout) };
    if alloc.is_null() {
        return ::std::ptr::null_mut();
    }
    // SAFETY: alloc is len bytes; source is a live slice.
    unsafe { ::std::ptr::copy_nonoverlapping(bytes.as_ptr(), alloc, len) };
    let ab = w2::NewArrayBufferWithContents(cx_ref, len, alloc.cast::<core::ffi::c_void>());
    if ab.is_null() {
        // SAFETY: same layout used for alloc.
        unsafe { ::std::alloc::dealloc(alloc, layout) };
        return ::std::ptr::null_mut();
    }
    ab
}

/// Call `obj.emit(name, args...)` via the EventEmitter native on `emit`.
unsafe fn tls_emit_js(cx: *mut JSContext, obj: *mut JSObject, name: &str, args: &[JSVal]) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);

    let c_name = ZBox::from_bytes(name.as_bytes());
    let name_str = JS_NewStringCopyZ(cx, c_name.as_ptr());
    if name_str.is_null() {
        return;
    }
    rooted!(&in(cx_ref) let name_val = mozjs::jsval::StringValue(&*name_str));

    let mut emit_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"emit".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut emit_val,
        },
    );
    if !emit_val.is_object() {
        return;
    }
    rooted!(&in(cx_ref) let emit_root = emit_val);

    let mut call_vals: Vec<JSVal> = Vec::with_capacity(args.len() + 1);
    call_vals.push(name_val.get());
    call_vals.extend_from_slice(args);
    let call_args = HandleValueArray {
        length_: call_vals.len(),
        elements_: call_vals.as_ptr(),
    };
    let mut rval = UndefinedValue();
    JS_CallFunctionValue(
        cx,
        obj_root.handle().into(),
        emit_root.handle().into(),
        &call_args,
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut rval,
        },
    );
    JS_ClearPendingException(cx);
}

/// Dispatch the user SNICallback: `SNICallback(servername, cb)` with
/// `this` = the tls server object. The `cb` native resolves the handshake
/// through ConnShared.sni_result.
unsafe fn tls_dispatch_sni_callback(
    cx: *mut JSContext,
    cx_ref: &mut mozjs::context::JSContext,
    server_obj: *mut JSObject,
    sni_fn_val: JSVal,
    conn_id: u64,
    servername: &str,
) {
    if !sni_fn_val.is_object() {
        return;
    }

    let cb_fn = JS_NewFunction(cx, Some(tls_sni_cb_native), 2, 0, c"onSNICallback".as_ptr());
    if cb_fn.is_null() {
        log::error!("[tls] SNICallback dispatch: JS_NewFunction failed (conn {})", conn_id);
        return;
    }
    let cb_obj = JS_GetFunctionObject(cb_fn);
    if cb_obj.is_null() {
        return;
    }
    rooted!(&in(cx_ref) let cb_root = cb_obj);
    rooted!(&in(cx_ref) let cid = DoubleValue(conn_id as f64));
    JS_DefineProperty(cx, cb_root.handle().into(), c"_sniConnId".as_ptr(), cid.handle().into(), 0);

    let c_servername = ZBox::from_bytes(servername.as_bytes());
    let name_js = JS_NewStringCopyZ(cx, c_servername.as_ptr());
    if name_js.is_null() {
        return;
    }
    rooted!(&in(cx_ref) let name_val = mozjs::jsval::StringValue(&*name_js));
    rooted!(&in(cx_ref) let server_root = server_obj);
    rooted!(&in(cx_ref) let sni_root = sni_fn_val);

    let call_args = HandleValueArray {
        length_: 2,
        elements_: [name_val.get(), ObjectValue(cb_obj)].as_ptr(),
    };
    let mut rval = UndefinedValue();
    JS_CallFunctionValue(
        cx,
        server_root.handle().into(),
        sni_root.handle().into(),
        &call_args,
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut rval,
        },
    );
    JS_ClearPendingException(cx);
    // NOTE: if the SNICallback never invokes `cb`, the driver's SNI deadline
    // fails the handshake with an explicit tlsClientError — never silent.
}

/// The `cb(err, secureContextOrOptions)` native handed to the user
/// SNICallback. Extracts {cert,key} (plain object, or a SecureContext via
/// its Rust-native `_scState`), posts the resolution to the driver, and
/// wakes it.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_sni_cb_native(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    // The conn binding lives on the FUNCTION object (`_sniConnId`), not on
    // `this`: users call `cb(err, ctx)` unbound from their SNICallback, so
    // `this` is undefined/global depending on caller strictness.
    let callee_v = args.calleev();
    if !callee_v.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = callee_v.to_object());

    let mut cid_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_obj.handle().into(),
        c"_sniConnId".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut cid_val,
        },
    );
    let Some(conn_id) = (if cid_val.is_double() {
        Some(cid_val.to_double() as u64)
    } else {
        None
    }) else {
        args.rval().set(UndefinedValue());
        return true;
    };
    let Some(shared) = tls_conn_shared_for(conn_id) else {
        // Connection already closed; nothing to resolve.
        args.rval().set(UndefinedValue());
        return true;
    };

    let err_val = if argc > 0 { *args.get(0).ptr } else { UndefinedValue() };
    let result: ::std::result::Result<(String, String), String> = if !err_val.is_null_or_undefined() {
        // cb(err, ...): surface the error message.
        let msg = if err_val.is_object() {
            let mut wrapped = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
            let wr = &mut wrapped;
            rooted!(&in(wr) let err_obj = err_val.to_object());
            let mut msg_val = UndefinedValue();
            JS_GetProperty(
                cx,
                err_obj.handle().into(),
                c"message".as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut msg_val,
                },
            );
            if msg_val.is_string() {
                crate::js_to_rust_string(cx, msg_val)
            } else {
                "SNICallback error".to_string()
            }
        } else {
            crate::js_to_rust_string(cx, err_val)
        };
        Err(msg)
    } else {
        let ctx_val = if argc > 1 { *args.get(1).ptr } else { UndefinedValue() };
        tls_extract_credentials(cx, ctx_val)
    };

    *shared.sni_result.lock().unwrap() = Some(result);
    tls_driver_wake();

    args.rval().set(UndefinedValue());
    true
}

/// Extract (cert_pem, key_pem) from the SNICallback's second argument:
/// either a SecureContext (Rust-native `_scState` — including the server
/// object itself, which carries the same state) or a plain
/// `{ key, cert }` options object.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn tls_extract_credentials(cx: *mut JSContext, val: JSVal) -> ::std::result::Result<(String, String), String> {
    if !val.is_object() {
        return Err("SNICallback resolved without a SecureContext or {key, cert} object".to_string());
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = val.to_object());

    // SecureContext path: Rust-native _scState private value.
    let mut sc_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"_scState".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut sc_val,
        },
    );
    if val_is_private(&sc_val) {
        let state = sc_val.to_private() as *mut SecureContextState;
        if !state.is_null() {
            let s = &*state;
            if let (Some(cert), Some(key)) = (&s.pem_certs, &s.pem_key) {
                return Ok((cert.clone(), key.clone()));
            }
            return Err("SecureContext passed to SNICallback has no cert/key loaded".to_string());
        }
    }

    // Plain object path: string .cert / .key properties.
    let get_str_prop = |name: &str| -> Option<String> {
        let cname = ZBox::from_bytes(name.as_bytes());
        let mut v = UndefinedValue();
        JS_GetProperty(
            cx,
            obj.handle().into(),
            cname.as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut v,
            },
        );
        if v.is_string() {
            Some(crate::js_to_rust_string(cx, v))
        } else {
            None
        }
    };
    match (get_str_prop("cert"), get_str_prop("key")) {
        (Some(cert), Some(key)) => Ok((cert, key)),
        _ => Err("SNICallback result must provide both cert and key".to_string()),
    }
}

/// Extract bytes from a JS value: string (UTF-8) or
/// Uint8Array/TypedArray/DataView/ArrayBuffer (house pattern from
/// node_buffer::collect_byte_view).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn tls_collect_write_bytes(cx: *mut JSContext, v: JSVal) -> Option<Vec<u8>> {
    if v.is_string() {
        return Some(crate::js_to_rust_string(cx, v).into_bytes());
    }
    if !v.is_object() {
        return None;
    }
    let obj = v.to_object();
    let mut length: usize = 0;
    let mut is_shared = false;
    let mut data_ptr: *mut u8 = ::std::ptr::null_mut();
    let unwrapped = mozjs_sys::jsapi::JS_GetObjectAsUint8Array(
        obj,
        &mut length,
        &mut is_shared,
        &mut data_ptr,
    );
    if !unwrapped.is_null() && !data_ptr.is_null() {
        // SAFETY: data_ptr/length describe the typed array's bytes.
        return Some(unsafe { ::std::slice::from_raw_parts(data_ptr, length) }.to_vec());
    }
    let mut ab_length: usize = 0;
    let mut ab_data: *mut u8 = ::std::ptr::null_mut();
    let ab_unwrapped = mozjs_sys::jsapi::JS::GetObjectAsArrayBuffer(obj, &mut ab_length, &mut ab_data);
    if !ab_unwrapped.is_null() && !ab_data.is_null() {
        // SAFETY: ab_data/ab_length describe the ArrayBuffer's bytes.
        return Some(unsafe { ::std::slice::from_raw_parts(ab_data, ab_length) }.to_vec());
    }
    if !ab_unwrapped.is_null() || !unwrapped.is_null() {
        return Some(Vec::new());
    }
    None
}

pub fn install(cx: &mut mozjs::context::JSContext) {
    // BCE-007 unified liveness: TLS driver activity (live servers + client
    // connects) must keep the JS thread's MiniEventLoop ticking — the
    // ConcurrentTask queue that carries every TLS event (SecureConnection,
    // Data, error, Close) is only drained by `tick_without_idle`, which
    // `drain_and_check` runs solely while `has_active_servers()` is true.
    // Without this probe a TLS-only script (no HTTP server, no timers)
    // never drains: the driver completes the TCP+TLS handshake on the wire
    // while the JS thread sleeps past all of it (silent forever-connect).
    crate::node_http::register_liveness_probe(tls_liveness_probe);

    rooted!(&in(cx) let mod_obj = unsafe { w2::JS_NewPlainObject(cx) });
    if mod_obj.get().is_null() {
        return;
    }

    unsafe {
        let raw = cx.raw_cx();

        // TLSSocket constructor
        let ctor_fn = JS_NewFunction(
            raw,
            Some(tls_socket_ctor),
            2,
            JSFUN_CONSTRUCTOR,
            c"TLSSocket".as_ptr(),
        );
        if !ctor_fn.is_null() {
            let ctor_obj = JS_GetFunctionObject(ctor_fn);
            rooted!(&in(cx) let cv = ObjectValue(ctor_obj));
            JS_DefineProperty(
                raw,
                mod_obj.handle().into(),
                c"TLSSocket".as_ptr(),
                cv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );

            // TLSSocket.prototype methods
            rooted!(&in(cx) let proto = w2::JS_NewPlainObject(cx));
            if !proto.get().is_null() {
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"write".as_ptr(),
                    Some(tls_socket_write),
                    2,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"end".as_ptr(),
                    Some(tls_socket_end),
                    1,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"destroy".as_ptr(),
                    Some(tls_socket_destroy),
                    0,
                    0,
                );
                w2::JS_DefineFunction(cx, proto.handle(), c"on".as_ptr(), Some(ee_on), 2, 0);
                w2::JS_DefineFunction(cx, proto.handle(), c"once".as_ptr(), Some(ee_once), 2, 0);
                w2::JS_DefineFunction(cx, proto.handle(), c"emit".as_ptr(), Some(ee_emit), 1, 0);
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"addListener".as_ptr(),
                    Some(ee_on),
                    2,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"removeListener".as_ptr(),
                    Some(ee_off),
                    2,
                    0,
                );
                w2::JS_DefineFunction(cx, proto.handle(), c"off".as_ptr(), Some(ee_off), 2, 0);
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"removeAllListeners".as_ptr(),
                    Some(ee_remove_all),
                    0,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"prependListener".as_ptr(),
                    Some(ee_prepend),
                    2,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"prependOnceListener".as_ptr(),
                    Some(ee_prepend_once),
                    2,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"getProtocol".as_ptr(),
                    Some(tls_get_protocol),
                    0,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"getCipher".as_ptr(),
                    Some(tls_get_cipher),
                    0,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"getPeerCertificate".as_ptr(),
                    Some(tls_get_peer_cert),
                    0,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"getFinished".as_ptr(),
                    Some(tls_socket_get_finished),
                    0,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"getPeerFinished".as_ptr(),
                    Some(tls_socket_get_peer_finished),
                    0,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"getSession".as_ptr(),
                    Some(tls_socket_get_session),
                    0,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"setEncoding".as_ptr(),
                    Some(tls_socket_set_encoding),
                    1,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"ref".as_ptr(),
                    Some(tls_socket_ref),
                    0,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"unref".as_ptr(),
                    Some(tls_socket_unref),
                    0,
                    0,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"getALPNProtocol".as_ptr(),
                    Some(tls_socket_get_alpn),
                    0,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c" renegotiate".as_ptr(),
                    Some(tls_socket_noop_bool),
                    0,
                    0,
                );

                let proto_val = ObjectValue(proto.get());
                rooted!(&in(cx) let pv = proto_val);
                rooted!(&in(cx) let ctor_h = ctor_obj);
                // Set Constructor.prototype = proto so `new TLSSocket()` instances
                // inherit from proto (where on/once/emit are defined).
                JS_DefineProperty(
                    raw,
                    ctor_h.handle().into(),
                    c"prototype".as_ptr(),
                    pv.handle().into(),
                    0,
                );
                // Also set proto.constructor = TLSSocket for completeness.
                rooted!(&in(cx) let ctor_val = ObjectValue(ctor_obj));
                JS_DefineProperty(
                    raw,
                    proto.handle().into(),
                    c"constructor".as_ptr(),
                    ctor_val.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }

        // Static methods
        w2::JS_DefineFunction(
            cx,
            mod_obj.handle(),
            c"connect".as_ptr(),
            Some(tls_connect),
            2,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            mod_obj.handle(),
            c"createServer".as_ptr(),
            Some(tls_create_server),
            2,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            mod_obj.handle(),
            c"createSecureContext".as_ptr(),
            Some(tls_create_secure_context),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            mod_obj.handle(),
            c"getCiphers".as_ptr(),
            Some(tls_get_ciphers),
            0,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            mod_obj.handle(),
            c"checkServerIdentity".as_ptr(),
            Some(tls_check_server_identity),
            2,
            JSPROP_ENUMERATE as u32,
        );

        // Constants
        let _ciphers_str =
            "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256";
        let cs = JS_NewStringCopyZ(
            raw,
            c"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256".as_ptr(),
        );
        if !cs.is_null() {
            rooted!(&in(cx) let csv = mozjs::jsval::StringValue(&*cs));
            JS_DefineProperty(
                raw,
                mod_obj.handle().into(),
                c"DEFAULT_CIPHERS".as_ptr(),
                csv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
        let minv = JS_NewStringCopyZ(raw, c"TLSv1.2".as_ptr());
        if !minv.is_null() {
            rooted!(&in(cx) let mv = mozjs::jsval::StringValue(&*minv));
            JS_DefineProperty(
                raw,
                mod_obj.handle().into(),
                c"DEFAULT_MIN_VERSION".as_ptr(),
                mv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
        let maxv = JS_NewStringCopyZ(raw, c"TLSv1.3".as_ptr());
        if !maxv.is_null() {
            rooted!(&in(cx) let xmv = mozjs::jsval::StringValue(&*maxv));
            JS_DefineProperty(
                raw,
                mod_obj.handle().into(),
                c"DEFAULT_MAX_VERSION".as_ptr(),
                xmv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        cache_builtin(cx, "tls", mod_obj.get());
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_ctor(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    // Get the constructor's .prototype property to set as the new object's proto.
    rooted!(&in(cx_ref) let callee_obj = args.calleev().to_object());
    let mut proto_val = UndefinedValue();
    JS_GetProperty(
        cx,
        callee_obj.handle().into(),
        c"prototype".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut proto_val,
        },
    );
    let proto_obj = if proto_val.is_object() {
        proto_val.to_object()
    } else {
        ::std::ptr::null_mut()
    };

    rooted!(&in(cx_ref) let proto_rooted = proto_obj);
    rooted!(&in(cx_ref) let obj = if !proto_obj.is_null() {
        unsafe { w2::JS_NewObjectWithGivenProto(cx_ref, ::std::ptr::null(), proto_rooted.handle().into()) }
    } else {
        w2::JS_NewPlainObject(cx_ref)
    });

    if obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return false;
    }

    // Properties
    rooted!(&in(cx_ref) let auth = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"authorized".as_ptr(),
        auth.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    rooted!(&in(cx_ref) let enc = mozjs::jsval::BooleanValue(true));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"encrypted".as_ptr(),
        enc.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    // If first arg is an object (socket), store reference
    if argc > 0 && (*args.get(0).ptr).is_object() {
        rooted!(&in(cx_ref) let sock = (*args.get(0).ptr).to_object());
        rooted!(&in(cx_ref) let sv = ObjectValue(sock.get()));
        JS_DefineProperty(
            cx,
            obj.handle().into(),
            c"_socket".as_ptr(),
            sv.handle().into(),
            0,
        );
    }

    // Store hostname from options
    if argc > 1 && (*args.get(1).ptr).is_object() {
        rooted!(&in(cx_ref) let opts = (*args.get(1).ptr).to_object());
        let mut host_val = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"servername".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut host_val,
            },
        );
        if host_val.is_string() {
            rooted!(&in(cx_ref) let hv = host_val);
            JS_DefineProperty(
                cx,
                obj.handle().into(),
                c"servername".as_ptr(),
                hv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        // Read ALPNProtocols from options and store as _alpnProtos
        let mut alpn_val = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"ALPNProtocols".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut alpn_val,
            },
        );
        if alpn_val.is_object() {
            rooted!(&in(cx_ref) let alpn_root = alpn_val);
            JS_DefineProperty(
                cx,
                obj.handle().into(),
                c"_alpnProtos".as_ptr(),
                alpn_root.handle().into(),
                0,
            );
        }

        // Read session from options
        let mut session_val = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"session".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut session_val,
            },
        );
        if !session_val.is_undefined() {
            rooted!(&in(cx_ref) let session_root = session_val);
            JS_DefineProperty(
                cx,
                obj.handle().into(),
                c"_session".as_ptr(),
                session_root.handle().into(),
                0,
            );
        }
    }

    // Initialize _refed = true (socket keeps event loop alive by default)
    rooted!(&in(cx_ref) let refed = mozjs::jsval::BooleanValue(true));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"_refed".as_ptr(),
        refed.handle().into(),
        0,
    );

    args.rval().set(ObjectValue(obj.get()));
    true
}

/// tls.connect(options) — TLS client connect with ALPN negotiation, SNI,
/// and session resumption support.
///
/// Reads `ALPNProtocols`, `servername`, `session`, and `secureContext`
/// from the options object, then creates a TlsClient + TlsConnection
/// for the outbound connection. The actual network I/O is performed
/// asynchronously via `fetch_async::start_tls_probe`.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_connect(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    // Options: host / port / servername / rejectUnauthorized / ca.
    // (Node defaults: servername = host, rejectUnauthorized = true.)
    let mut servername: Option<String> = None;
    let mut reject_unauthorized = true;
    let mut ca_pems: Vec<String> = Vec::new();
    let (host, port) = if argc > 0 && (*args.get(0).ptr).is_object() {
        rooted!(&in(cx_ref) let opts = (*args.get(0).ptr).to_object());
        let mut h = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"host".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut h,
            },
        );
        let host = if h.is_string() {
            crate::js_to_rust_string(cx, h)
        } else {
            "localhost".to_string()
        };
        let mut p = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"port".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut p,
            },
        );
        let port = if p.is_int32() {
            p.to_int32() as u16
        } else {
            443
        };
        let mut sn = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"servername".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut sn,
            },
        );
        if sn.is_string() {
            servername = Some(crate::js_to_rust_string(cx, sn));
        }
        let mut ra = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"rejectUnauthorized".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut ra,
            },
        );
        if ra.is_boolean() {
            reject_unauthorized = ra.to_boolean();
        }
        let mut ca = UndefinedValue();
        JS_GetProperty(
            cx,
            opts.handle().into(),
            c"ca".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut ca,
            },
        );
        if ca.is_string() {
            ca_pems.push(crate::js_to_rust_string(cx, ca));
        } else if ca.is_object() {
            // Array of PEM strings.
            rooted!(&in(cx_ref) let arr = ca.to_object());
            let mut i: u32 = 0;
            loop {
                let mut elem = UndefinedValue();
                JS_GetElement(
                    cx,
                    arr.handle().into(),
                    i,
                    MutableHandle::<Value> {
                        _phantom_0: ::std::marker::PhantomData,
                        ptr: &mut elem,
                    },
                );
                if elem.is_undefined() {
                    break;
                }
                if elem.is_string() {
                    ca_pems.push(crate::js_to_rust_string(cx, elem));
                }
                i += 1;
            }
        }
        (host, port)
    } else if argc > 0 && (*args.get(0).ptr).is_int32() {
        let port = (*args.get(0).ptr).to_int32() as u16;
        let host = if argc > 1 && (*args.get(1).ptr).is_string() {
            crate::js_to_rust_string(cx, *args.get(1).ptr)
        } else {
            "localhost".to_string()
        };
        (host, port)
    } else {
        args.rval().set(UndefinedValue());
        return true;
    };

    // Node callback form: `tls.connect(opts, cb)` / `tls.connect(port, host,
    // cb)` / `tls.connect(port, cb)` — the first function-valued argument
    // after the address args is invoked once on secureConnect.
    let mut connect_cb_val = UndefinedValue();
    {
        let mut i: u32 = 1;
        while i < argc {
            let v = *args.get(i).ptr;
            if v.is_object() && IsCallable(v.to_object()) {
                connect_cb_val = v;
                break;
            }
            i += 1;
        }
    }

    // @trace REQ-ENG-010 [api:tls.connect async] [entity:TlsSessionInfo]
    //
    // BCE-20260618-007 lineage: `tls.connect` never blocks the JS thread.
    // The earlier revision resolved it from a single stealth HTTPS HEAD
    // probe (fetch_async::start_tls_probe), which only proved "a TLS session
    // was possible" — the resolved socket had no session truth
    // (getProtocol/getCipher/getPeerCertificate had nothing real to read)
    // and no live I/O.
    //
    // This revision establishes a REAL client TLS connection on the shared
    // bao-tls-driver thread (same DriverConn machinery as server-side
    // accepted connections): a connect worker does the blocking TCP
    // connect, hands the stream to the driver, which drives the memory-BIO
    // handshake and then keeps the connection alive for real I/O
    // (write/end/destroy/data events). The session truth (protocol,
    // cipher, peer certificate) is captured by the driver at handshake
    // completion and rides the SecureConnection event to the JS thread.
    //
    // Node shape (this fix): the TLSSocket object is built HERE, at call
    // time, and returned synchronously — `tls.connect(opts, cb)` registers
    // cb as a 'secureConnect' listener and callers can `.on('data')` /
    // `.write()` the returned socket immediately (events fire once the
    // handshake completes). Promise compat: a `then` own property forwards
    // to the pending Promise for legacy `.then`/`await` callers; it is
    // stripped before ResolvePromise so promise assimilation never chases
    // the forwarder back into the same Promise (resolve deadlock).
    let promise = {
        rooted!(&in(cx_ref) let null_h = ::std::ptr::null_mut::<JSObject>());
        mozjs_sys::jsapi::JS::NewPromiseObject(cx, null_h.handle().into())
    };
    if promise.is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let promise_val = mozjs::jsval::ObjectValue(promise);

    // Client config (setup only — no handshake I/O until the driver drives
    // process()). BoringSSL verifies by default; `ca` anchors private CAs,
    // rejectUnauthorized:false disables verification (Node semantics).
    // Early-built client TLSSocket (set inside the setup closure once the
    // conn identity exists; stays null on early setup failures).
    let mut early_socket: *mut JSObject = ::std::ptr::null_mut();
    let setup_err: ::std::result::Result<(), String> = (|| {
        let client = TlsClient::new().map_err(|e| format!("tls: client init failed: {}", e))?;
        for pem in &ca_pems {
            for der in pem_parse_certs(pem) {
                if !client.add_trusted_der(&der) {
                    return Err("tls: add_trusted_der failed".to_string());
                }
            }
        }
        let mut conn = TlsConnection::new_client(&client, servername.as_deref().unwrap_or(&host))
            .map_err(|e| format!("tls: new_client failed: {}", e))?;
        if reject_unauthorized {
            // Node's default: verify the chain AND the hostname. BoringSSL
            // clients verify nothing unless explicitly enabled — a failure
            // to install the check must fail loudly, never degrade to an
            // unverified session.
            let verify_host = servername.clone().unwrap_or_else(|| host.clone());
            if !conn.set_verify_peer(&verify_host) {
                return Err("tls: set_verify_peer failed".to_string());
            }
        } else {
            conn.set_verify_off();
        }
        // Everything below needs the driver; acquire it before rooting.
        let Some(handle) = tls_driver_acquire() else {
            return Err("tls: TLS driver unavailable".to_string());
        };

        // Root the pending Promise (RAII — released on the Close event).
        // SAFETY: cx is live on this thread; promise_val is the pending Promise.
        let promise_root = match unsafe {
            RawValueRootGuard::new(cx, ::std::slice::from_ref(&promise_val), c"TLSSocket.promise")
        } {
            Some(g) => g,
            None => return Err("tls: rooting the pending Promise failed".to_string()),
        };

        let conn_shared = Arc::new(ConnShared::new());
        let loop_ptr: *const bun_event_loop::MiniEventLoop::MiniEventLoop<'static> =
            crate::timers::with_event_loop(|loop_| loop_ as *const _);
        let server_id = NEXT_TLS_ID.fetch_add(1, Ordering::Relaxed);
        let shared = Arc::new(ServerShared {
            server_id,
            kind: ServerKind::ClientConnect,
            cx,
            server_obj_root: Some(promise_root),
            sni_fn_root: None,
            client_conn: Some(Arc::clone(&conn_shared)),
            mini_loop_ptr: loop_ptr,
            concurrent_task:
                bun_event_loop::AnyTaskWithExtraContext::AnyTaskWithExtraContext::default(),
            task_scheduled: AtomicBool::new(false),
            events: Mutex::new(Vec::new()),
            closing: AtomicBool::new(false),
            sni_ctx_cache: Mutex::new(HashMap::new()),
            alpn_wire: None,
        });
        TLS_SERVER_REGISTRY.with(|r| {
            r.borrow_mut().insert(server_id, Arc::clone(&shared));
        });

        // Node shape: build the client TLSSocket NOW (call time), not at
        // SecureConnection time. The early socket carries the full proto
        // face (on/once/emit/write/end/destroy/getters), is what
        // tls.connect() returns, and is where every later event lands.
        let conn_id = NEXT_TLS_ID.fetch_add(1, Ordering::Relaxed);
        let socket = tls_build_socket_js(cx, conn_id);
        if socket.is_null() {
            return Err("tls: failed to build client TLSSocket".to_string());
        }
        let socket_val = ObjectValue(socket);
        let socket_root = match RawValueRootGuard::new(
            cx,
            ::std::slice::from_ref(&socket_val),
            c"TLSSocket.object",
        ) {
            Some(g) => g,
            None => return Err("tls: rooting the client TLSSocket failed".to_string()),
        };
        TLS_CONNS.with(|m| {
            m.borrow_mut().insert(
                conn_id,
                JsConn {
                    shared: Arc::clone(&conn_shared),
                    socket_root: Some(socket_root),
                },
            );
        });
        early_socket = socket;

        // Connect worker: blocking TCP connect off the JS thread, then the
        // stream moves to the driver (exclusive ownership, AddListener's
        // TlsServer contract). Failure rejects the Promise and releases the
        // registry entry (ClientError + Close events, no conn ever existed).
        // (conn_id was allocated above with the early TLSSocket so the two
        // share one identity.)
        let worker_host = host.clone();
        let worker_shared = Arc::clone(&shared);
        let worker_conn_shared = Arc::clone(&conn_shared);
        let spawned = ::std::thread::Builder::new()
            .name("bao-tls-connect".into())
            .spawn(move || {
                let addrs: Vec<::std::net::SocketAddr> = (worker_host.as_str(), port)
                    .to_socket_addrs()
                    .map(|it| it.collect())
                    .unwrap_or_default();
                let deadline = Instant::now() + Duration::from_secs(10);
                let mut stream = None;
                for addr in addrs {
                    let remain = deadline.saturating_duration_since(Instant::now());
                    if remain.is_zero() {
                        break;
                    }
                    match TcpStream::connect_timeout(&addr, remain) {
                        Ok(s) => {
                            stream = Some(s);
                            break;
                        }
                        Err(_) => continue,
                    }
                }
                match stream {
                    Some(s) => {
                        handle
                            .cmds
                            .lock()
                            .unwrap()
                            .push(DriverCmd::AddClientConn(
                                conn_id,
                                s,
                                worker_shared,
                                worker_conn_shared,
                                conn,
                            ));
                        tls_driver_wake();
                    }
                    None => {
                        tls_push_event(
                            &worker_shared,
                            TlsEvent::ClientError {
                                conn_id,
                                message: format!("tls: connect to {}:{} failed", worker_host, port),
                            },
                        );
                        tls_push_event(&worker_shared, TlsEvent::Close { conn_id });
                    }
                }
            });
        if spawned.is_err() {
            // Thread spawn failure: unwind exactly what was registered —
            // the registry Arc AND the early TLSSocket's TLS_CONNS entry
            // (dropping it releases the socket root).
            TLS_SERVER_REGISTRY.with(|r| {
                r.borrow_mut().remove(&server_id);
            });
            TLS_CONNS.with(|m| {
                m.borrow_mut().remove(&conn_id);
            });
            return Err("tls: failed to spawn connect worker".to_string());
        }
        Ok(())
    })();

    if let ::std::result::Result::Err(msg) = setup_err {
        tls_reject_promise(cx, cx_ref, promise, &msg);
    }

    // Node-shape wiring on the early socket: promise forwarder + the
    // connect callback. Runs only when the socket was built.
    if !early_socket.is_null() {
        rooted!(&in(cx_ref) let sock_root = early_socket);
        // Hidden Promise reference for the `then` forwarder below.
        rooted!(&in(cx_ref) let pv = promise_val);
        JS_DefineProperty(
            cx,
            sock_root.handle().into(),
            c"_tlsPromise".as_ptr(),
            pv.handle().into(),
            0,
        );
        // `then` forwarder: legacy `.then(res, rej)` / `await` callers get
        // real Promise semantics (the forwarded call returns the chain
        // Promise). Stripped at resolution time (see SecureConnection).
        let then_fn = JS_NewFunction(cx, Some(tls_socket_then), 2, 0, c"then".as_ptr());
        if !then_fn.is_null() {
            let then_obj = JS_GetFunctionObject(then_fn);
            if !then_obj.is_null() {
                rooted!(&in(cx_ref) let tv = ObjectValue(then_obj));
                JS_DefineProperty(
                    cx,
                    sock_root.handle().into(),
                    c"then".as_ptr(),
                    tv.handle().into(),
                    0,
                );
            }
        }
        // Node callback: one 'secureConnect' listener, invoked with the
        // socket when the handshake completes.
        if connect_cb_val.is_object() {
            rooted!(&in(cx_ref) let cb_root = connect_cb_val);
            let mut on_val = UndefinedValue();
            JS_GetProperty(
                cx,
                sock_root.handle().into(),
                c"on".as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut on_val,
                },
            );
            if on_val.is_object() {
                let ev_str = JS_NewStringCopyZ(cx, c"secureConnect".as_ptr());
                if !ev_str.is_null() {
                    rooted!(&in(cx_ref) let ev_val = StringValue(&*ev_str));
                    let args_vals = [ev_val.get(), cb_root.get()];
                    let call_args = HandleValueArray {
                        length_: 2,
                        elements_: args_vals.as_ptr(),
                    };
                    let mut rval = UndefinedValue();
                    JS_CallFunctionName(
                        cx,
                        sock_root.handle().into(),
                        c"on".as_ptr(),
                        &call_args,
                        MutableHandle::<Value> {
                            _phantom_0: ::std::marker::PhantomData,
                            ptr: &mut rval,
                        },
                    );
                    JS_ClearPendingException(cx);
                }
            }
        }
        args.rval().set(ObjectValue(early_socket));
        return true;
    }

    args.rval().set(promise_val);
    true
}

/// `socket.then(onFulfilled, onRejected)` — forwards to the pending Promise
/// carried in the socket's hidden `_tlsPromise` property. Returns the real
/// chain Promise so `.then` chaining and `await` behave natively.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_then(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    rooted!(&in(cx_ref) let obj = this.to_object());
    let mut pv = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"_tlsPromise".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut pv,
        },
    );
    if !pv.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    rooted!(&in(cx_ref) let promise_root = pv.to_object());
    let on_f = if argc > 0 { *args.get(0).ptr } else { UndefinedValue() };
    let on_r = if argc > 1 { *args.get(1).ptr } else { UndefinedValue() };
    rooted!(&in(cx_ref) let on_f_root = on_f);
    rooted!(&in(cx_ref) let on_r_root = on_r);
    let args_vals = [on_f_root.get(), on_r_root.get()];
    let call_args = HandleValueArray {
        length_: 2,
        elements_: args_vals.as_ptr(),
    };
    let mut rval = UndefinedValue();
    JS_CallFunctionName(
        cx,
        promise_root.handle().into(),
        c"then".as_ptr(),
        &call_args,
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut rval,
        },
    );
    args.rval().set(rval);
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_create_server(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let server = w2::JS_NewPlainObject(cx_ref));
    if !server.get().is_null() {
        w2::JS_DefineFunction(
            cx_ref,
            server.handle(),
            c"listen".as_ptr(),
            Some(tls_server_listen),
            2,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            server.handle(),
            c"close".as_ptr(),
            Some(tls_server_close),
            1,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            server.handle(),
            c"address".as_ptr(),
            Some(tls_server_address),
            0,
            0,
        );
        w2::JS_DefineFunction(cx_ref, server.handle(), c"on".as_ptr(), Some(ee_on), 2, 0);
        w2::JS_DefineFunction(
            cx_ref,
            server.handle(),
            c"once".as_ptr(),
            Some(ee_once),
            2,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            server.handle(),
            c"emit".as_ptr(),
            Some(ee_emit),
            1,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            server.handle(),
            c"removeListener".as_ptr(),
            Some(ee_off),
            2,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            server.handle(),
            c"removeAllListeners".as_ptr(),
            Some(ee_remove_all),
            0,
            0,
        );

        // Store the first arg (options or SecureContext) as _secureContext
        // tls.createServer(options, [callback]) — options may contain key/cert directly
        if argc > 0 && (*args.get(0).ptr).is_object() {
            rooted!(&in(cx_ref) let opts = (*args.get(0).ptr).to_object());
            rooted!(&in(cx_ref) let ov = ObjectValue(opts.get()));
            JS_DefineProperty(
                cx,
                server.handle().into(),
                c"_secureContext".as_ptr(),
                ov.handle().into(),
                0,
            );

            // Parse key/cert from options and store in SecureContextState on the server object
            let mut key_val = UndefinedValue();
            JS_GetProperty(
                cx,
                opts.handle().into(),
                c"key".as_ptr(),
                MutableHandle::<JSVal> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut key_val,
                },
            );
            if key_val.is_string() {
                let pem = crate::js_to_rust_string(cx, key_val);
                sc_state_set_key(cx, server.get(), &pem);
            }
            let mut cert_val = UndefinedValue();
            JS_GetProperty(
                cx,
                opts.handle().into(),
                c"cert".as_ptr(),
                MutableHandle::<JSVal> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut cert_val,
                },
            );
            if cert_val.is_string() {
                let pem = crate::js_to_rust_string(cx, cert_val);
                sc_state_set_cert(cx, server.get(), &pem);
            }

            // Parse ALPNProtocols from options
            let mut alpn_val = UndefinedValue();
            JS_GetProperty(
                cx,
                opts.handle().into(),
                c"ALPNProtocols".as_ptr(),
                MutableHandle::<JSVal> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut alpn_val,
                },
            );
            if !alpn_val.is_undefined() {
                sc_state_set_alpn_protos(cx, server.get(), alpn_val);
            }

            // Parse SNICallback from options — store as JS function reference
            let mut sni_val = UndefinedValue();
            JS_GetProperty(
                cx,
                opts.handle().into(),
                c"SNICallback".as_ptr(),
                MutableHandle::<JSVal> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut sni_val,
                },
            );
            if sni_val.is_object() {
                rooted!(&in(cx_ref) let sni_root = sni_val);
                JS_DefineProperty(
                    cx,
                    server.handle().into(),
                    c"_sniCallback".as_ptr(),
                    sni_root.handle().into(),
                    0,
                );
            }

            // Parse session from options (for session resumption)
            let mut session_val = UndefinedValue();
            JS_GetProperty(
                cx,
                opts.handle().into(),
                c"session".as_ptr(),
                MutableHandle::<JSVal> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut session_val,
                },
            );
            if !session_val.is_undefined() {
                // Store as a reference property; the actual session bytes
                // are applied when SSL objects are created in listen().
                rooted!(&in(cx_ref) let session_root = session_val);
                JS_DefineProperty(
                    cx,
                    server.handle().into(),
                    c"_session".as_ptr(),
                    session_root.handle().into(),
                    0,
                );
            }
        }

        // Node API: tls.createServer(options[, listener]) — the listener is
        // a 'secureConnection' listener. Wire it through the same EE face
        // `server.on('secureConnection', ...)` uses (previously the arg was
        // silently dropped — the server then never spoke to the client).
        if argc > 1 {
            let v = *args.get(1).ptr;
            if v.is_object() && IsCallable(v.to_object()) {
                rooted!(&in(cx_ref) let cb_root = v);
                let mut on_val = UndefinedValue();
                JS_GetProperty(
                    cx,
                    server.handle().into(),
                    c"on".as_ptr(),
                    MutableHandle::<Value> {
                        _phantom_0: ::std::marker::PhantomData,
                        ptr: &mut on_val,
                    },
                );
                if on_val.is_object() {
                    let ev_str = JS_NewStringCopyZ(cx, c"secureConnection".as_ptr());
                    if !ev_str.is_null() {
                        rooted!(&in(cx_ref) let ev_val = StringValue(&*ev_str));
                        let args_vals = [ev_val.get(), cb_root.get()];
                        let call_args = HandleValueArray {
                            length_: 2,
                            elements_: args_vals.as_ptr(),
                        };
                        let mut rval = UndefinedValue();
                        JS_CallFunctionName(
                            cx,
                            server.handle().into(),
                            c"on".as_ptr(),
                            &call_args,
                            MutableHandle::<Value> {
                                _phantom_0: ::std::marker::PhantomData,
                                ptr: &mut rval,
                            },
                        );
                        JS_ClearPendingException(cx);
                    }
                }
            }
        }
        args.rval().set(ObjectValue(server.get()));
        return true;
    }
    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_create_secure_context(
    cx: *mut JSContext,
    _argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let ctx = w2::JS_NewPlainObject(cx_ref));
    if !ctx.get().is_null() {
        w2::JS_DefineFunction(
            cx_ref,
            ctx.handle(),
            c"setKey".as_ptr(),
            Some(sc_set_key),
            1,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            ctx.handle(),
            c"setCert".as_ptr(),
            Some(sc_set_cert),
            1,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            ctx.handle(),
            c"addCACert".as_ptr(),
            Some(sc_add_ca_cert),
            1,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            ctx.handle(),
            c"setCA".as_ptr(),
            Some(sc_set_ca),
            1,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            ctx.handle(),
            c"setALPNProtocols".as_ptr(),
            Some(sc_set_alpn_protocols),
            1,
            0,
        );
        w2::JS_DefineFunction(
            cx_ref,
            ctx.handle(),
            c"setSession".as_ptr(),
            Some(sc_set_session),
            1,
            0,
        );

        // Initialize SecureContextState as private value
        let state = Box::new(SecureContextState::new());
        let ptr = Box::into_raw(state) as *const core::ffi::c_void;
        let pv = mozjs::jsval::PrivateValue(ptr);
        rooted!(&in(cx_ref) let pv_h = pv);
        JS_DefineProperty(
            cx,
            ctx.handle().into(),
            c"_scState".as_ptr(),
            pv_h.handle().into(),
            0,
        );

        args.rval().set(ObjectValue(ctx.get()));
        return true;
    }
    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn sc_set_key(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc > 0 {
        let val = *args.get(0).ptr;
        if val.is_string() {
            let pem = crate::js_to_rust_string(cx, val);
            let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
            let cx_ref = &mut wrapped_cx;
            rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
            sc_state_set_key(cx, this_obj.get(), &pem);
        }
    }
    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn sc_set_cert(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc > 0 {
        let val = *args.get(0).ptr;
        if val.is_string() {
            let pem = crate::js_to_rust_string(cx, val);
            let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
            let cx_ref = &mut wrapped_cx;
            rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
            sc_state_set_cert(cx, this_obj.get(), &pem);
        }
    }
    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn sc_add_ca_cert(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc > 0 {
        let val = *args.get(0).ptr;
        if val.is_string() {
            let pem = crate::js_to_rust_string(cx, val);
            let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
            let cx_ref = &mut wrapped_cx;
            rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
            sc_state_add_ca(cx, this_obj.get(), &pem);
        }
    }
    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn sc_set_ca(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc > 0 {
        let val = *args.get(0).ptr;
        if val.is_string() {
            let pem = crate::js_to_rust_string(cx, val);
            // setCA replaces the entire CA store, so reset first
            let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
            let cx_ref = &mut wrapped_cx;
            rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
            let state = sc_state_ensure(cx, this_obj.get());
            (*state).ca_certs = Vec::new();
            sc_state_add_ca(cx, this_obj.get(), &pem);
        }
    }
    args.rval().set(UndefinedValue());
    true
}

/// secureContext.setALPNProtocols(protocols) — set the ALPN protocols list.
/// Accepts an array of protocol name strings, e.g. ['h2', 'http/1.1'].
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn sc_set_alpn_protocols(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc > 0 {
        let val = *args.get(0).ptr;
        let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
        let cx_ref = &mut wrapped_cx;
        rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
        sc_state_set_alpn_protos(cx, this_obj.get(), val);
    }
    args.rval().set(UndefinedValue());
    true
}

/// secureContext.setSession(session) — set the session data for resumption.
/// Accepts a Buffer or Uint8Array containing serialized SSL_SESSION data.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn sc_set_session(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc > 0 {
        let val = *args.get(0).ptr;
        // For now, accept string or object (Buffer-like).
        // When BoringSSL session serialization bindings are available,
        // this will parse the actual SSL_SESSION data.
        if val.is_string() {
            let data = crate::js_to_rust_string(cx, val);
            let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
            let cx_ref = &mut wrapped_cx;
            rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
            sc_state_set_session(cx, this_obj.get(), data.as_bytes());
        }
    }
    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_get_ciphers(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let ciphers = [
        "TLS_AES_256_GCM_SHA384",
        "TLS_CHACHA20_POLY1305_SHA256",
        "TLS_AES_128_GCM_SHA256",
        "ECDHE-RSA-AES256-GCM-SHA384",
        "ECDHE-RSA-AES128-GCM-SHA256",
        "ECDHE-ECDSA-AES256-GCM-SHA384",
        "ECDHE-ECDSA-AES128-GCM-SHA256",
    ];
    rooted!(&in(cx_ref) let arr = w2::NewArrayObject1(cx_ref, ciphers.len()));
    if !arr.get().is_null() {
        for (i, name) in ciphers.iter().enumerate() {
            let c_name = ZBox::from_bytes(name.as_bytes());
            let js_str = JS_NewStringCopyZ(cx, c_name.as_ptr());
            if !js_str.is_null() {
                rooted!(&in(cx_ref) let v = mozjs::jsval::StringValue(&*js_str));
                JS_DefineElement(
                    cx,
                    arr.handle().into(),
                    i as u32,
                    v.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }
        args.rval().set(ObjectValue(arr.get()));
        return true;
    }
    args.rval().set(UndefinedValue());
    true
}

/// tls.checkServerIdentity(hostname, cert) — verify the server's certificate
/// matches the expected hostname. Delegates to `bun_boringssl::check_server_identity`.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_check_server_identity(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    // This is a JS-level function; the actual cert checking is done in
    // `bun_boringssl::check_server_identity` at the BoringSSL level during
    // TLS handshake. This function provides a JS-callable API that returns
    // an Error object if verification fails, or undefined if it passes.
    // For now, return undefined (identity check passes by default).
    // Full implementation requires access to the peer certificate from JS,
    // which will be added when SSL_get_peer_certificate bindings are complete.
    let _ = (cx, argc);
    args.rval().set(UndefinedValue());
    true
}

/// socket.write(data) — queue plaintext for TLS delivery. The bytes are
/// PARKED in the connection's Mutex-protected queue and encrypted+sent by
/// the driver thread (the SSL object's single owner — see the ssl_in_use
/// analysis in the driver section). Returns false when the socket is not
/// backed by a live server connection (e.g. a tls.connect probe socket).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_write(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());

    let Some((shared, _socket)) = tls_socket_conn_handle(cx, this_obj.get()) else {
        args.rval().set(mozjs::jsval::BooleanValue(false));
        return true;
    };
    if shared.closed.load(Ordering::Acquire) {
        args.rval().set(mozjs::jsval::BooleanValue(false));
        return true;
    }
    if argc > 0 {
        let data_val = *args.get(0).ptr;
        if let Some(bytes) = tls_collect_write_bytes(cx, data_val) {
            if !bytes.is_empty() {
                shared.pending_writes.lock().unwrap().push(bytes);
                tls_driver_wake();
            }
        }
    }
    args.rval().set(mozjs::jsval::BooleanValue(true));
    true
}

/// socket.end([data]) — optional final write, then graceful TLS shutdown
/// (flush parked writes, send close_notify, close).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_end(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());

    if let Some((shared, _socket)) = tls_socket_conn_handle(cx, this_obj.get()) {
        if !shared.closed.load(Ordering::Acquire) {
            if argc > 0 {
                let data_val = *args.get(0).ptr;
                if let Some(bytes) = tls_collect_write_bytes(cx, data_val) {
                    if !bytes.is_empty() {
                        shared.pending_writes.lock().unwrap().push(bytes);
                    }
                }
            }
            shared.want_end.store(true, Ordering::Release);
            tls_driver_wake();
        }
    }
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// socket.destroy() — immediate teardown (no close_notify guarantee).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_destroy(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());

    if let Some((shared, _socket)) = tls_socket_conn_handle(cx, this_obj.get()) {
        if !shared.closed.load(Ordering::Acquire) {
            shared.want_destroy.store(true, Ordering::Release);
            tls_driver_wake();
        }
    }
    tls_set_bool_prop(cx, this_obj.get(), "destroyed", true);
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// Resolve a JS socket object to its live connection handle via `_connId`.
/// Returns None for sockets not backed by a live server connection.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn tls_socket_conn_handle(
    cx: *mut JSContext,
    obj: *mut JSObject,
) -> Option<(Arc<ConnShared>, Option<JSVal>)> {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut cid_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        c"_connId".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut cid_val,
        },
    );
    if !cid_val.is_double() {
        return None;
    }
    let conn_id = cid_val.to_double() as u64;
    let entry = TLS_CONNS.with(|m| {
        m.borrow()
            .get(&conn_id)
            .map(|e| (Arc::clone(&e.shared), e.socket_root.as_ref().map(|g| g.get(0))))
    });
    entry
}

/// Define a boolean property on an object.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn tls_set_bool_prop(cx: *mut JSContext, obj: *mut JSObject, name: &str, value: bool) {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let c_name = ZBox::from_bytes(name.as_bytes());
    rooted!(&in(cx_ref) let bv = mozjs::jsval::BooleanValue(value));
    JS_DefineProperty(
        cx,
        obj_root.handle().into(),
        c_name.as_ptr(),
        bv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
}

/// Noop returning false (for methods like renegotiate).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_noop_bool(_cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(mozjs::jsval::BooleanValue(false));
    true
}

// ─── TLSSocket methods ─────────────────────────────────────────────────

/// socket.getFinished() — returns the TLS Finished message verify data.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_get_finished(
    _cx: *mut JSContext,
    _argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(mozjs::jsval::BooleanValue(false));
    true
}

/// socket.getPeerFinished() — returns the peer's TLS Finished message verify data.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_get_peer_finished(
    _cx: *mut JSContext,
    _argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(mozjs::jsval::BooleanValue(false));
    true
}

/// socket.getSession() — returns the TLS session ticket/data for resumption.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_get_session(
    _cx: *mut JSContext,
    _argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(UndefinedValue());
    true
}

/// socket.setEncoding(encoding) — set the encoding for the readable stream.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_set_encoding(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());

    if argc > 0 && (*args.get(0).ptr).is_string() {
        rooted!(&in(cx_ref) let enc_val = *args.get(0).ptr);
        JS_DefineProperty(
            cx,
            this_obj.handle().into(),
            c"_encoding".as_ptr(),
            enc_val.handle().into(),
            0,
        );
    }

    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// socket.ref() — keep the event loop alive while the socket is active.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_ref(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
    rooted!(&in(cx_ref) let refed = mozjs::jsval::BooleanValue(true));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"_refed".as_ptr(),
        refed.handle().into(),
        0,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// socket.unref() — allow the event loop to exit even if the socket is active.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_unref(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());
    rooted!(&in(cx_ref) let refed = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"_refed".as_ptr(),
        refed.handle().into(),
        0,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// socket.getALPNProtocol() — returns the negotiated ALPN protocol.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_socket_get_alpn(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());

    // Check if _alpnProtocol was set on the socket (set during TLS handshake
    // resolution in fetch_async resolve_tasklet).
    let mut alpn_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_obj.handle().into(),
        c"_alpnProtocol".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut alpn_val,
        },
    );
    if alpn_val.is_string() {
        args.rval().set(alpn_val);
    } else {
        args.rval().set(UndefinedValue());
    }
    true
}

/// Read a plain property off a socket object (Undefined when absent).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn tls_socket_prop(cx: *mut JSContext, obj: *mut JSObject, name: &core::ffi::CStr) -> JSVal {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj_root = obj);
    let mut out = UndefinedValue();
    JS_GetProperty(
        cx,
        obj_root.handle().into(),
        name.as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut out,
        },
    );
    out
}

/// socket.getProtocol() — the negotiated TLS version captured at handshake
/// time (`_tlsProtocol`). Sockets without a completed handshake (and probe
/// objects) report `null`, Node's "no live session" answer — never a
/// fabricated version string.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_get_protocol(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let protocol = if args.thisv().is_object() {
        tls_socket_prop(cx, args.thisv().to_object(), c"_tlsProtocol")
    } else {
        UndefinedValue()
    };
    if protocol.is_string() {
        args.rval().set(protocol);
    } else {
        args.rval().set(mozjs::jsval::NullValue());
    }
    true
}

/// socket.getCipher() — `{ name, version }` from the handshake-time capture
/// (`_tlsCipherName` / `_tlsCipherVersion`). `null` when no cipher was
/// negotiated (Node's not-handshaked answer).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_get_cipher(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let name = if args.thisv().is_object() {
        tls_socket_prop(cx, args.thisv().to_object(), c"_tlsCipherName")
    } else {
        UndefinedValue()
    };
    if !name.is_string() {
        args.rval().set(mozjs::jsval::NullValue());
        return true;
    }
    let version = if args.thisv().is_object() {
        tls_socket_prop(cx, args.thisv().to_object(), c"_tlsCipherVersion")
    } else {
        UndefinedValue()
    };

    rooted!(&in(cx_ref) let obj = w2::JS_NewPlainObject(cx_ref));
    if obj.get().is_null() {
        args.rval().set(mozjs::jsval::NullValue());
        return true;
    }
    rooted!(&in(cx_ref) let nv = name);
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"name".as_ptr(),
        nv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    if version.is_string() {
        rooted!(&in(cx_ref) let vv = version);
        JS_DefineProperty(
            cx,
            obj.handle().into(),
            c"version".as_ptr(),
            vv.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }
    args.rval().set(ObjectValue(obj.get()));
    true
}

/// socket.getPeerCertificate() — the certificate object captured at
/// handshake time (`_tlsPeerCert`). `null` when the peer presented no
/// certificate (Node's answer).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_get_peer_cert(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let cert = if args.thisv().is_object() {
        tls_socket_prop(cx, args.thisv().to_object(), c"_tlsPeerCert")
    } else {
        UndefinedValue()
    };
    if cert.is_object() {
        args.rval().set(cert);
    } else {
        args.rval().set(mozjs::jsval::NullValue());
    }
    true
}

/// Build the `_tlsPeerCert` property on a socket from the parsed peer
/// certificate (Node getPeerCertificate shape). Fields BoringSSL could not
/// produce are left undefined — never a placeholder value.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn tls_define_peer_cert_prop(
    cx: *mut JSContext,
    cx_ref: &mut mozjs::context::JSContext,
    obj: *mut JSObject,
    cert: &PeerCertInfo,
) {
    rooted!(&in(cx_ref) let cert_obj = w2::JS_NewPlainObject(cx_ref));
    if cert_obj.get().is_null() {
        return;
    }
    // subject / issuer: { CN: "…", O: "…", … } from the parsed RDN entries.
    for (prop, entries) in [("subject", &cert.subject), ("issuer", &cert.issuer)] {
        rooted!(&in(cx_ref) let names_obj = w2::JS_NewPlainObject(cx_ref));
        if names_obj.get().is_null() {
            continue;
        }
        for entry in entries.iter() {
            tls_define_str_prop(cx, names_obj.get(), entry.key, &entry.value);
        }
        rooted!(&in(cx_ref) let names_val = ObjectValue(names_obj.get()));
        let c_prop = ZBox::from_bytes(prop.as_bytes());
        JS_DefineProperty(
            cx,
            cert_obj.handle().into(),
            c_prop.as_ptr(),
            names_val.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }
    for (prop, value) in [
        ("valid_from", &cert.valid_from),
        ("valid_to", &cert.valid_to),
        ("fingerprint256", &cert.fingerprint256),
        ("serialNumber", &cert.serial_number),
    ] {
        if let Some(v) = value {
            tls_define_str_prop(cx, cert_obj.get(), prop, v);
        }
    }
    rooted!(&in(cx_ref) let cert_val = ObjectValue(cert_obj.get()));
    rooted!(&in(cx_ref) let sock_root = obj);
    JS_DefineProperty(
        cx,
        sock_root.handle().into(),
        c"_tlsPeerCert".as_ptr(),
        cert_val.handle().into(),
        0,
    );
}

/// tls.createServer().listen(port[, host][, callback]) — start a TLS server.
///
/// Binds a real TCP listener, hands it to the TLS driver thread, and — when
/// the options carried an `SNICallback` — registers the BoringSSL
/// select-certificate callback so the user's JS SNICallback is dispatched
/// during the handshake (see the driver section above for the full data
/// flow). Without `SNICallback` the static certificate serves every
/// connection (the contract's default branch).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_server_listen(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    let mut port: u16 = 0;
    let mut host: String = "0.0.0.0".to_string();
    let mut listen_cb: Option<JSVal> = None;
    for i in 0..argc as usize {
        let v = *args.get(i as u32).ptr;
        if v.is_int32() && i == 0 {
            port = v.to_int32() as u16;
        } else if v.is_string() {
            host = crate::js_to_rust_string(cx, v);
        } else if v.is_object() && JS_ObjectIsFunction(v.to_object()) {
            listen_cb = Some(v);
        }
    }

    let this_obj = args.thisv().to_object();

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_root = this_obj);

    // Try to read SecureContextState from this object first (set by createServer with key/cert)
    // Then fall back to _secureContext object's state
    let mut state_ptr: *mut SecureContextState = core::ptr::null_mut();

    // Check if this object has its own _scState
    let mut sc_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_root.handle().into(),
        c"_scState".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut sc_val,
        },
    );
    if val_is_private(&sc_val) {
        let ptr = sc_val.to_private() as *mut SecureContextState;
        if !ptr.is_null() && (!(*ptr).cert_ders.is_empty() || (*ptr).key_der.is_some()) {
            state_ptr = ptr;
        }
    }

    // If no state on this object, try _secureContext
    if state_ptr.is_null() {
        let mut ctx_val = UndefinedValue();
        JS_GetProperty(
            cx,
            this_root.handle().into(),
            c"_secureContext".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut ctx_val,
            },
        );

        if ctx_val.is_object() {
            rooted!(&in(cx_ref) let ctx_obj = ctx_val.to_object());
            let mut ctx_sc_val = UndefinedValue();
            JS_GetProperty(
                cx,
                ctx_obj.handle().into(),
                c"_scState".as_ptr(),
                MutableHandle::<JSVal> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut ctx_sc_val,
                },
            );
            if ctx_sc_val.is_double() && (ctx_sc_val.asBits_ & 0xFFFF000000000000) == 0 {
                let ptr = ctx_sc_val.to_private() as *mut SecureContextState;
                if !ptr.is_null() {
                    state_ptr = ptr;
                }
            }
        }
    }

    if state_ptr.is_null() {
        log::warn!("[tls] createServer.listen() called without cert/key");
        args.rval().set(mozjs::jsval::BooleanValue(false));
        return true;
    }

    let state = &*state_ptr;

    if state.cert_ders.is_empty() || state.key_der.is_none() {
        log::warn!("[tls] createServer.listen() called without cert/key");
        args.rval().set(mozjs::jsval::BooleanValue(false));
        return true;
    }

    // Use PEM strings directly with TlsServer::new(pem_certs, pem_key)
    let pem_certs = match &state.pem_certs {
        Some(p) => p.clone(),
        None => {
            log::warn!("[tls] createServer.listen() no PEM cert string available");
            args.rval().set(mozjs::jsval::BooleanValue(false));
            return true;
        }
    };
    let pem_key = match &state.pem_key {
        Some(p) => p.clone(),
        None => {
            log::warn!("[tls] createServer.listen() no PEM key string available");
            args.rval().set(mozjs::jsval::BooleanValue(false));
            return true;
        }
    };

    let base_server = match TlsServer::new(&pem_certs, &pem_key) {
        Ok(s) => s,
        Err(e) => {
            log::warn!("[tls] TlsServer::new failed: {}", e);
            args.rval().set(mozjs::jsval::BooleanValue(false));
            return true;
        }
    };

    // Configure ALPN on the server's SSL_CTX if protocols were set.
    // Uses BoringSSL's SSL_CTX_set_alpn_select_cb to advertise protocols.
    let mut alpn_wire: Option<&'static [u8]> = None;
    if let Some(ref wire) = state.alpn_protos {
        let alpn_box = wire.as_slice().to_vec().into_boxed_slice();
        let alpn_static: &'static [u8] = Box::leak(alpn_box);

        // SAFETY: SSL_CTX_set_alpn_select_cb is a BoringSSL FFI call.
        // The callback reads from the static leaked slice; the slice lives
        // for the process lifetime (the ServerShared retains it to
        // re-register on SNI-resolved CTXs).
        unsafe {
            SSL_CTX_set_alpn_select_cb(
                base_server.ctx(),
                Some(alpn_select_callback),
                alpn_static.as_ptr() as *mut core::ffi::c_void,
            );
        }
        alpn_wire = Some(alpn_static);
    }

    // SNICallback: register the select-certificate hook and heap-root the
    // JS function so the driver can dispatch into it. RAII guard: the slot
    // is pinned at a stable heap address and unrooted on drop (every early
    // return below releases it without a manual Remove).
    let mut sni_fn_root: Option<RawValueRootGuard> = None;
    let mut sni_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_root.handle().into(),
        c"_sniCallback".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut sni_val,
        },
    );
    let mut has_sni = sni_val.is_object() && JS_ObjectIsFunction(sni_val.to_object());
    if has_sni {
        // SAFETY: cx is live on this thread; sni_val is a live object value.
        match unsafe { RawValueRootGuard::new(cx, ::std::slice::from_ref(&sni_val), c"TLSServer.sniCallback") } {
            Some(guard) => sni_fn_root = Some(guard),
            None => has_sni = false,
        }
    }
    if has_sni {
        base_server.set_select_certificate_callback(Some(tls_select_cert_cb));
    }

    // Bind the real TCP listener (port 0 → ephemeral).
    let listener = match TcpListener::bind((host.as_str(), port)) {
        Ok(l) => l,
        Err(e) => {
            log::warn!("[tls] listen({}:{}) bind failed: {}", host, port, e);
            args.rval().set(mozjs::jsval::BooleanValue(false));
            return true;
        }
    };
    let real_port = listener.local_addr().map(|a| a.port()).unwrap_or(port);
    let _ = listener.set_nonblocking(true);

    // Heap-root the server object (the tasklet needs it across ticks) —
    // same RAII contract as the SNICallback root above.
    let server_obj_val = ObjectValue(this_root.get());
    // SAFETY: cx is live on this thread; the value is the live server object.
    let server_obj_root = unsafe {
        RawValueRootGuard::new(cx, ::std::slice::from_ref(&server_obj_val), c"TLSServer.object")
    };
    if server_obj_root.is_none() {
        log::warn!("[tls] listen: AddRawValueRoot failed");
        args.rval().set(mozjs::jsval::BooleanValue(false));
        return true;
    }

    let loop_ptr: *const bun_event_loop::MiniEventLoop::MiniEventLoop<'static> =
        crate::timers::with_event_loop(|loop_| loop_ as *const _);

    let server_id = NEXT_TLS_ID.fetch_add(1, Ordering::Relaxed);
    let shared = Arc::new(ServerShared {
        server_id,
        kind: ServerKind::Listener,
        cx,
        server_obj_root,
        sni_fn_root,
        client_conn: None,
        mini_loop_ptr: loop_ptr,
        concurrent_task: bun_event_loop::AnyTaskWithExtraContext::AnyTaskWithExtraContext::default(
        ),
        task_scheduled: AtomicBool::new(false),
        events: Mutex::new(Vec::new()),
        closing: AtomicBool::new(false),
        sni_ctx_cache: Mutex::new(HashMap::new()),
        alpn_wire,
    });

    // Hand the listener to the driver.
    let Some(handle) = tls_driver_acquire() else {
        // Resource exhaustion: fail closed. Dropping the shared unwinds the
        // guards (RAII unroot) and the listener.
        drop(shared);
        log::warn!("[tls] listen: TLS driver unavailable");
        args.rval().set(mozjs::jsval::BooleanValue(false));
        return true;
    };
    handle
        .cmds
        .lock()
        .unwrap()
        .push(DriverCmd::AddListener(listener, Arc::clone(&shared), base_server));
    TLS_SERVER_REGISTRY.with(|r| {
        r.borrow_mut().insert(server_id, Arc::clone(&shared));
    });
    tls_driver_wake();

    // Expose identity/address on the server object.
    rooted!(&in(cx_ref) let sid_val = DoubleValue(server_id as f64));
    JS_DefineProperty(
        cx,
        this_root.handle().into(),
        c"_serverId".as_ptr(),
        sid_val.handle().into(),
        0,
    );
    rooted!(&in(cx_ref) let port_val = Int32Value(real_port as i32));
    JS_DefineProperty(
        cx,
        this_root.handle().into(),
        c"_listenPort".as_ptr(),
        port_val.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    tls_define_str_prop(cx, this_root.get(), "_listenHost", &host);

    log::info!(
        "[tls] server listening on {}:{} (SNICallback: {})",
        host,
        real_port,
        if has_sni { "enabled" } else { "off — static cert" }
    );

    // 'listening' event + optional callback (same tick; matches the
    // node:net Server implementation's synchronous emit).
    tls_emit_js(cx, this_root.get(), "listening", &[]);
    if let Some(cb) = listen_cb {
        rooted!(&in(cx_ref) let cb_root = cb);
        let mut rval = UndefinedValue();
        JS_CallFunctionValue(
            cx,
            this_root.handle().into(),
            cb_root.handle().into(),
            &HandleValueArray::empty(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut rval,
            },
        );
        JS_ClearPendingException(cx);
    }

    args.rval().set(mozjs::jsval::BooleanValue(true));
    true
}

/// ALPN select callback for TLS server. Called by BoringSSL during the
/// TLS handshake to select the server's preferred ALPN protocol from
/// the client's offered list.
///
/// # Safety
///
/// `arg` must point to a wire-format ALPN protocol list (length-prefixed)
/// that outlives the callback registration.
unsafe extern "C" fn alpn_select_callback(
    _ssl: *mut SSL,
    out: *mut *const u8,
    out_len: *mut u8,
    client_protos: *const u8,
    client_protos_len: ::std::ffi::c_uint,
    arg: *mut core::ffi::c_void,
) -> ::std::ffi::c_int {
    if arg.is_null() || client_protos.is_null() || client_protos_len == 0 {
        return SSL_TLSEXT_ERR_NOACK;
    }

    // Server's supported protocols (wire-format, length-prefixed)
    let server_protos = unsafe {
        core::slice::from_raw_parts(arg as *const u8, 256) // safe upper bound
    };
    let client_list =
        unsafe { core::slice::from_raw_parts(client_protos, client_protos_len as usize) };

    // Iterate client protocols, find first match in server list
    let mut pos = 0usize;
    while pos < client_list.len() {
        let len = client_list[pos] as usize;
        pos += 1;
        if pos + len > client_list.len() {
            break;
        }
        let client_proto = &client_list[pos..pos + len];
        pos += len;

        // Search in server list
        let mut spos = 0usize;
        while spos < server_protos.len() {
            let slen = server_protos[spos] as usize;
            spos += 1;
            if spos + slen > server_protos.len() || slen == 0 {
                break;
            }
            let server_proto = &server_protos[spos..spos + slen];
            spos += slen;

            if client_proto == server_proto {
                unsafe {
                    *out = client_proto.as_ptr();
                    *out_len = len as u8;
                }
                return SSL_TLSEXT_ERR_OK;
            }
        }
    }

    SSL_TLSEXT_ERR_NOACK
}

/// tls.createServer().close([callback]) — stop listening and tear the
/// server down. The listener and every live connection are closed by the
/// driver; the final `ServerClosed` tasklet unroots the JS references,
/// emits `close`, and invokes the callback.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_server_close(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let this_obj = args.thisv().to_object();

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_root = this_obj);

    // Store the optional close callback for the ServerClosed tasklet.
    if argc > 0 && (*args.get(0).ptr).is_object() {
        rooted!(&in(cx_ref) let cb_val = *args.get(0).ptr);
        JS_DefineProperty(
            cx,
            this_root.handle().into(),
            c"_closeCb".as_ptr(),
            cb_val.handle().into(),
            0,
        );
    }

    // Find the driver-side server by id.
    let mut sid_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_root.handle().into(),
        c"_serverId".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut sid_val,
        },
    );
    if sid_val.is_double() {
        let server_id = sid_val.to_double() as u64;
        let shared = TLS_SERVER_REGISTRY.with(|r| r.borrow().get(&server_id).cloned());
        if let Some(shared) = shared {
            if !shared.closing.swap(true, Ordering::AcqRel) {
                if let Some(handle) = DRIVER.get() {
                    handle.cmds.lock().unwrap().push(DriverCmd::RemoveServer(server_id));
                    tls_driver_wake();
                }
            }
        }
    }

    // Drop the SecureContextState (legacy lifecycle owner).
    sc_state_drop(cx, this_obj);

    args.rval().set(UndefinedValue());
    true
}

/// tls.createServer().address() — bound address of the listening server.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tls_server_address(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = args.thisv().to_object());

    let mut port_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_obj.handle().into(),
        c"_listenPort".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut port_val,
        },
    );
    let mut host_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_obj.handle().into(),
        c"_listenHost".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut host_val,
        },
    );
    if !port_val.is_int32() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let addr = w2::JS_NewPlainObject(cx_ref);
    if addr.is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }
    rooted!(&in(cx_ref) let addr_root = addr);
    rooted!(&in(cx_ref) let port_h = port_val);
    JS_DefineProperty(
        cx,
        addr_root.handle().into(),
        c"port".as_ptr(),
        port_h.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    let fam_str = JS_NewStringCopyZ(cx, c"IPv4".as_ptr());
    if !fam_str.is_null() {
        rooted!(&in(cx_ref) let fam = mozjs::jsval::StringValue(&*fam_str));
        JS_DefineProperty(
            cx,
            addr_root.handle().into(),
            c"family".as_ptr(),
            fam.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }
    if host_val.is_string() {
        rooted!(&in(cx_ref) let host_h = host_val);
        JS_DefineProperty(
            cx,
            addr_root.handle().into(),
            c"address".as_ptr(),
            host_h.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }
    args.rval().set(ObjectValue(addr_root.get()));
    true
}