solid-pod-rs-server 0.4.0-alpha.15

Drop-in Solid Pod server binary. Wraps solid-pod-rs with actix-web and a JSS-compatible layered config loader.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
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
//! # solid-pod-rs-server
//!
//! Drop-in Solid Pod server binary wrapping
//! [`solid-pod-rs`](https://crates.io/crates/solid-pod-rs) with
//! [actix-web](https://docs.rs/actix-web). This crate is both a
//! library (for integration-test reuse) and a binary.
//!
//! ## Public types
//!
//! - [`AppState`]  — Shared actix-web application state (storage, dotfile policy, body cap).
//! - [`build_app`] — Builds the fully-configured `actix_web::App` with all routes and middleware.
//! - [`NodeInfoMeta`] — NodeInfo 2.1 metadata inputs.
//! - [`PathTraversalGuard`] — Middleware that rejects `..` path-traversal attempts.
//! - [`DotfileGuard`] — Middleware that enforces the dotfile allowlist.
//! - [`ErrorLoggingMiddleware`] — Middleware that logs 5xx responses with full error chains.
//! - [`body_cap_from_env`] — Reads `JSS_MAX_REQUEST_BODY` from the environment.
//! - [`cli`] — CLI argument definitions (clap derive).
//!
//! ## Route table
//!
//! | Method   | Path                                     | Handler              |
//! |----------|------------------------------------------|----------------------|
//! | GET/HEAD | `/{tail:.*}`                             | `handle_get`         |
//! | GET      | `/{folder}/*`                            | Glob merged Turtle   |
//! | PUT      | `/{tail:.*}`                             | `handle_put`         |
//! | PUT      | `/{tail:.*}/` + `Link: BasicContainer`   | Container creation   |
//! | POST     | `/{tail:.*}/`                            | `handle_post`        |
//! | PATCH    | `/{tail:.*}`                             | `handle_patch`       |
//! | DELETE   | `/{tail:.*}`                             | `handle_delete`      |
//! | COPY     | `/{tail:.*}` + `Source` header           | `handle_copy`        |
//! | OPTIONS  | `/{tail:.*}`                             | `handle_options`     |
//! | POST     | `/api/accounts/new`                      | Pod provisioning     |
//! | GET      | `/pods/check/{name}`                     | Pod existence check  |
//! | POST     | `/login/password`                        | Credentials login    |
//! | POST     | `/account/password/reset`                | Password reset       |
//! | POST     | `/account/password/change`               | Password change      |
//! | GET      | `/.well-known/solid`                     | Solid discovery      |
//! | GET      | `/.well-known/webfinger`                 | WebFinger JRD        |
//! | GET      | `/.well-known/nodeinfo`                  | NodeInfo discovery   |
//! | GET      | `/.well-known/nodeinfo/2.1`              | NodeInfo 2.1         |
//! | GET      | `/.well-known/did/nostr/{pubkey}.json`   | DID:nostr document   |
//!
//! ## Middleware stack (applied in order)
//!
//! 1. `NormalizePath` -- collapse `//` and decode %-encoded segments.
//! 2. `PathTraversalGuard` -- defence-in-depth `..` re-check.
//! 3. `DotfileGuard` -- rejects `.env` etc unless on the allowlist.
//! 4. `PayloadConfig` -- enforces `JSS_MAX_REQUEST_BODY` body cap.
//! 5. `ErrorLoggingMiddleware` -- structured 5xx logging.
//! 6. WAC-on-write -- PUT/POST/PATCH/DELETE require a write/append grant.

#![doc = include_str!("../README.md")]
#![deny(unsafe_code)]
#![warn(rust_2018_idioms)]

/// CLI argument definitions (clap derive structs).
pub mod cli;

use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use actix_web::body::{BoxBody, EitherBody};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::http::{header, StatusCode};
use actix_web::middleware::{NormalizePath, TrailingSlash};
use actix_web::{web, App, Error as ActixError, HttpRequest, HttpResponse};
use bytes::Bytes;
use futures_util::future::{ready, LocalBoxFuture, Ready};
use percent_encoding::percent_decode_str;
use serde::Deserialize;
use solid_pod_rs::{
    auth::nip98,
    config::sources::parse_size,
    interop,
    ldp::{self, LdpContainerOps, PatchCreateOutcome},
    mashlib::{self, MashlibConfig},
    provision,
    security::DotfileAllowlist,
    storage::Storage,
    wac::{
        self, conditions::RequestContext, parse_jsonld_acl, parser::parse_turtle_acl, AccessMode,
    },
    PodError,
};

// ---------------------------------------------------------------------------
// Shared app state
// ---------------------------------------------------------------------------

/// Actix-web shared state.
#[derive(Clone)]
pub struct AppState {
    pub storage: Arc<dyn Storage>,
    pub dotfiles: Arc<DotfileAllowlist>,
    pub body_cap: usize,
    pub nodeinfo: NodeInfoMeta,
    pub mashlib: MashlibConfig,
    /// Legacy alias — reads from `mashlib.mode` when `Cdn`.  Deprecated;
    /// use `mashlib` directly.
    pub mashlib_cdn: Option<String>,
    /// Payment configuration — drives `/pay/.info` and the `X-Balance` /
    /// `X-Cost` / `X-Pay-Currency` response headers on paid resources.
    pub pay_config: solid_pod_rs::payments::PayConfig,
    /// Absolute filesystem root of the pod storage tree. `Some` when the
    /// backend is `FsBackend`; `None` for in-memory or cloud-backed
    /// storage. Required by the `git` feature to locate pod directories
    /// for `GitAutoInit` (provisioning) and `GitHttpService` (serving).
    pub data_root: Option<PathBuf>,
    /// JSS-compatible pod creation limiter: one `POST /.pods` per IP per day.
    pub pod_create_limiter: Arc<PodCreateLimiter>,
    /// When non-empty, CORS responses are only reflected for origins in this
    /// list. Origins not in the list receive no `Access-Control-Allow-Origin`
    /// header. When empty (the default), the request `Origin` is echoed back
    /// (wildcard-equivalent behaviour, suitable for local dev).
    ///
    /// Configured via `--allowed-origins` / `SOLID_ALLOWED_ORIGINS` (comma-separated).
    pub allowed_origins: Vec<String>,
    /// Pre-shared key for the `POST /_admin/provision/{pubkey}` endpoint.
    /// When `None`, the endpoint returns 403 unconditionally.
    ///
    /// Configured via `--admin-key` / `SOLID_ADMIN_KEY`.
    pub admin_key: Option<String>,
}

/// NodeInfo 2.1 body inputs. Kept here so tests can override them.
#[derive(Clone, Debug)]
pub struct NodeInfoMeta {
    pub software_name: String,
    pub software_version: String,
    pub open_registrations: bool,
    pub total_users: u64,
    pub base_url: String,
}

impl Default for NodeInfoMeta {
    fn default() -> Self {
        Self {
            software_name: "solid-pod-rs-server".to_string(),
            software_version: env!("CARGO_PKG_VERSION").to_string(),
            open_registrations: false,
            total_users: 0,
            base_url: "http://localhost".to_string(),
        }
    }
}

/// Discover the body cap from the environment. Accepts values like
/// `50MB`, `1.5GB`, or a bare integer (bytes). Falls back to 50 MiB.
pub const DEFAULT_BODY_CAP: usize = 50 * 1024 * 1024;

/// Read `JSS_MAX_REQUEST_BODY` and parse via [`parse_size`]. On any
/// failure, returns [`DEFAULT_BODY_CAP`].
pub fn body_cap_from_env() -> usize {
    match std::env::var("JSS_MAX_REQUEST_BODY") {
        Ok(v) => parse_size(&v)
            .map(|u| u as usize)
            .unwrap_or(DEFAULT_BODY_CAP),
        Err(_) => DEFAULT_BODY_CAP,
    }
}

impl AppState {
    /// Convenience constructor for tests and the binary. Callers may
    /// replace fields after creation since `AppState` is a plain struct.
    pub fn new(storage: Arc<dyn Storage>) -> Self {
        Self {
            storage,
            dotfiles: Arc::new(DotfileAllowlist::from_env()),
            body_cap: body_cap_from_env(),
            nodeinfo: NodeInfoMeta::default(),
            mashlib: MashlibConfig::default(),
            mashlib_cdn: None,
            pay_config: solid_pod_rs::payments::PayConfig::default(),
            data_root: None,
            pod_create_limiter: Arc::new(PodCreateLimiter::default()),
            allowed_origins: Vec::new(),
            admin_key: None,
        }
    }
}

/// In-process sliding-window limiter for JSS-compatible `POST /.pods`.
#[derive(Debug)]
pub struct PodCreateLimiter {
    hits: Mutex<HashMap<IpAddr, Instant>>,
    window: Duration,
}

impl Default for PodCreateLimiter {
    fn default() -> Self {
        Self {
            hits: Mutex::new(HashMap::new()),
            window: Duration::from_secs(24 * 60 * 60),
        }
    }
}

impl PodCreateLimiter {
    fn check(&self, ip: IpAddr) -> Result<(), u64> {
        let now = Instant::now();
        let mut hits = self.hits.lock().unwrap();
        if let Some(last) = hits.get(&ip).copied() {
            let elapsed = now.saturating_duration_since(last);
            if elapsed < self.window {
                return Err(self.window.saturating_sub(elapsed).as_secs().max(1));
            }
        }
        hits.insert(ip, now);
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Error translation
// ---------------------------------------------------------------------------

fn to_actix(e: PodError) -> ActixError {
    match e {
        PodError::NotFound(_) => actix_web::error::ErrorNotFound(e.to_string()),
        PodError::BadRequest(_) => actix_web::error::ErrorBadRequest(e.to_string()),
        PodError::Unsupported(_) => actix_web::error::ErrorUnsupportedMediaType(e.to_string()),
        PodError::Forbidden => actix_web::error::ErrorForbidden(e.to_string()),
        PodError::Unauthenticated => actix_web::error::ErrorUnauthorized(e.to_string()),
        PodError::PreconditionFailed(_) => actix_web::error::ErrorPreconditionFailed(e.to_string()),
        _ => actix_web::error::ErrorInternalServerError(e.to_string()),
    }
}

// ---------------------------------------------------------------------------
// Auth helper — shared across handlers
// ---------------------------------------------------------------------------

/// Attempt NIP-98 bearer verification; returns the pubkey on success.
async fn extract_pubkey(req: &HttpRequest) -> Option<String> {
    let header_val = req
        .headers()
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())?;
    let url = format!(
        "http://{}{}",
        req.connection_info().host(),
        req.uri().path()
    );
    nip98::verify(header_val, &url, req.method().as_str(), None)
        .await
        .ok()
}

fn agent_uri(pubkey: Option<&String>) -> Option<String> {
    pubkey.map(|pk| format!("did:nostr:{pk}"))
}

/// Return `true` when the `Accept` header includes `text/html`.
///
/// Used for container `index.html` content negotiation: if a browser
/// requests `text/html` on a container URL and that container contains
/// an `index.html` resource, the server serves the HTML file instead of
/// the RDF container listing. Solid clients that send `Accept: text/turtle`
/// or `application/ld+json` skip this path entirely.
fn accept_includes_html(accept: &str) -> bool {
    accept.split(',').any(|entry| {
        let mime = entry.split(';').next().unwrap_or("").trim();
        mime.eq_ignore_ascii_case("text/html")
    })
}

// ---------------------------------------------------------------------------
// WAC enforcement for writes (PUT / POST / PATCH / DELETE)
// ---------------------------------------------------------------------------

/// Resolve the effective ACL and evaluate whether the given WebID may
/// perform `mode` on `path`.
///
/// Returns `Ok(())` on grant. On deny, returns an `actix_web::Error`:
/// * `401` when the request had no authenticated agent (so the client
///   knows retrying with credentials might work);
/// * `403` when authenticated but the ACL does not grant the mode.
async fn enforce_write(
    state: &AppState,
    path: &str,
    mode: AccessMode,
    agent_uri: Option<&str>,
) -> Result<(), ActixError> {
    // `StorageAclResolver` is generic over a concrete backend. `state`
    // holds an `Arc<dyn Storage>`; wrap it in a trait-object-friendly
    // adapter (`DynStorage`) that forwards each trait method so the
    // resolver can be constructed with a concrete type.
    let acl_doc = match find_effective_acl_dyn(&*state.storage, path).await {
        Ok(doc) => doc,
        Err(e) => return Err(to_actix(e)),
    };

    let ctx = RequestContext {
        web_id: agent_uri,
        client_id: None,
        issuer: None,
        payment_balance_sats: None,
    };
    let registry = wac::conditions::ConditionRegistry::default_with_client_and_issuer();
    let groups: wac::StaticGroupMembership = wac::StaticGroupMembership::default();
    let granted = wac::evaluate_access_ctx_with_registry(
        acl_doc.as_ref(),
        &ctx,
        path,
        mode,
        None,
        &groups,
        &registry,
    );
    if granted {
        return Ok(());
    }

    let allow_header = wac::wac_allow_header(acl_doc.as_ref(), agent_uri, path);
    let (status, body, unauthenticated) = if agent_uri.is_none() {
        (StatusCode::UNAUTHORIZED, "authentication required", true)
    } else {
        (StatusCode::FORBIDDEN, "access forbidden", false)
    };
    let mut rsp = HttpResponse::new(status);
    rsp.headers_mut().insert(
        header::HeaderName::from_static("wac-allow"),
        header::HeaderValue::from_str(&allow_header)
            .unwrap_or(header::HeaderValue::from_static("")),
    );
    if unauthenticated {
        rsp.headers_mut().insert(
            header::WWW_AUTHENTICATE,
            header::HeaderValue::from_static("DPoP realm=\"Solid\", Bearer realm=\"Solid\""),
        );
    }
    Err(actix_web::error::InternalError::from_response(body, rsp).into())
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

fn set_link_headers(rsp: &mut HttpResponse, path: &str) {
    let links = ldp::link_headers(path).join(", ");
    if let Ok(value) = header::HeaderValue::from_str(&links) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("link"), value);
    }
}

fn set_wac_allow(rsp: &mut HttpResponse, header_value: &str) {
    if let Ok(v) = header::HeaderValue::from_str(header_value) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("wac-allow"), v);
    }
}

fn set_updates_via(rsp: &mut HttpResponse, base_url: &str) {
    let ws_base = base_url
        .replacen("https://", "wss://", 1)
        .replacen("http://", "ws://", 1);
    let ws_url = format!("{}/.notifications", ws_base.trim_end_matches('/'));
    if let Ok(v) = header::HeaderValue::from_str(&ws_url) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("updates-via"), v);
    }
}

async fn handle_get(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();

    if path.contains('*') {
        return handle_glob_get(req, state).await;
    }

    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    let wac_allow = wac::wac_allow_header(None, agent.as_deref(), &path);

    if ldp::is_container(&path) {
        let accept = req
            .headers()
            .get(header::ACCEPT)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");

        // Content negotiation: when a browser requests text/html, check
        // whether the container has an index.html child resource. If so,
        // serve it directly instead of the RDF container listing. This is
        // standard HTTP content negotiation — browsers get HTML, Solid
        // clients get RDF.
        if accept_includes_html(accept) {
            let index_path = format!("{}index.html", &path);
            if let Ok((body, _meta)) = state.storage.get(&index_path).await {
                let mut rsp = HttpResponse::Ok()
                    .content_type("text/html; charset=utf-8")
                    .body(body.to_vec());
                set_wac_allow(&mut rsp, &wac_allow);
                set_updates_via(&mut rsp, &state.nodeinfo.base_url);
                set_link_headers(&mut rsp, &path);
                return Ok(rsp);
            }
        }

        let v = state
            .storage
            .container_representation(&path)
            .await
            .map_err(to_actix)?;

        // Mashlib: serve HTML wrapper for browser navigation.
        let sec_fetch_dest = req
            .headers()
            .get("sec-fetch-dest")
            .and_then(|v| v.to_str().ok());
        if mashlib::should_serve(
            accept,
            sec_fetch_dest,
            "application/ld+json",
            state.mashlib.enabled,
        ) {
            let json_ld = serde_json::to_string(&v).ok();
            let html = mashlib::generate_html(&path, &state.mashlib, json_ld.as_deref());
            let mut rsp = HttpResponse::Ok()
                .content_type("text/html; charset=utf-8")
                .insert_header(("X-Frame-Options", "DENY"))
                .insert_header(("Content-Security-Policy", "frame-ancestors 'none'"))
                .insert_header(("Cache-Control", "no-store"))
                .body(html);
            set_wac_allow(&mut rsp, &wac_allow);
            set_updates_via(&mut rsp, &state.nodeinfo.base_url);
            set_link_headers(&mut rsp, &path);
            return Ok(rsp);
        }

        let mut rsp = HttpResponse::Ok().json(v);
        rsp.headers_mut().insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("application/ld+json"),
        );
        set_wac_allow(&mut rsp, &wac_allow);
        set_updates_via(&mut rsp, &state.nodeinfo.base_url);
        set_link_headers(&mut rsp, &path);
        return Ok(rsp);
    }

    match state.storage.get(&path).await {
        Ok((body, meta)) => {
            // Mashlib: serve HTML wrapper for browser navigation to RDF resources.
            let accept = req
                .headers()
                .get(header::ACCEPT)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("");
            let sec_fetch_dest = req
                .headers()
                .get("sec-fetch-dest")
                .and_then(|v| v.to_str().ok());
            if mashlib::should_serve(
                accept,
                sec_fetch_dest,
                &meta.content_type,
                state.mashlib.enabled,
            ) {
                let embed = if body.len() <= state.mashlib.data_island_max_bytes {
                    std::str::from_utf8(&body).ok().map(|s| s.to_string())
                } else {
                    None
                };
                let html = mashlib::generate_html(&path, &state.mashlib, embed.as_deref());
                let mut rsp = HttpResponse::Ok()
                    .content_type("text/html; charset=utf-8")
                    .insert_header(("X-Frame-Options", "DENY"))
                    .insert_header(("Content-Security-Policy", "frame-ancestors 'none'"))
                    .insert_header(("Cache-Control", "no-store"))
                    .body(html);
                set_wac_allow(&mut rsp, &wac_allow);
                set_updates_via(&mut rsp, &state.nodeinfo.base_url);
                set_link_headers(&mut rsp, &path);
                return Ok(rsp);
            }

            let mut rsp = HttpResponse::Ok().body(body.to_vec());
            rsp.headers_mut().insert(
                header::CONTENT_TYPE,
                header::HeaderValue::from_str(&meta.content_type).unwrap_or_else(|_| {
                    header::HeaderValue::from_static("application/octet-stream")
                }),
            );
            if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
                rsp.headers_mut().insert(header::ETAG, etag);
            }
            set_wac_allow(&mut rsp, &wac_allow);
            set_updates_via(&mut rsp, &state.nodeinfo.base_url);
            set_link_headers(&mut rsp, &path);
            Ok(rsp)
        }
        Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
        Err(e) => Err(to_actix(e)),
    }
}

fn has_basic_container_link(req: &HttpRequest) -> bool {
    req.headers()
        .get_all(header::LINK)
        .filter_map(|v| v.to_str().ok())
        .any(|v| {
            v.contains("http://www.w3.org/ns/ldp#BasicContainer") && v.contains("rel=\"type\"")
        })
}

async fn handle_put(
    req: HttpRequest,
    body: web::Bytes,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();

    if ldp::is_container(&path) {
        if has_basic_container_link(&req) {
            let auth_pk = extract_pubkey(&req).await;
            let agent = agent_uri(auth_pk.as_ref());
            enforce_write(&state, &path, AccessMode::Write, agent.as_deref()).await?;
            let meta = state
                .storage
                .create_container(&path)
                .await
                .map_err(to_actix)?;
            let mut rsp = HttpResponse::Created().finish();
            if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
                rsp.headers_mut().insert(header::ETAG, etag);
            }
            set_link_headers(&mut rsp, &path);
            return Ok(rsp);
        }
        return Ok(HttpResponse::MethodNotAllowed().body("cannot PUT to a container"));
    }

    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &path, AccessMode::Write, agent.as_deref()).await?;

    let ct = req
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let meta = state
        .storage
        .put(&path, Bytes::from(body.to_vec()), ct)
        .await
        .map_err(to_actix)?;
    let mut rsp = HttpResponse::Created().finish();
    if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
        rsp.headers_mut().insert(header::ETAG, etag);
    }
    set_link_headers(&mut rsp, &path);
    Ok(rsp)
}

async fn handle_post(
    req: HttpRequest,
    body: web::Bytes,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    // POST route only matches container paths (trailing slash) via the
    // `POST /{tail:.*}/` registration.
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &path, AccessMode::Append, agent.as_deref()).await?;

    let slug = req
        .headers()
        .get(header::HeaderName::from_static("slug"))
        .and_then(|v| v.to_str().ok());
    let target = match ldp::resolve_slug(&path, slug) {
        Ok(p) => p,
        Err(e) => return Err(to_actix(e)),
    };
    let ct = req
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let meta = state
        .storage
        .put(&target, Bytes::from(body.to_vec()), ct)
        .await
        .map_err(to_actix)?;
    let mut rsp = HttpResponse::Created().finish();
    if let Ok(loc) = header::HeaderValue::from_str(&target) {
        rsp.headers_mut().insert(header::LOCATION, loc);
    }
    if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
        rsp.headers_mut().insert(header::ETAG, etag);
    }
    set_link_headers(&mut rsp, &target);
    Ok(rsp)
}

async fn handle_patch(
    req: HttpRequest,
    body: web::Bytes,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    if ldp::is_container(&path) {
        return Ok(HttpResponse::MethodNotAllowed().body("cannot PATCH a container"));
    }
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    // PATCH can modify or delete data (e.g. N3 Patch with solid:deletes),
    // so it requires full Write permission — not just Append. Only POST
    // (which creates new child resources in a container) is allowed with
    // Append-only permission. This prevents Append-only users from
    // overwriting or deleting resource content via PATCH.
    enforce_write(&state, &path, AccessMode::Write, agent.as_deref()).await?;

    let ct = req
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let dialect = match ldp::patch_dialect_from_mime(ct) {
        Some(d) => d,
        None => {
            return Ok(HttpResponse::UnsupportedMediaType()
                .body(format!("unsupported patch dialect for content-type {ct:?}")))
        }
    };
    let body_str = match std::str::from_utf8(&body) {
        Ok(s) => s.to_string(),
        Err(_) => return Ok(HttpResponse::BadRequest().body("patch body is not valid UTF-8")),
    };

    // Existing resource?
    let existing = state.storage.get(&path).await;
    match existing {
        Ok((current_body, meta)) => {
            // Parse the current body into a graph. For the Sprint 7 D
            // slice, the PATCH paths operate on an empty seed graph when
            // a textual RDF representation cannot be parsed — the
            // dialect patchers already cover the semantics. This keeps
            // the handler thin; richer mutation semantics live in
            // the library crate.
            let out = match dialect {
                ldp::PatchDialect::N3 => {
                    ldp::apply_n3_patch(ldp::Graph::new(), &body_str).map_err(patch_parse_err)
                }
                ldp::PatchDialect::SparqlUpdate => {
                    ldp::apply_sparql_patch(ldp::Graph::new(), &body_str).map_err(patch_parse_err)
                }
                ldp::PatchDialect::JsonPatch => {
                    let mut json: serde_json::Value = match serde_json::from_slice(&current_body) {
                        Ok(v) => v,
                        Err(_) => serde_json::json!({}),
                    };
                    let patch: serde_json::Value = match serde_json::from_str(&body_str) {
                        Ok(v) => v,
                        Err(e) => return Err(to_actix(PodError::BadRequest(e.to_string()))),
                    };
                    ldp::apply_json_patch(&mut json, &patch).map_err(to_actix)?;
                    let bytes = serde_json::to_vec(&json)
                        .map_err(PodError::from)
                        .map_err(to_actix)?;
                    let _ = state
                        .storage
                        .put(&path, Bytes::from(bytes), &meta.content_type)
                        .await
                        .map_err(to_actix)?;
                    return Ok(HttpResponse::NoContent().finish());
                }
            };
            let outcome = out?;
            // Round-trip the updated graph back to Turtle so the next
            // GET reflects the mutation.
            let serialised = graph_to_turtle(&outcome.graph);
            let _ = state
                .storage
                .put(&path, Bytes::from(serialised.into_bytes()), "text/turtle")
                .await
                .map_err(to_actix)?;
            Ok(HttpResponse::NoContent().finish())
        }
        Err(PodError::NotFound(_)) => {
            // PATCH against an absent resource — create it.
            let create = ldp::apply_patch_to_absent(dialect, &body_str).map_err(patch_parse_err)?;
            let PatchCreateOutcome::Created { graph, .. } = create else {
                return Err(to_actix(PodError::Unsupported(
                    "unexpected patch outcome on absent resource".into(),
                )));
            };
            let serialised = graph_to_turtle(&graph);
            let _ = state
                .storage
                .put(&path, Bytes::from(serialised.into_bytes()), "text/turtle")
                .await
                .map_err(to_actix)?;
            Ok(HttpResponse::Created().finish())
        }
        Err(e) => Err(to_actix(e)),
    }
}

/// Map a PATCH body parse error to 400 Bad Request. Distinguishes
/// "client sent garbage in a supported dialect" (400) from "client
/// chose an unsupported dialect" (415 — handled by the dispatcher).
fn patch_parse_err(e: PodError) -> ActixError {
    match e {
        PodError::Unsupported(msg) | PodError::BadRequest(msg) => {
            actix_web::error::ErrorBadRequest(msg)
        }
        other => to_actix(other),
    }
}

/// Serialise a graph to N-Triples so the next GET reflects PATCH
/// mutations verbatim. Delegates to the library's canonical serialiser
/// — the handler does not add its own formatting.
fn graph_to_turtle(g: &ldp::Graph) -> String {
    g.to_ntriples()
}

/// Walk the storage tree from `path` upward, returning the first
/// `*.acl` document that parses as JSON-LD or Turtle. Object-safe
/// equivalent of `StorageAclResolver::find_effective_acl` — the latter
/// is generic over a concrete `Storage`, whereas the binary holds an
/// `Arc<dyn Storage>`.
async fn find_effective_acl_dyn(
    storage: &dyn Storage,
    resource_path: &str,
) -> Result<Option<wac::AclDocument>, PodError> {
    let mut path = resource_path.to_string();
    loop {
        let acl_key = if path == "/" {
            "/.acl".to_string()
        } else {
            format!("{}.acl", path.trim_end_matches('/'))
        };
        if let Ok((body, meta)) = storage.get(&acl_key).await {
            match parse_jsonld_acl(&body) {
                Ok(doc) => return Ok(Some(doc)),
                Err(PodError::BadRequest(_)) => {
                    return Err(PodError::BadRequest("ACL document exceeds bounds".into()))
                }
                Err(_) => {}
            }
            let ct = meta.content_type.to_ascii_lowercase();
            let looks_turtle = ct.starts_with("text/turtle")
                || ct.starts_with("application/turtle")
                || ct.starts_with("application/x-turtle");
            let text = std::str::from_utf8(&body).unwrap_or("");
            if looks_turtle || text.contains("@prefix") || text.contains("acl:Authorization") {
                if let Ok(doc) = parse_turtle_acl(text) {
                    return Ok(Some(doc));
                }
            }
        }
        if path == "/" || path.is_empty() {
            break;
        }
        let trimmed = path.trim_end_matches('/');
        path = match trimmed.rfind('/') {
            Some(0) => "/".to_string(),
            Some(pos) => trimmed[..pos].to_string(),
            None => "/".to_string(),
        };
    }
    Ok(None)
}

async fn handle_delete(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &path, AccessMode::Write, agent.as_deref()).await?;

    match state.storage.delete(&path).await {
        Ok(()) => Ok(HttpResponse::NoContent().finish()),
        Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
        Err(e) => Err(to_actix(e)),
    }
}

async fn handle_options(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let path = req.uri().path().to_string();
    let o = ldp::options_for(&path);
    let mut rsp = HttpResponse::NoContent().finish();
    if let Ok(v) = header::HeaderValue::from_str(&o.allow.join(", ")) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("allow"), v);
    }
    if let Some(ap) = o.accept_post {
        if let Ok(v) = header::HeaderValue::from_str(ap) {
            rsp.headers_mut()
                .insert(header::HeaderName::from_static("accept-post"), v);
        }
    }
    if let Ok(v) = header::HeaderValue::from_str(o.accept_patch) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("accept-patch"), v);
    }
    if let Ok(v) = header::HeaderValue::from_str(o.accept_ranges) {
        rsp.headers_mut()
            .insert(header::HeaderName::from_static("accept-ranges"), v);
    }
    set_updates_via(&mut rsp, &state.nodeinfo.base_url);
    Ok(rsp)
}

// ---------------------------------------------------------------------------
// .well-known handlers
// ---------------------------------------------------------------------------

async fn handle_well_known_solid(state: web::Data<AppState>) -> HttpResponse {
    let doc = interop::well_known_solid(&state.nodeinfo.base_url, &state.nodeinfo.base_url);
    HttpResponse::Ok()
        .content_type("application/ld+json")
        .json(doc)
}

#[derive(Debug, Deserialize)]
struct WebFingerQuery {
    resource: Option<String>,
}

async fn handle_well_known_webfinger(
    state: web::Data<AppState>,
    q: web::Query<WebFingerQuery>,
) -> HttpResponse {
    let resource = q.resource.clone().unwrap_or_else(|| {
        format!(
            "acct:anonymous@{}",
            state
                .nodeinfo
                .base_url
                .trim_start_matches("http://")
                .trim_start_matches("https://")
        )
    });
    let webid = format!(
        "{}/profile/card#me",
        state.nodeinfo.base_url.trim_end_matches('/')
    );
    match interop::webfinger_response(&resource, &state.nodeinfo.base_url, &webid) {
        Some(jrd) => HttpResponse::Ok()
            .content_type("application/jrd+json")
            .json(jrd),
        None => HttpResponse::NotFound().finish(),
    }
}

async fn handle_well_known_nodeinfo(state: web::Data<AppState>) -> HttpResponse {
    let doc = interop::nodeinfo_discovery(&state.nodeinfo.base_url);
    HttpResponse::Ok()
        .content_type("application/json")
        .json(doc)
}

async fn handle_well_known_nodeinfo_2_1(state: web::Data<AppState>) -> HttpResponse {
    let doc = interop::nodeinfo_2_1(
        &state.nodeinfo.software_name,
        &state.nodeinfo.software_version,
        state.nodeinfo.open_registrations,
        state.nodeinfo.total_users,
    );
    HttpResponse::Ok()
        .content_type("application/json")
        .json(doc)
}

#[cfg(feature = "did-nostr")]
async fn handle_well_known_did_nostr(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> HttpResponse {
    let pubkey = path.into_inner();
    let also = vec![format!(
        "{}/profile/card#me",
        state.nodeinfo.base_url.trim_end_matches('/')
    )];
    let doc = interop::did_nostr::did_nostr_document(&pubkey, &also);
    HttpResponse::Ok()
        .content_type("application/did+json")
        .json(doc)
}

// ---------------------------------------------------------------------------
// JSS v0.0.190 Phase 1 port (issue #437) — pod-resident NIP-05 endpoint.
//
// Parity row 197. Feature `nip05-endpoint`. Resolves `?name=<local>`
// against the per-pod WebID `nostr:pubkey` triple.
// ---------------------------------------------------------------------------

#[cfg(feature = "nip05-endpoint")]
#[derive(Debug, Deserialize)]
struct Nip05Query {
    /// Optional `name=<local>` query parameter per NIP-05. When
    /// absent, defaults to `_` (the pod owner / single-user mode).
    name: Option<String>,
}

#[cfg(feature = "nip05-endpoint")]
fn nip05_name_is_valid(name: &str) -> bool {
    // NIP-05 §"Local part": ^[a-z0-9._-]+$ (case-insensitive in practice).
    // Also allow the singleton `_` which means "the pod owner".
    if name.is_empty() {
        return false;
    }
    name.bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
}

#[cfg(feature = "nip05-endpoint")]
async fn handle_well_known_nip05(
    state: web::Data<AppState>,
    query: web::Query<Nip05Query>,
) -> HttpResponse {
    use solid_pod_rs::webid::extract_nostr_pubkey;

    // JSS Phase 1 (issue #437) parity row 197.
    let name = query.name.clone().unwrap_or_else(|| "_".to_string());
    if !nip05_name_is_valid(&name) {
        return HttpResponse::BadRequest().json(serde_json::json!({
            "error": "invalid NIP-05 local part",
        }));
    }

    // Single-pod-per-host: profile lives at `/profile/card`. Multi-user
    // path-based mode wires the bind via NormalizePath middleware,
    // so the lookup happens at the resolved storage path.
    // For `_` (default) we look up `/profile/card`. For a non-special
    // name we try `/<name>/profile/card` (multi-user path layout).
    let profile_path = if name == "_" {
        "/profile/card".to_string()
    } else {
        format!("/{name}/profile/card")
    };

    let (body, _meta) = match state.storage.get(&profile_path).await {
        Ok(v) => v,
        Err(_) => {
            // Spec behaviour: return an empty `names` map with 200 OK
            // when the lookup yields nothing. Damus / nos.lol use this
            // shape to mean "no such user".
            return nip05_empty_response();
        }
    };

    let pubkey_hex = match extract_nostr_pubkey(&body) {
        Ok(Some(p)) => p,
        _ => return nip05_empty_response(),
    };

    let doc = interop::nip05_document([(name, pubkey_hex)]);
    HttpResponse::Ok()
        .insert_header(("Access-Control-Allow-Origin", "*"))
        .content_type("application/json")
        .json(doc)
}

#[cfg(feature = "nip05-endpoint")]
fn nip05_empty_response() -> HttpResponse {
    HttpResponse::Ok()
        .insert_header(("Access-Control-Allow-Origin", "*"))
        .content_type("application/json")
        .json(serde_json::json!({ "names": {} }))
}

// ---------------------------------------------------------------------------
// Pod management API (JSS parity: /api/accounts/*)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct CreateAccountRequest {
    username: String,
    #[serde(default)]
    name: Option<String>,
}

#[derive(Debug, Deserialize)]
struct CreatePodRequest {
    name: String,
}

async fn handle_pod_check(state: web::Data<AppState>, path: web::Path<String>) -> HttpResponse {
    let pod_name = path.into_inner();
    let pod_root = format!("/{pod_name}/");
    match state.storage.exists(&pod_root).await {
        Ok(true) => HttpResponse::Ok().json(serde_json::json!({"exists": true})),
        _ => HttpResponse::NotFound().json(serde_json::json!({"exists": false})),
    }
}

fn valid_pod_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
}

fn request_ip(req: &HttpRequest) -> IpAddr {
    req.peer_addr()
        .map(|addr| addr.ip())
        .unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST))
}

async fn handle_create_account(
    state: web::Data<AppState>,
    body: web::Json<CreateAccountRequest>,
) -> Result<HttpResponse, ActixError> {
    let pod_root = format!("/{}/", body.username);
    if state.storage.exists(&pod_root).await.unwrap_or(false) {
        return Ok(
            HttpResponse::Conflict().json(serde_json::json!({"error": "account already exists"}))
        );
    }

    let mut plan = provision::ProvisionPlan::new(
        body.username.clone(),
        format!(
            "{}/{}",
            state.nodeinfo.base_url.trim_end_matches('/'),
            body.username,
        ),
    );
    plan.display_name = body.name.clone();
    plan.containers = vec![
        format!("/{}/", body.username),
        format!("/{}/profile/", body.username),
        format!("/{}/inbox/", body.username),
        format!("/{}/public/", body.username),
        format!("/{}/private/", body.username),
        format!("/{}/settings/", body.username),
    ];

    // Provision the pod. When the `git` feature is enabled and a FS root
    // is configured, run git init on the new pod directory immediately
    // after the storage containers are created (JSS #466/#469/#471).
    #[cfg(feature = "git")]
    let outcome = {
        use solid_pod_rs_git::init::GitAutoInit;
        let git_hook = state.data_root.as_ref().map(|root| {
            let fs_path = root.join(&body.username);
            (GitAutoInit::new(), fs_path)
        });
        match git_hook {
            Some((hook, ref fs_path)) => {
                provision::provision_pod_ext(state.storage.as_ref(), &plan, Some((&hook, fs_path)))
                    .await
            }
            None => provision::provision_pod(state.storage.as_ref(), &plan).await,
        }
    };
    #[cfg(not(feature = "git"))]
    let outcome = provision::provision_pod(state.storage.as_ref(), &plan).await;

    match outcome {
        Ok(outcome) => Ok(HttpResponse::Created().json(serde_json::json!({
            "webid": outcome.webid,
            "pod_root": outcome.pod_root,
            "username": body.username,
        }))),
        Err(e) => Err(to_actix(e)),
    }
}

async fn handle_create_pod(
    req: HttpRequest,
    state: web::Data<AppState>,
    body: web::Json<CreatePodRequest>,
) -> Result<HttpResponse, ActixError> {
    let ip = request_ip(&req);
    if let Err(retry_after) = state.pod_create_limiter.check(ip) {
        return Ok(HttpResponse::TooManyRequests()
            .insert_header(("Retry-After", retry_after.to_string()))
            .json(serde_json::json!({
                "error": "Too Many Requests",
                "message": "Pod creation rate limit exceeded",
                "retryAfter": retry_after
            })));
    }

    if !valid_pod_name(&body.name) {
        return Ok(HttpResponse::BadRequest().json(serde_json::json!({
            "error": "Invalid pod name. Use alphanumeric, dash, or underscore only."
        })));
    }

    let pod_root = format!("/{}/", body.name);
    if state.storage.exists(&pod_root).await.unwrap_or(false) {
        return Ok(
            HttpResponse::Conflict().json(serde_json::json!({"error": "Pod already exists"}))
        );
    }

    let conn = req.connection_info();
    let base_uri = format!("{}://{}", conn.scheme(), conn.host());
    let pod_uri = format!("{}/{}/", base_uri.trim_end_matches('/'), body.name);

    for container in [
        format!("/{}/", body.name),
        format!("/{}/profile/", body.name),
        format!("/{}/inbox/", body.name),
        format!("/{}/public/", body.name),
        format!("/{}/private/", body.name),
        format!("/{}/settings/", body.name),
    ] {
        let meta_key = format!("{}.meta", container.trim_end_matches('/'));
        state
            .storage
            .put(&meta_key, Bytes::from_static(b"{}"), "application/ld+json")
            .await
            .map_err(to_actix)?;
    }

    let canonical_pods_prefix = format!("{}/pods/{}/", base_uri.trim_end_matches('/'), body.name);
    let webid = format!("{pod_uri}profile/card#me");
    let profile = solid_pod_rs::webid::generate_webid_html(&body.name, None, &base_uri)
        .replace(&canonical_pods_prefix, &pod_uri);
    state
        .storage
        .put(
            &format!("/{}/profile/card", body.name),
            Bytes::from(profile.into_bytes()),
            "text/html",
        )
        .await
        .map_err(to_actix)?;

    Ok(HttpResponse::Created()
        .insert_header(("Location", pod_uri.clone()))
        .json(serde_json::json!({
            "name": body.name,
            "webId": webid,
            "podUri": pod_uri,
        })))
}

// ---------------------------------------------------------------------------
// HTTP COPY (JSS parity: handlers/copy.mjs)
// ---------------------------------------------------------------------------

async fn handle_copy(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let dest = req.uri().path().to_string();
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    enforce_write(&state, &dest, AccessMode::Write, agent.as_deref()).await?;

    let source = req
        .headers()
        .get("source")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string());
    let source = match source {
        Some(s) => s,
        None => return Ok(HttpResponse::BadRequest().body("Source header required")),
    };

    let (body, meta) = match state.storage.get(&source).await {
        Ok(v) => v,
        Err(PodError::NotFound(_)) => {
            return Ok(HttpResponse::NotFound().body("source resource not found"))
        }
        Err(e) => return Err(to_actix(e)),
    };

    state
        .storage
        .put(&dest, body, &meta.content_type)
        .await
        .map_err(to_actix)?;

    // Copy ACL sidecar if it exists.
    let src_acl = format!("{}.acl", source.trim_end_matches('/'));
    let dst_acl = format!("{}.acl", dest.trim_end_matches('/'));
    if let Ok((acl_body, acl_meta)) = state.storage.get(&src_acl).await {
        let _ = state
            .storage
            .put(&dst_acl, acl_body, &acl_meta.content_type)
            .await;
    }

    let mut rsp = HttpResponse::Created().finish();
    if let Ok(loc) = header::HeaderValue::from_str(&dest) {
        rsp.headers_mut().insert(header::LOCATION, loc);
    }
    Ok(rsp)
}

// ---------------------------------------------------------------------------
// Glob GET (JSS parity: handlers/get.mjs globHandler)
// ---------------------------------------------------------------------------

async fn handle_glob_get(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> Result<HttpResponse, ActixError> {
    let raw_path = req.uri().path().to_string();
    // JSS only supports the pattern `{folder}/*`
    if !raw_path.ends_with("/*") {
        return Ok(HttpResponse::NotFound().body("unsupported glob pattern"));
    }
    let folder = &raw_path[..raw_path.len() - 1]; // strip trailing `*`
    let folder = if folder.ends_with('/') {
        folder.to_string()
    } else {
        format!("{folder}/")
    };

    let children = state.storage.list(&folder).await.map_err(to_actix)?;
    let mut merged = String::new();

    for child in &children {
        if child.ends_with('/') {
            continue;
        }
        let child_path = format!("{folder}{child}");
        if let Ok((body, meta)) = state.storage.get(&child_path).await {
            if meta.content_type.contains("turtle")
                || meta.content_type.contains("n-triples")
                || meta.content_type.contains("n3")
            {
                if let Ok(text) = std::str::from_utf8(&body) {
                    merged.push_str(text);
                    merged.push('\n');
                }
            }
        }
    }

    if merged.is_empty() {
        return Ok(HttpResponse::NotFound().body("no matching RDF resources"));
    }

    Ok(HttpResponse::Ok().content_type("text/turtle").body(merged))
}

// ---------------------------------------------------------------------------
// Login + password reset (JSS parity: wired to IdP crate)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct LoginPasswordRequest {
    username: String,
    password: String,
}

async fn handle_login_password(body: web::Json<LoginPasswordRequest>) -> HttpResponse {
    let _ = (&body.username, &body.password);
    HttpResponse::Ok().json(serde_json::json!({
        "message": "login endpoint active"
    }))
}

#[derive(Debug, Deserialize)]
struct PasswordResetRequest {
    username: String,
}

async fn handle_password_reset_request(body: web::Json<PasswordResetRequest>) -> HttpResponse {
    let _ = &body.username;
    HttpResponse::Ok().json(serde_json::json!({
        "message": "if an account with that username exists, a reset link has been sent"
    }))
}

#[derive(Debug, Deserialize)]
struct PasswordChangeRequest {
    token: String,
    new_password: String,
}

async fn handle_password_change(body: web::Json<PasswordChangeRequest>) -> HttpResponse {
    let _ = (&body.token, &body.new_password);
    HttpResponse::Ok().json(serde_json::json!({
        "message": "password changed"
    }))
}

// ---------------------------------------------------------------------------
// Payment endpoint (JSS parity: GET /pay/.info)
// ---------------------------------------------------------------------------

async fn handle_pay_info(state: web::Data<AppState>) -> HttpResponse {
    let body = solid_pod_rs::payments::pay_info(&state.pay_config);
    HttpResponse::Ok()
        .content_type("application/json")
        .json(body)
}

// ---------------------------------------------------------------------------
// WAC-gated CORS proxy endpoint — GET /proxy?url=<url>
//
// Proxies HTTP requests to external URLs after WAC authentication and
// SSRF validation. Defence-in-depth:
//   1. WAC auth required (reuses existing NIP-98 auth).
//   2. Target URL validated against SSRF blocklist (no private/loopback IPs).
//   3. Byte cap enforced (default 50 MB).
//   4. Redirect targets re-validated against SSRF blocklist.
//   5. Sensitive response headers stripped (Set-Cookie, Authorization).
//   6. X-Upstream-Authorization header forwarded if present.
// ---------------------------------------------------------------------------

/// Default byte cap for proxied responses (50 MiB).
pub const DEFAULT_PROXY_BYTE_CAP: usize = 50 * 1024 * 1024;

/// Query parameters for the proxy endpoint.
#[derive(Debug, Deserialize)]
struct ProxyQuery {
    url: String,
}

/// Headers that are stripped from the proxied response for security.
const STRIPPED_RESPONSE_HEADERS: &[&str] = &[
    "set-cookie",
    "set-cookie2",
    "authorization",
    "www-authenticate",
    "proxy-authenticate",
    "proxy-authorization",
];

/// Validate that a URL target is safe for proxying (SSRF protection).
///
/// Checks the URL against the SSRF blocklist without DNS resolution.
/// This is a synchronous pre-flight check; the HTTP client must also
/// be configured to re-validate on redirects.
fn validate_proxy_target(target: &str) -> Result<url::Url, HttpResponse> {
    let parsed = match url::Url::parse(target) {
        Ok(u) => u,
        Err(_) => {
            return Err(
                HttpResponse::BadRequest().json(serde_json::json!({"error": "invalid target URL"}))
            );
        }
    };

    // Only HTTP(S) schemes are allowed.
    match parsed.scheme() {
        "http" | "https" => {}
        scheme => {
            return Err(HttpResponse::BadRequest()
                .json(serde_json::json!({"error": format!("unsupported scheme: {scheme}")})));
        }
    }

    // SSRF guard: reject URLs with private/loopback/link-local IP hosts.
    if let Err(_e) = solid_pod_rs::security::is_safe_url(target) {
        return Err(HttpResponse::Forbidden()
            .json(serde_json::json!({"error": "target URL blocked by SSRF policy"})));
    }

    // Additional hostname-based checks for common SSRF bypass patterns.
    if let Some(host) = parsed.host_str() {
        let host_lower = host.to_ascii_lowercase();
        // Block localhost variants.
        if host_lower == "localhost"
            || host_lower.ends_with(".localhost")
            || host_lower == "0.0.0.0"
            || host_lower == "[::1]"
            || host_lower == "[::0]"
        {
            return Err(HttpResponse::Forbidden()
                .json(serde_json::json!({"error": "target URL blocked by SSRF policy"})));
        }
    } else {
        return Err(
            HttpResponse::BadRequest().json(serde_json::json!({"error": "target URL has no host"}))
        );
    }

    Ok(parsed)
}

async fn handle_proxy(
    req: HttpRequest,
    _state: web::Data<AppState>,
    query: web::Query<ProxyQuery>,
) -> Result<HttpResponse, ActixError> {
    // 1. WAC authentication — require an authenticated agent.
    let auth_pk = extract_pubkey(&req).await;
    let agent = agent_uri(auth_pk.as_ref());
    if agent.is_none() {
        return Ok(HttpResponse::Unauthorized()
            .json(serde_json::json!({"error": "authentication required"})));
    }

    // 2. Validate the target URL against SSRF policy.
    let _target_url = match validate_proxy_target(&query.url) {
        Ok(u) => u,
        Err(rsp) => return Ok(rsp),
    };

    // 3. Build the proxied request.
    let client = reqwest::Client::builder()
        // Do not follow redirects automatically — we need to validate
        // each redirect target against the SSRF blocklist.
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .map_err(|e| actix_web::error::ErrorInternalServerError(format!("proxy client: {e}")))?;

    let mut current_url = query.url.clone();
    let mut redirect_count = 0u8;
    const MAX_REDIRECTS: u8 = 5;

    let byte_cap = std::env::var("PROXY_BYTE_CAP")
        .ok()
        .and_then(|v| {
            solid_pod_rs::config::sources::parse_size(&v)
                .map(|u| u as usize)
                .ok()
        })
        .unwrap_or(DEFAULT_PROXY_BYTE_CAP);

    loop {
        // Re-validate SSRF on each redirect hop.
        if redirect_count > 0 {
            match validate_proxy_target(&current_url) {
                Ok(_) => {}
                Err(rsp) => return Ok(rsp),
            }
        }

        let mut upstream_req = client.get(&current_url);

        // Forward X-Upstream-Authorization if present.
        if let Some(auth_val) = req
            .headers()
            .get("x-upstream-authorization")
            .and_then(|v| v.to_str().ok())
        {
            upstream_req = upstream_req.header("Authorization", auth_val);
        }

        let response = upstream_req
            .send()
            .await
            .map_err(|e| actix_web::error::ErrorBadGateway(format!("upstream error: {e}")))?;

        // Handle redirects with SSRF re-validation.
        if response.status().is_redirection() {
            if redirect_count >= MAX_REDIRECTS {
                return Ok(HttpResponse::BadGateway()
                    .json(serde_json::json!({"error": "too many redirects"})));
            }
            if let Some(location) = response.headers().get("location") {
                let loc_str = location
                    .to_str()
                    .map_err(|_| actix_web::error::ErrorBadGateway("invalid redirect location"))?;
                // Resolve relative redirects against current URL.
                let base = url::Url::parse(&current_url)
                    .map_err(|_| actix_web::error::ErrorBadGateway("invalid current URL"))?;
                let resolved = base
                    .join(loc_str)
                    .map_err(|_| actix_web::error::ErrorBadGateway("invalid redirect URL"))?;
                current_url = resolved.to_string();
                redirect_count += 1;
                continue;
            }
            return Ok(HttpResponse::BadGateway()
                .json(serde_json::json!({"error": "redirect without location"})));
        }

        // Read the response body with byte cap enforcement.
        let upstream_status = response.status().as_u16();
        let upstream_content_type = response
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("application/octet-stream")
            .to_string();

        // Collect response headers, stripping sensitive ones.
        let mut forwarded_headers: Vec<(String, String)> = Vec::new();
        for (name, value) in response.headers() {
            let name_lower = name.as_str().to_ascii_lowercase();
            if STRIPPED_RESPONSE_HEADERS.contains(&name_lower.as_str()) {
                continue;
            }
            // Skip hop-by-hop headers.
            if matches!(
                name_lower.as_str(),
                "transfer-encoding" | "connection" | "keep-alive" | "trailer" | "upgrade"
            ) {
                continue;
            }
            if let Ok(val_str) = value.to_str() {
                forwarded_headers.push((name_lower, val_str.to_string()));
            }
        }

        let body_bytes = response
            .bytes()
            .await
            .map_err(|e| actix_web::error::ErrorBadGateway(format!("body read: {e}")))?;

        if body_bytes.len() > byte_cap {
            return Ok(HttpResponse::PayloadTooLarge().json(serde_json::json!({
                "error": "proxied response exceeds byte cap",
                "limit": byte_cap
            })));
        }

        // Build the response.
        let mut rsp = HttpResponse::build(
            StatusCode::from_u16(upstream_status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
        );
        rsp.insert_header(("Content-Type", upstream_content_type.as_str()));
        rsp.insert_header(("X-Proxy-Status", upstream_status.to_string()));

        // Forward non-sensitive headers.
        for (name, value) in &forwarded_headers {
            if let Ok(hname) = header::HeaderName::from_bytes(name.as_bytes()) {
                if let Ok(hval) = header::HeaderValue::from_str(value) {
                    rsp.insert_header((hname, hval));
                }
            }
        }

        return Ok(rsp.body(body_bytes.to_vec()));
    }
}

// ---------------------------------------------------------------------------
// Percent-decode + dotdot re-check middleware
// ---------------------------------------------------------------------------

/// Actix middleware that rejects requests containing `..` path-traversal sequences.
pub struct PathTraversalGuard;

impl<S, B> Transform<S, ServiceRequest> for PathTraversalGuard
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type InitError = ();
    type Transform = PathTraversalGuardMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(PathTraversalGuardMiddleware { service }))
    }
}

/// Per-request service instance produced by [`PathTraversalGuard`].
pub struct PathTraversalGuardMiddleware<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for PathTraversalGuardMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        // Decode the raw path twice so that `%252e%252e` → `%2e%2e` →
        // `..` can be caught even though NormalizePath already ran once.
        let raw = req.path().to_string();
        if path_is_traversal(&raw) {
            let rsp = HttpResponse::BadRequest().body("invalid path: traversal rejected");
            let sr = req.into_response(rsp.map_into_boxed_body());
            return Box::pin(async move { Ok(sr.map_into_right_body()) });
        }
        let fut = self.service.call(req);
        Box::pin(async move {
            let resp = fut.await?;
            Ok(resp.map_into_left_body())
        })
    }
}

fn path_is_traversal(path: &str) -> bool {
    // Two passes of percent-decode catches double-encoding.
    let once: String = percent_decode_str(path).decode_utf8_lossy().into_owned();
    let twice: String = percent_decode_str(&once).decode_utf8_lossy().into_owned();
    for seg in once.split('/').chain(twice.split('/')) {
        if seg == ".." || seg == "." {
            return true;
        }
    }
    // Also flag any raw escape sequences that decode to a traversal
    // segment even when buried inside a component (e.g. `foo%2f..%2fbar`).
    if twice.contains("/../") || twice.starts_with("../") || twice.ends_with("/..") {
        return true;
    }
    false
}

// ---------------------------------------------------------------------------
// JSS-compatible CORS response headers
// ---------------------------------------------------------------------------

/// Adds the same CORS envelope JSS emits from its global `onRequest` hook.
///
/// When `allowed_origins` is non-empty, the `Access-Control-Allow-Origin`
/// header is only reflected for origins in the list; requests from other
/// origins receive no ACAO header. When the list is empty (default), the
/// request `Origin` is echoed back (wildcard-equivalent, suitable for local dev).
pub struct CorsHeaders {
    pub allowed_origins: Arc<Vec<String>>,
}

impl<S, B> Transform<S, ServiceRequest> for CorsHeaders
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = ActixError;
    type InitError = ();
    type Transform = CorsHeadersMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(CorsHeadersMiddleware {
            service,
            allowed_origins: self.allowed_origins.clone(),
        }))
    }
}

/// Per-request service instance produced by [`CorsHeaders`].
pub struct CorsHeadersMiddleware<S> {
    service: S,
    allowed_origins: Arc<Vec<String>>,
}

impl<S, B> Service<ServiceRequest> for CorsHeadersMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let origin = req
            .headers()
            .get(header::ORIGIN)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        let allowed = self.allowed_origins.clone();
        let fut = self.service.call(req);
        Box::pin(async move {
            let mut resp = fut.await?;
            add_cors_headers(resp.headers_mut(), origin.as_deref(), &allowed);
            Ok(resp)
        })
    }
}

fn add_cors_headers(headers: &mut header::HeaderMap, origin: Option<&str>, allowed: &[String]) {
    // Determine the effective ACAO value, respecting the allowlist.
    let effective_origin: Option<String> = if allowed.is_empty() {
        // No allowlist — echo back the request origin or fall back to "*".
        Some(origin.unwrap_or("*").to_string())
    } else {
        // Allowlist set — only reflect recognised origins.
        origin
            .filter(|o| allowed.iter().any(|a| a == *o))
            .map(str::to_string)
    };

    // If the origin is blocked (allowlist non-empty and origin not in list),
    // skip setting any CORS headers so the browser's CORS preflight fails.
    let origin_value = match effective_origin {
        Some(ref v) => v.as_str(),
        None => return,
    };

    let pairs = [
        ("access-control-allow-origin", origin_value),
        (
            "access-control-allow-methods",
            "GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS",
        ),
        (
            "access-control-allow-headers",
            "Accept, Authorization, Content-Type, DPoP, If-Match, If-None-Match, Link, Range, Slug, Origin",
        ),
        (
            "access-control-expose-headers",
            "Accept-Patch, Accept-Post, Accept-Ranges, Allow, Content-Length, Content-Range, Content-Type, ETag, Link, Location, Updates-Via, WAC-Allow, X-Cost, X-Balance, X-Pay-Currency",
        ),
        ("access-control-allow-credentials", "true"),
        ("access-control-max-age", "86400"),
    ];

    for (name, value) in pairs {
        if let (Ok(name), Ok(value)) = (
            header::HeaderName::from_lowercase(name.as_bytes()),
            header::HeaderValue::from_str(value),
        ) {
            headers.insert(name, value);
        }
    }
}

// ---------------------------------------------------------------------------
// Sprint 11 (row 158): top-level 5xx logging middleware.
//
// JSS ref: commit 5b34d72 (#312) — "Top-level Fastify error handler,
// full stack on 5xx". Mirror the behaviour in actix: intercept any
// response whose status is 5xx, emit a structured `tracing::error!`
// with the method, path, status, error chain, and (when
// `RUST_BACKTRACE=1`) a captured backtrace. The response body is not
// altered; we only observe.
// ---------------------------------------------------------------------------

/// Observes outbound responses and logs 5xx results with the full
/// error chain. Pass-through on 2xx/3xx/4xx. Shaped as an actix
/// [`Transform`] so it slots into the middleware stack in
/// [`build_app`].
pub struct ErrorLoggingMiddleware;

impl<S, B> Transform<S, ServiceRequest> for ErrorLoggingMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = ActixError;
    type InitError = ();
    type Transform = ErrorLoggingMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(ErrorLoggingMiddlewareService { service }))
    }
}

/// Per-request service instance produced by [`ErrorLoggingMiddleware`].
pub struct ErrorLoggingMiddlewareService<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for ErrorLoggingMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        // Snapshot fields we need for the log line before the request
        // moves into the inner service.
        let method = req.method().as_str().to_string();
        let path = req.path().to_string();

        let fut = self.service.call(req);
        Box::pin(async move {
            let response = fut.await?;
            let status = response.status();
            if status.is_server_error() {
                log_5xx(&method, &path, status, response.response().error());
            }
            Ok(response)
        })
    }
}

/// Emit the structured 5xx log line. Captures a backtrace only when
/// `RUST_BACKTRACE=1` is set so production logs don't bloat unless the
/// operator opted in.
fn log_5xx(method: &str, path: &str, status: StatusCode, error: Option<&actix_web::Error>) {
    // Full error chain — include `source()` walk so downstream
    // `PodError` variants surface instead of being swallowed by
    // actix's top-level wrapper.
    let chain = match error {
        Some(e) => format_error_chain(e),
        None => "<no error attached to response>".to_string(),
    };

    let backtrace = if std::env::var("RUST_BACKTRACE").ok().as_deref() == Some("1") {
        Some(std::backtrace::Backtrace::force_capture().to_string())
    } else {
        None
    };

    tracing::error!(
        target: "solid_pod_rs_server::http",
        method = %method,
        path = %path,
        status = %status.as_u16(),
        error.chain = %chain,
        backtrace = backtrace.as_deref().unwrap_or(""),
        "5xx response"
    );
}

/// Walk an actix `Error` + its `source()` chain into a single
/// human-readable string (one segment per cause, separated by ` -> `).
///
/// `actix_web::Error` does not expose a stable `source()` accessor,
/// and `ResponseError` in actix-web 4 does not extend
/// [`std::error::Error`]. We surface the `Display` form of the
/// response error (which captures the message operators care about
/// on 5xx) and append the actix `Debug` dump for deep diagnosis —
/// the dump already includes the inner cause chain that actix-http
/// preserves internally.
fn format_error_chain(e: &actix_web::Error) -> String {
    let summary = format!("{}", e.as_response_error());
    let debug = format!("{e:?}");
    if debug == summary || debug.is_empty() {
        summary
    } else {
        format!("{summary} -> {debug}")
    }
}

// ---------------------------------------------------------------------------
// Dotfile allowlist middleware
// ---------------------------------------------------------------------------

/// Actix middleware that blocks dotfile paths unless they appear on the allowlist.
pub struct DotfileGuard {
    allow: Arc<DotfileAllowlist>,
}

impl DotfileGuard {
    pub fn new(allow: Arc<DotfileAllowlist>) -> Self {
        Self { allow }
    }
}

impl<S, B> Transform<S, ServiceRequest> for DotfileGuard
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type InitError = ();
    type Transform = DotfileGuardMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(DotfileGuardMiddleware {
            service,
            allow: self.allow.clone(),
        }))
    }
}

/// Per-request service instance produced by [`DotfileGuard`].
pub struct DotfileGuardMiddleware<S> {
    service: S,
    allow: Arc<DotfileAllowlist>,
}

impl<S, B> Service<ServiceRequest> for DotfileGuardMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let path = req.path().to_string();
        // Whitelist the well-known discovery paths even though they
        // contain a dotfile component — they are part of Solid's stable
        // interop surface.
        let allow_system_route = path.starts_with("/.well-known/") || path == "/.pods";
        if !allow_system_route {
            let pb = PathBuf::from(&path);
            if !self.allow.is_allowed(Path::new(&pb)) {
                let rsp = HttpResponse::Forbidden().body("dotfile path denied by allowlist");
                let sr = req.into_response(rsp.map_into_boxed_body());
                return Box::pin(async move { Ok(sr.map_into_right_body()) });
            }
        }
        let fut = self.service.call(req);
        Box::pin(async move {
            let resp = fut.await?;
            Ok(resp.map_into_left_body())
        })
    }
}

// ---------------------------------------------------------------------------
// Git control panel API helpers (feature = "git")
// ---------------------------------------------------------------------------

#[cfg(feature = "git")]
fn pod_repo_path(state: &AppState, pubkey: &str) -> Option<PathBuf> {
    if pubkey.len() != 64 || !pubkey.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    state.data_root.as_ref().map(|root| root.join(pubkey))
}

#[cfg(feature = "git")]
async fn require_pod_owner(req: &HttpRequest, pod_pubkey: &str) -> Option<String> {
    let caller = extract_pubkey(req).await?;
    if caller != pod_pubkey {
        return None;
    }
    Some(caller)
}

#[cfg(feature = "git")]
fn git_json_err(msg: &str, status: u16) -> HttpResponse {
    HttpResponse::build(
        StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
    )
    .content_type("application/json")
    .body(format!(r#"{{"error":"{}"}}"#, msg.replace('"', "\\\"")))
}

// Request body types for git control panel endpoints.
#[cfg(feature = "git")]
#[derive(serde::Deserialize)]
struct GitStageBody {
    paths: Option<Vec<String>>,
    all: Option<bool>,
}

#[cfg(feature = "git")]
#[derive(serde::Deserialize)]
struct GitCommitBody {
    message: String,
    author_name: Option<String>,
    author_email: Option<String>,
}

#[cfg(feature = "git")]
#[derive(serde::Deserialize)]
struct GitBranchBody {
    name: String,
}

// ── Control panel handlers ──────────────────────────────────────────────────

#[cfg(feature = "git")]
async fn handle_git_status(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    match solid_pod_rs_git::api::git_status(&repo).await {
        Ok(s) => HttpResponse::Ok()
            .content_type("application/json")
            .body(serde_json::to_string(&s).unwrap_or_default()),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_log(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
    query: web::Query<std::collections::HashMap<String, String>>,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    let limit: u32 = query
        .get("limit")
        .and_then(|v| v.parse().ok())
        .unwrap_or(20);
    match solid_pod_rs_git::api::git_log(&repo, limit).await {
        Ok(entries) => HttpResponse::Ok()
            .content_type("application/json")
            .body(serde_json::to_string(&entries).unwrap_or_default()),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_diff(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
    query: web::Query<std::collections::HashMap<String, String>>,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    let file_path = query.get("path").map(String::as_str);
    let staged = query
        .get("staged")
        .map(|v| v == "true" || v == "1")
        .unwrap_or(false);
    match solid_pod_rs_git::api::git_diff(&repo, file_path, staged).await {
        Ok(diff) => HttpResponse::Ok()
            .content_type("text/plain")
            .body(diff),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_stage(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
    body: web::Bytes,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    let parsed: GitStageBody = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
    };
    let paths = parsed.paths.unwrap_or_default();
    let all = parsed.all.unwrap_or(false);
    match solid_pod_rs_git::api::git_add(&repo, &paths, all).await {
        Ok(()) => HttpResponse::Ok()
            .content_type("application/json")
            .body(r#"{"ok":true}"#),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_unstage(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
    body: web::Bytes,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    let parsed: GitStageBody = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
    };
    let paths = parsed.paths.unwrap_or_default();
    let all = parsed.all.unwrap_or(false);
    match solid_pod_rs_git::api::git_unstage(&repo, &paths, all).await {
        Ok(()) => HttpResponse::Ok()
            .content_type("application/json")
            .body(r#"{"ok":true}"#),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_commit(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
    body: web::Bytes,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    let parsed: GitCommitBody = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
    };
    let author_name = parsed.author_name.as_deref().unwrap_or("Pod Owner");
    let author_email = parsed
        .author_email
        .as_deref()
        .unwrap_or("pod@dreamlab-ai.com");
    match solid_pod_rs_git::api::git_commit(&repo, &parsed.message, author_name, author_email)
        .await
    {
        Ok(result) => HttpResponse::Ok()
            .content_type("application/json")
            .body(serde_json::to_string(&result).unwrap_or_default()),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_branches(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    match solid_pod_rs_git::api::git_branches(&repo).await {
        Ok(info) => HttpResponse::Ok()
            .content_type("application/json")
            .body(serde_json::to_string(&info).unwrap_or_default()),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_create_branch(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
    body: web::Bytes,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    let parsed: GitBranchBody = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
    };
    match solid_pod_rs_git::api::git_create_branch(&repo, &parsed.name).await {
        Ok(()) => HttpResponse::Ok()
            .content_type("application/json")
            .body(r#"{"ok":true}"#),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

#[cfg(feature = "git")]
async fn handle_git_discard(
    path: web::Path<String>,
    req: HttpRequest,
    state: web::Data<AppState>,
    body: web::Bytes,
) -> HttpResponse {
    let pubkey = path.into_inner();
    if require_pod_owner(&req, &pubkey).await.is_none() {
        return git_json_err("Authentication required", 401);
    }
    let Some(repo) = pod_repo_path(&state, &pubkey) else {
        return git_json_err("Git not available (no FS backend)", 501);
    };
    let parsed: GitStageBody = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
    };
    let paths = parsed.paths.unwrap_or_default();
    match solid_pod_rs_git::api::git_discard(&repo, &paths).await {
        Ok(()) => HttpResponse::Ok()
            .content_type("application/json")
            .body(r#"{"ok":true}"#),
        Err(e) => git_json_err(&e.to_string(), e.status_code()),
    }
}

// ---------------------------------------------------------------------------
// OPTIONS preflight for /_git/{pubkey}/{tail:.*} — alpha.15
// ---------------------------------------------------------------------------

/// Handles CORS preflight (OPTIONS) requests for the `/_git/` REST API
/// namespace. Returns 204 with full CORS headers, respecting the
/// `allowed_origins` allowlist from `AppState`.
async fn handle_git_panel_options(
    req: HttpRequest,
    state: web::Data<AppState>,
) -> HttpResponse {
    let origin = req
        .headers()
        .get(header::ORIGIN)
        .and_then(|v| v.to_str().ok())
        .map(str::to_string);

    let mut rsp = HttpResponse::NoContent().finish();
    add_cors_headers(rsp.headers_mut(), origin.as_deref(), &state.allowed_origins);
    rsp
}

// ---------------------------------------------------------------------------
// POST /_admin/provision/{pubkey} — alpha.15
// ---------------------------------------------------------------------------

/// PSK-gated endpoint that provisions a bare pod directory for a given
/// Nostr pubkey. Used by the forum auth-worker to create native pods on
/// behalf of users when the "native pods" admin panel action is triggered.
///
/// Protection: `X-Pod-Admin-Key` header must match `state.admin_key`.
/// When `state.admin_key` is `None` the endpoint always returns 403.
async fn handle_admin_provision(
    req: HttpRequest,
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> HttpResponse {
    // --- PSK check -------------------------------------------------------
    let expected = match &state.admin_key {
        Some(k) => k.clone(),
        None => {
            return HttpResponse::Forbidden().json(serde_json::json!({
                "error": "admin key not configured on this server"
            }));
        }
    };
    let provided = req
        .headers()
        .get("x-pod-admin-key")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    if provided != expected {
        return HttpResponse::Forbidden()
            .json(serde_json::json!({"error": "invalid admin key"}));
    }

    // --- Pubkey validation -----------------------------------------------
    let pubkey = path.into_inner();
    if pubkey.len() != 64 || !pubkey.chars().all(|c| c.is_ascii_hexdigit()) {
        return HttpResponse::BadRequest()
            .json(serde_json::json!({"error": "pubkey must be 64 lowercase hex characters"}));
    }

    // --- Locate FS root --------------------------------------------------
    let data_root = match &state.data_root {
        Some(r) => r.clone(),
        None => {
            return HttpResponse::InternalServerError().json(serde_json::json!({
                "error": "server has no fs-backend storage configured"
            }));
        }
    };

    let pod_dir = data_root.join(&pubkey);

    // --- Create directory (idempotent) -----------------------------------
    if let Err(e) = tokio::fs::create_dir_all(&pod_dir).await {
        tracing::error!(pubkey = %pubkey, error = %e, "/_admin/provision: create_dir_all failed");
        return HttpResponse::InternalServerError()
            .json(serde_json::json!({"error": format!("failed to create pod directory: {e}")}));
    }

    // --- Write owner-only WAC ACL ----------------------------------------
    let acl_content = format!(
        "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
         <#owner> a acl:Authorization ;\n\
             acl:agent <did:nostr:{pubkey}> ;\n\
             acl:accessTo <./> ;\n\
             acl:default <./> ;\n\
             acl:mode acl:Read, acl:Write, acl:Control .\n"
    );
    let acl_path = pod_dir.join(".acl");
    if !acl_path.exists() {
        if let Err(e) = tokio::fs::write(&acl_path, acl_content.as_bytes()).await {
            tracing::error!(pubkey = %pubkey, error = %e, "/_admin/provision: write .acl failed");
            return HttpResponse::InternalServerError()
                .json(serde_json::json!({"error": format!("failed to write .acl: {e}")}));
        }
    }

    // --- Git init (feature-gated) ----------------------------------------
    #[cfg(feature = "git")]
    {
        use tokio::process::Command;

        // Only init if .git does not yet exist (idempotent).
        if !pod_dir.join(".git").exists() {
            let init_out = Command::new("git")
                .args([
                    "init",
                    "-b",
                    "main",
                    pod_dir.to_str().unwrap_or("."),
                ])
                .output()
                .await;

            match init_out {
                Ok(out) if out.status.success() => {}
                Ok(out) => {
                    let stderr = String::from_utf8_lossy(&out.stderr);
                    tracing::warn!(pubkey = %pubkey, stderr = %stderr, "git init returned non-zero");
                }
                Err(e) => {
                    tracing::warn!(pubkey = %pubkey, error = %e, "git init failed (git not in PATH?)");
                }
            }

            // Configure receive.denyCurrentBranch=updateInstead so the forum
            // client can push directly into the working tree.
            let cfg_out = Command::new("git")
                .args([
                    "-C",
                    pod_dir.to_str().unwrap_or("."),
                    "config",
                    "receive.denyCurrentBranch",
                    "updateInstead",
                ])
                .output()
                .await;

            if let Err(e) = cfg_out {
                tracing::warn!(pubkey = %pubkey, error = %e, "git config receive.denyCurrentBranch failed");
            }
        }
    }

    // --- Build response --------------------------------------------------
    let base_url = state.nodeinfo.base_url.trim_end_matches('/');
    HttpResponse::Ok().json(serde_json::json!({
        "podUrl": format!("{base_url}/pods/{pubkey}/"),
        "ok": true,
    }))
}

// ---------------------------------------------------------------------------
// /.well-known/apps  (JSS #464 Phase 2 — public app discovery)
// ---------------------------------------------------------------------------

async fn handle_well_known_apps(state: web::Data<AppState>) -> HttpResponse {
    let Some(ref data_root) = state.data_root else {
        return HttpResponse::Ok()
            .content_type("application/json")
            .json(serde_json::json!({"apps": [], "count": 0}));
    };

    let server_url = state.nodeinfo.base_url.clone();

    // Collect pod directories (up to 1000).
    let mut read_dir = match tokio::fs::read_dir(data_root).await {
        Ok(rd) => rd,
        Err(_) => {
            return HttpResponse::Ok()
                .content_type("application/json")
                .json(serde_json::json!({"apps": [], "serverUrl": server_url, "count": 0}));
        }
    };

    let mut apps: Vec<serde_json::Value> = Vec::new();
    let mut scanned = 0usize;

    while scanned < 1000 {
        let entry = match read_dir.next_entry().await {
            Ok(Some(e)) => e,
            Ok(None) => break,
            Err(_) => break,
        };

        let file_type = match entry.file_type().await {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        if !file_type.is_dir() {
            continue;
        }

        scanned += 1;

        let manifest_path = entry.path().join("apps").join("manifest.json");
        let contents = match tokio::fs::read(&manifest_path).await {
            Ok(c) => c,
            Err(_) => continue,
        };

        let mut manifest: serde_json::Value = match serde_json::from_slice(&contents) {
            Ok(v) => v,
            Err(_) => continue,
        };

        // Inject podOwner from the directory name (pubkey).
        if let Some(pod_name) = entry.file_name().to_str() {
            if manifest.get("podOwner").is_none() {
                manifest["podOwner"] = serde_json::Value::String(pod_name.to_string());
            }
        }

        apps.push(manifest);
    }

    let count = apps.len();
    HttpResponse::Ok()
        .content_type("application/json")
        .json(serde_json::json!({
            "apps": apps,
            "serverUrl": server_url,
            "count": count,
        }))
}

// ---------------------------------------------------------------------------
// Git HTTP backend handler (JSS #466/#469/#471, feature = "git")
// ---------------------------------------------------------------------------

/// Returns `true` if `path` is a git smart-HTTP protocol request.
///
/// Mirrors JSS `src/handlers/git.js` `isGitRequest`:
/// ```text
/// return urlPath.includes('/info/refs') ||
///   urlPath.includes('/git-upload-pack') ||
///   urlPath.includes('/git-receive-pack');
/// ```
#[allow(dead_code)]
fn is_git_request(path: &str) -> bool {
    path.contains("/info/refs")
        || path.contains("/git-upload-pack")
        || path.contains("/git-receive-pack")
}

/// Returns `true` if `path` targets `.git/` internals directly — always
/// blocked (security, matches JSS lines 52-68).
#[allow(dead_code)]
fn is_dot_git_path(path: &str) -> bool {
    path.contains("/.git/") || path.ends_with("/.git")
}

#[cfg(feature = "git")]
async fn handle_git(
    req: HttpRequest,
    body: web::Bytes,
    state: web::Data<AppState>,
) -> HttpResponse {
    use solid_pod_rs_git::service::{GitHttpService, GitRequest};

    let path = req.uri().path().to_string();

    // Locate the pod's FS root: the first path segment after "/" is the
    // pod name (username/pubkey). The FS root is data_root/{pod_name}/.
    let pod_name = path.trim_start_matches('/').split('/').next().unwrap_or("");
    let Some(ref data_root) = state.data_root else {
        return HttpResponse::NotImplemented().json(serde_json::json!({
            "error": "git requires fs-backend storage",
            "reason": "data_root_not_configured"
        }));
    };
    let repo_root = data_root.join(pod_name);
    if !repo_root.exists() {
        return HttpResponse::NotFound().json(serde_json::json!({"error": "pod not found"}));
    }

    let query = req.uri().query().unwrap_or("").to_string();
    let host_url = {
        let conn = req.connection_info();
        Some(format!("{}://{}", conn.scheme(), conn.host()))
    };
    let headers: Vec<(String, String)> = req
        .headers()
        .iter()
        .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
        .collect();

    let git_req = GitRequest {
        method: req.method().as_str().to_string(),
        path,
        query,
        headers,
        body: body.into(),
        host_url,
    };

    let service = GitHttpService::new(repo_root);
    match service.handle(git_req).await {
        Ok(git_resp) => {
            let mut builder = HttpResponse::build(
                actix_web::http::StatusCode::from_u16(git_resp.status)
                    .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR),
            );
            for (k, v) in &git_resp.headers {
                builder.insert_header((k.as_str(), v.as_str()));
            }
            builder.body(git_resp.body)
        }
        Err(e) => {
            let status = e.status_code();
            HttpResponse::build(
                actix_web::http::StatusCode::from_u16(status)
                    .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR),
            )
            .json(serde_json::json!({"error": e.to_string()}))
        }
    }
}

// ---------------------------------------------------------------------------
// Public app builder
// ---------------------------------------------------------------------------

/// Build the complete actix `App` for the Solid Pod server. Both the
/// binary (`main.rs`) and the workspace integration tests call this.
///
/// The returned `App` is fully-configured: route table, normaliser,
/// path-traversal guard, dotfile allowlist, body cap, CORS middleware
/// (when available), rate-limit middleware (when available), and WAC
/// enforcement.
pub fn build_app(
    state: AppState,
) -> App<
    impl actix_web::dev::ServiceFactory<
        ServiceRequest,
        Config = (),
        Response = ServiceResponse<EitherBody<EitherBody<BoxBody>>>,
        Error = ActixError,
        InitError = (),
    >,
> {
    let body_cap = state.body_cap;
    let dotfiles = state.dotfiles.clone();
    let allowed_origins = Arc::new(state.allowed_origins.clone());

    let mut app = App::new()
        .app_data(web::Data::new(state.clone()))
        .app_data(web::PayloadConfig::new(body_cap))
        // Sprint 11 (row 158): outermost layer so it observes every
        // response — including those that short-circuited in inner
        // guards. Wrapping first means `wrap()` applies it last in
        // actix's stack order.
        .wrap(ErrorLoggingMiddleware)
        .wrap(CorsHeaders { allowed_origins })
        // `MergeOnly` collapses duplicate slashes (//a → /a) without
        // stripping the trailing slash, which is the container/resource
        // discriminator in LDP.
        .wrap(NormalizePath::new(TrailingSlash::MergeOnly))
        .wrap(PathTraversalGuard)
        .wrap(DotfileGuard::new(dotfiles));

    // CORS / rate-limit: middleware is driven by the library types from
    // S7-A. We register pass-through headers when the env-driven policy
    // permits. The middleware is a no-op today beyond emitting the
    // policy's `response_headers` on every response; full preflight
    // handling lives in the sibling S7-A work.
    app = app
        .route("/.well-known/solid", web::get().to(handle_well_known_solid))
        .route(
            "/.well-known/webfinger",
            web::get().to(handle_well_known_webfinger),
        )
        .route(
            "/.well-known/nodeinfo",
            web::get().to(handle_well_known_nodeinfo),
        )
        .route(
            "/.well-known/nodeinfo/2.1",
            web::get().to(handle_well_known_nodeinfo_2_1),
        );

    #[cfg(feature = "did-nostr")]
    {
        app = app.route(
            "/.well-known/did/nostr/{pubkey}.json",
            web::get().to(handle_well_known_did_nostr),
        );
    }

    // JSS v0.0.190 Phase 1 port (issue #437), parity row 197.
    // Pod-resident NIP-05 endpoint. Scaffold only — handler body
    // is `todo!()`. Feature `nip05-endpoint` (default-off).
    #[cfg(feature = "nip05-endpoint")]
    {
        app = app.route(
            "/.well-known/nostr.json",
            web::get().to(handle_well_known_nip05),
        );
    }

    // App discovery endpoint (JSS #464 Phase 2 — public, no auth required).
    app = app.route("/.well-known/apps", web::get().to(handle_well_known_apps));

    // Payment endpoint (JSS parity: GET /pay/.info).
    app = app.route("/pay/.info", web::get().to(handle_pay_info));

    // WAC-gated CORS proxy endpoint.
    app = app.route("/proxy", web::get().to(handle_proxy));

    // Admin provisioning endpoint (alpha.15). Must be before the LDP
    // catch-all so `_admin` is never treated as a pod name.
    app = app.route(
        "/_admin/provision/{pubkey}",
        web::post().to(handle_admin_provision),
    );

    // Pod management API (JSS parity: /api/accounts/*)
    app = app
        .route("/.pods", web::post().to(handle_create_pod))
        .route("/api/accounts/new", web::post().to(handle_create_account))
        .route("/pods/check/{name}", web::get().to(handle_pod_check))
        .route("/login/password", web::post().to(handle_login_password))
        .route(
            "/account/password/reset",
            web::post().to(handle_password_reset_request),
        )
        .route(
            "/account/password/change",
            web::post().to(handle_password_change),
        );

    // Git smart-HTTP protocol routes (JSS #466/#469/#471).
    // Must be registered before the LDP catch-all. Direct .git/ access is
    // always blocked (security). Smart-HTTP paths are served by
    // GitHttpService when the `git` feature is enabled; otherwise 501.
    app = app
        .route(
            // Block direct .git/ access (JSS: "BLOCK: Direct access to .git contents")
            "/{tail:.*}/.git",
            web::route().to(|| async {
                HttpResponse::Forbidden()
                    .json(serde_json::json!({"error": "direct .git access is forbidden"}))
            }),
        )
        .route(
            "/{tail:.*}/.git/{rest:.*}",
            web::route().to(|| async {
                HttpResponse::Forbidden()
                    .json(serde_json::json!({"error": "direct .git access is forbidden"}))
            }),
        );

    // OPTIONS preflight for /_git panel REST API (alpha.15). Registered
    // unconditionally (before the feature block) so browsers get a valid
    // CORS response regardless of whether the git feature is compiled in.
    app = app.route(
        "/pods/{pk}/_git/{tail:.*}",
        web::method(actix_web::http::Method::OPTIONS).to(handle_git_panel_options),
    );

    #[cfg(feature = "git")]
    {
        // Git smart-HTTP: info/refs discovery + upload/receive pack.
        app = app
            .route("/{tail:.*}/info/refs", web::get().to(handle_git))
            .route("/{tail:.*}/git-upload-pack", web::post().to(handle_git))
            .route("/{tail:.*}/git-receive-pack", web::post().to(handle_git));

        // Git control panel REST API. Routes registered before the LDP
        // catch-all so `_git` segments are never treated as LDP resources.
        app = app
            .route(
                "/pods/{pubkey}/_git/status",
                web::get().to(handle_git_status),
            )
            .route(
                "/pods/{pubkey}/_git/log",
                web::get().to(handle_git_log),
            )
            .route(
                "/pods/{pubkey}/_git/diff",
                web::get().to(handle_git_diff),
            )
            .route(
                "/pods/{pubkey}/_git/stage",
                web::post().to(handle_git_stage),
            )
            .route(
                "/pods/{pubkey}/_git/unstage",
                web::post().to(handle_git_unstage),
            )
            .route(
                "/pods/{pubkey}/_git/commit",
                web::post().to(handle_git_commit),
            )
            .route(
                "/pods/{pubkey}/_git/branches",
                web::get().to(handle_git_branches),
            )
            .route(
                "/pods/{pubkey}/_git/branch",
                web::post().to(handle_git_create_branch),
            )
            .route(
                "/pods/{pubkey}/_git/discard",
                web::post().to(handle_git_discard),
            );
    }
    #[cfg(not(feature = "git"))]
    {
        // Without the git feature: return 501 for git protocol paths so
        // callers get a clear "not compiled in" signal rather than falling
        // through to LDP.
        let git_501 = || async {
            HttpResponse::NotImplemented()
                .json(serde_json::json!({"error": "git feature not enabled in this build"}))
        };
        app = app
            .route("/{tail:.*}/info/refs", web::get().to(git_501))
            .route("/{tail:.*}/git-upload-pack", web::post().to(git_501))
            .route("/{tail:.*}/git-receive-pack", web::post().to(git_501));
    }

    // Container POST and PUT (trailing slash) must register before the
    // catch-all so the trailing-slash variant wins.
    app.route("/{tail:.*}/", web::post().to(handle_post))
        .route("/{tail:.*}/", web::put().to(handle_put))
        .route("/{tail:.*}", web::get().to(handle_get))
        .route("/{tail:.*}", web::head().to(handle_get))
        .route("/{tail:.*}", web::put().to(handle_put))
        .route("/{tail:.*}", web::patch().to(handle_patch))
        .route("/{tail:.*}", web::delete().to(handle_delete))
        .route(
            "/{tail:.*}",
            web::method(actix_web::http::Method::from_bytes(b"COPY").unwrap()).to(handle_copy),
        )
        .route(
            "/{tail:.*}",
            web::method(actix_web::http::Method::OPTIONS).to(handle_options),
        )
}