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
// Package activitypub provides a single-file ActivityPub server that can be
// dropped into any Go project to create ActivityPub-speaking services.
//
// It implements:
//   - WebFinger discovery (/.well-known/webfinger)
//   - Actor document serving (GET /users/{actor})
//   - Inbox (POST /users/{actor}/inbox) with HTTP Signature verification
//   - Outbox (GET /users/{actor}/outbox) as a public OrderedCollection
//   - Followers / Following collections
//   - Server-to-server activity delivery with HTTP Signatures (draft-cavage-12)
//   - JSON-file persistence (zero external dependencies, stdlib only)
//   - RSA-2048 key generation and persistence
//
// Usage:
//
//	cfg := activitypub.Config{
//	    Domain:    "ap.example.com",
//	    ActorName: "mybot",
//	    ActorType: "Service",
//	    Summary:   "A helpful bot",
//	    DataDir:   "./data",
//	}
//	srv, err := activitypub.New(cfg)
//	srv.SetHooks(activitypub.Hooks{
//	    OnFollow: func(actorURL string) activitypub.FollowDecision { return activitypub.AcceptFollow },
//	    OnDM:     func(from, content, noteID, inReplyTo string) { /* handle DM */ },
//	})
//	srv.Register(http.DefaultServeMux)
//	http.ListenAndServe(":8080", nil)
package activitypub

import (
	"bytes"
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"sync"
	"syscall"
	"time"
)

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

// Config holds the configuration for an ActivityPub server instance.
type Config struct {
	// Domain is the hostname for this actor, e.g. "ap.example.com".
	// All URLs are built as https://{Domain}/...
	Domain string

	// ActorName is the username part, e.g. "mybot".
	// The actor URL will be https://{Domain}/users/{ActorName}.
	ActorName string

	// ActorType is the ActivityStreams actor type, e.g. "Service" or "Person".
	// Defaults to "Service".
	ActorType string

	// Summary is a short bio shown in the actor document.
	Summary string

	// DataDir is the directory where JSON state files and the RSA key are stored.
	// The directory is created if it does not exist.
	DataDir string

	// PrivateKey is optional. If nil, a key is loaded from DataDir/key.pem
	// or generated and saved there automatically.
	PrivateKey *rsa.PrivateKey
}

// FollowDecision is the return type of the OnFollow hook.
type FollowDecision bool

const (
	// AcceptFollow instructs the server to accept the incoming Follow activity.
	AcceptFollow FollowDecision = true
	// RejectFollow instructs the server to reject the incoming Follow activity.
	RejectFollow FollowDecision = false
)

// Hooks lets the consuming application react to incoming activities.
type Hooks struct {
	// OnFollow is called when a remote actor sends a Follow activity.
	// Return AcceptFollow to accept, RejectFollow to reject.
	// If nil, all follows are auto-accepted.
	OnFollow func(followerActorURL string) FollowDecision

	// OnDM is called when a Create{Note} activity is addressed directly to
	// this actor (i.e. it is a direct message / mention-only post).
	// from is the actor URL of the sender; content is the HTML content of the
	// Note; noteID is the URL of the incoming Note (use as inReplyTo when
	// replying); inReplyTo is the URL of the note this DM is itself a reply to
	// (empty if not a reply).
	OnDM func(from string, content string, noteID string, inReplyTo string)

	// OnHTML, if non-nil, is called when a browser requests the actor's
	// profile page (Accept: text/html). The handler may render whatever HTML
	// it likes using w and r. If nil, a 406 Not Acceptable response is
	// returned with a JSON body explaining that this is an ActivityPub actor.
	OnHTML func(w http.ResponseWriter, r *http.Request)

	// ServeNote, if non-nil, is called at the start of GET
	// /users/{actor}/notes/{id} before the library's own outbox lookup.
	// noteURL is the full canonical URL of the requested note.
	// Return true to indicate the request was fully handled; return false to
	// fall through to the default outbox-based lookup.
	// This hook exists so applications can serve notes that are not yet in
	// the outbox (e.g. notes awaiting external authorization before publish).
	ServeNote func(w http.ResponseWriter, r *http.Request, noteURL string) bool

	// OnAccept, if non-nil, is called when an Accept activity is received.
	// The library has already handled Accept{Follow} (updating the following
	// list). This hook lets applications handle additional Accept subtypes
	// (e.g. Accept{QuoteRequest}).
	OnAccept func(activity map[string]any)

	// OnReject, if non-nil, is called when a Reject activity is received.
	// Applications can use this to handle Reject{QuoteRequest} and similar.
	OnReject func(activity map[string]any)
}

// domain groups all actors sharing the same domain for WebFinger lookups.
type domain struct {
	mu     sync.RWMutex
	actors map[string]*Server // keyed by actor name
}

func (d *domain) register(s *Server) {
	d.mu.Lock()
	d.actors[s.cfg.ActorName] = s
	d.mu.Unlock()
}

func (d *domain) lookup(name string) (*Server, bool) {
	d.mu.RLock()
	s, ok := d.actors[name]
	d.mu.RUnlock()
	return s, ok
}

// domains is a process-wide map from domain string to domain registry.
var (
	domainsMu sync.Mutex
	domains   = map[string]*domain{}
)

func getDomain(domainName string) *domain {
	domainsMu.Lock()
	defer domainsMu.Unlock()
	if d, ok := domains[domainName]; ok {
		return d
	}
	d := &domain{actors: make(map[string]*Server)}
	domains[domainName] = d
	return d
}

// Server is an ActivityPub server instance. Create one with New().
type Server struct {
	cfg        Config
	root       *os.Root // traversal-resistant handle on cfg.DataDir
	privateKey *rsa.PrivateKey
	publicKey  *rsa.PublicKey
	hooks      Hooks
	dom        *domain

	mu        sync.RWMutex
	followers []string // actor URLs
	following []string // actor URLs
	outbox    []map[string]any
	inbox     []map[string]any

	iconURL     string // public URL of the actor's avatar image, or ""
	iconMu      sync.RWMutex
	displayName string // actor display name, falls back to ActorName if empty
	displayMu   sync.RWMutex

	// in-process cache of remote actor documents keyed by actor URL
	actorCache   map[string]map[string]any
	actorCacheMu sync.RWMutex
}

// ---------------------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------------------

// New creates a new Server from the given Config, loading or generating keys
// and restoring persisted state from DataDir.
func New(cfg Config) (*Server, error) {
	if cfg.Domain == "" {
		return nil, errors.New("activitypub: Config.Domain must not be empty")
	}
	if cfg.ActorName == "" {
		return nil, errors.New("activitypub: Config.ActorName must not be empty")
	}
	if cfg.ActorType == "" {
		cfg.ActorType = "Service"
	}
	if cfg.DataDir == "" {
		cfg.DataDir = "."
	}
	if err := os.MkdirAll(cfg.DataDir, 0o755); err != nil {
		return nil, fmt.Errorf("activitypub: create data dir: %w", err)
	}
	root, err := os.OpenRoot(cfg.DataDir)
	if err != nil {
		return nil, fmt.Errorf("activitypub: open data dir root: %w", err)
	}

	s := &Server{
		cfg:        cfg,
		root:       root,
		dom:        getDomain(cfg.Domain),
		actorCache: make(map[string]map[string]any),
	}
	s.dom.register(s)

	if cfg.PrivateKey != nil {
		s.privateKey = cfg.PrivateKey
	} else {
		key, err := s.loadOrGenerateKey()
		if err != nil {
			return nil, err
		}
		s.privateKey = key
	}
	s.publicKey = &s.privateKey.PublicKey

	// Load persisted state (errors are non-fatal; we start fresh if files are missing)
	_ = s.loadJSON("followers.json", &s.followers)
	_ = s.loadJSON("following.json", &s.following)
	_ = s.loadJSON("outbox.json", &s.outbox)
	_ = s.loadJSON("inbox.json", &s.inbox)

	return s, nil
}

// SetHooks registers application callbacks. Must be called before Register().
func (s *Server) SetHooks(h Hooks) {
	s.hooks = h
}

// ---------------------------------------------------------------------------
// HTTP handler registration
// ---------------------------------------------------------------------------

// Register mounts all ActivityPub and WebFinger routes onto mux.
//
// For single-actor deployments this is all you need. For multi-actor
// deployments, call RegisterActor for each actor and RegisterDomain once:
//
//	for _, srv := range servers {
//	    srv.RegisterActor(mux)
//	}
//	servers[0].RegisterDomain(mux)
//
// Routes registered by RegisterActor:
//
//	GET/POST /users/{actor}/inbox
//	GET      /users/{actor}/outbox
//	GET      /users/{actor}/followers
//	GET      /users/{actor}/following
//	GET      /users/{actor}
//
// Routes registered by RegisterDomain (domain-wide, register once):
//
//	GET  /.well-known/webfinger
//	POST /inbox  (shared inbox)
func (s *Server) Register(mux *http.ServeMux) {
	s.RegisterActor(mux)
	s.RegisterDomain(mux)
}

// RegisterActor mounts only the per-actor routes for this server's actor.
// Safe to call for each actor in a multi-actor deployment.
func (s *Server) RegisterActor(mux *http.ServeMux) {
	mux.HandleFunc("/users/"+s.cfg.ActorName, s.handleActor)
	mux.HandleFunc("/users/"+s.cfg.ActorName+"/inbox", s.handleInbox)
	mux.HandleFunc("/users/"+s.cfg.ActorName+"/outbox", s.handleOutbox)
	mux.HandleFunc("/users/"+s.cfg.ActorName+"/followers", s.handleFollowers)
	mux.HandleFunc("/users/"+s.cfg.ActorName+"/following", s.handleFollowing)
	mux.HandleFunc("/users/"+s.cfg.ActorName+"/notes/", s.handleNote)
}

// RegisterDomain mounts the domain-wide routes that must only be registered
// once regardless of how many actors share this domain.
// The WebFinger handler will respond for all actors registered on this mux
// whose actor name matches the requested resource — call RegisterDomain on
// any one of the actors (typically the first).
func (s *Server) RegisterDomain(mux *http.ServeMux) {
	mux.HandleFunc("/.well-known/webfinger", s.handleWebFinger)
	mux.HandleFunc("/inbox", s.handleInbox)
}

// ---------------------------------------------------------------------------
// Public ActivityPub operations
// ---------------------------------------------------------------------------

// Announce sends an Announce (boost) activity for the given object URL to all
// followers and saves it to the outbox.
func (s *Server) Announce(objectURL string) error {
	return s.AnnounceWithOriginal(objectURL, "")
}

// AnnounceWithOriginal is like Announce but also records the original
// (pre-resolution) URL so that UndoAnnounce can match a Delete activity
// that references the original URL rather than the resolved AP object id.
func (s *Server) AnnounceWithOriginal(objectURL, originalURL string) error {
	activity := s.buildAnnounce(objectURL)
	if originalURL != "" && originalURL != objectURL {
		activity["originalObject"] = originalURL
	}
	s.mu.Lock()
	s.outbox = prependCapped(s.outbox, activity, 500)
	s.mu.Unlock()
	if err := s.saveOutbox(); err != nil {
		log.Printf("activitypub: save outbox: %v", err)
	}
	return s.deliverToFollowers(activity)
}

// UndoAnnounce sends an Undo{Announce} for any Announce of objectURL in the
// outbox, replaces it with a Tombstone, and delivers the Undo to all followers.
// Matches against both the resolved object URL and the originalObject field.
// Replacing with a Tombstone (rather than deleting) lets remote servers that
// re-fetch the activity id learn that it has been retracted.
func (s *Server) UndoAnnounce(objectURL string) error {
	now := time.Now().UTC().Format(time.RFC3339)

	s.mu.Lock()
	var announce map[string]any
	for i, item := range s.outbox {
		if item["type"] == "Announce" {
			if item["object"] == objectURL || item["originalObject"] == objectURL {
				announce = item
				// Replace in-place with a Tombstone at the same id
				s.outbox[i] = map[string]any{
					"@context":  "https://www.w3.org/ns/activitystreams",
					"id":        item["id"],
					"type":      "Tombstone",
					"published": item["published"],
					"deleted":   now,
				}
				break
			}
		}
	}
	s.mu.Unlock()

	if err := s.saveOutbox(); err != nil {
		log.Printf("activitypub: save outbox after undo: %v", err)
	}

	if announce == nil {
		log.Printf("activitypub: UndoAnnounce: no Announce found for %s", objectURL)
		return nil
	}

	undo := map[string]any{
		"@context":  "https://www.w3.org/ns/activitystreams",
		"id":        fmt.Sprintf("%s#undos/%d", s.actorURL(), time.Now().UnixNano()),
		"type":      "Undo",
		"actor":     s.actorURL(),
		"object":    announce,
		"published": now,
		"to":        []string{"https://www.w3.org/ns/activitystreams#Public"},
		"cc":        []string{s.actorURL() + "/followers"},
	}
	return s.deliverToFollowers(undo)
}

// SendDM sends a direct-message Note to toActorURL. The Note is addressed
// only to the recipient (not public, not followers) so it stays out of the
// outbox. inReplyTo may be empty. The Note is delivered to the recipient's
// inbox but never stored in the outbox.
//
// It returns the AP id of the Note it sent. Because DM Notes are not kept in
// the outbox they are not retrievable at that id afterwards, so callers who
// need to recognise replies to their own DMs must remember the id themselves.
// The id is returned even on delivery failure, so it is only meaningful to
// record it when err is nil.
func (s *Server) SendDM(toActorURL, content, inReplyTo string) (noteID string, err error) {
	// Use personal inbox, not sharedInbox — DMs are addressed to a specific
	// user and sharedInbox delivery may be rejected by the remote server.
	actor, err := s.fetchActor(toActorURL)
	if err != nil {
		return "", fmt.Errorf("fetch actor for DM: %w", err)
	}
	inbox, _ := actor["inbox"].(string)
	if inbox == "" {
		return "", fmt.Errorf("actor %s has no inbox", toActorURL)
	}
	log.Printf("activitypub: SendDM: sending to %s (inbox: %s)", toActorURL, inbox)
	now := time.Now().UTC().Format(time.RFC3339)
	noteID = fmt.Sprintf("%s/notes/%d", s.actorURL(), time.Now().UnixNano())
	note := map[string]any{
		"@context":     "https://www.w3.org/ns/activitystreams",
		"id":           noteID,
		"type":         "Note",
		"attributedTo": s.actorURL(),
		"published":    now,
		"to":           []string{toActorURL},
		"cc":           []string{},
		"content":      content,
		"tag": []map[string]any{
			{
				"type": "Mention",
				"href": toActorURL,
			},
		},
	}
	if inReplyTo != "" {
		note["inReplyTo"] = inReplyTo
	}
	create := map[string]any{
		"@context":  "https://www.w3.org/ns/activitystreams",
		"id":        fmt.Sprintf("%s/creates/%d", s.actorURL(), time.Now().UnixNano()),
		"type":      "Create",
		"actor":     s.actorURL(),
		"published": now,
		"to":        []string{toActorURL},
		"cc":        []string{},
		"object":    note,
	}
	if err := s.postActivity(inbox, create); err != nil {
		return noteID, fmt.Errorf("post DM to %s: %w", inbox, err)
	}
	log.Printf("activitypub: SendDM: delivered to %s (note %s)", inbox, noteID)
	return noteID, nil
}

// DeliverToFollowers signs and POSTs activity to every known follower's inbox.
func (s *Server) DeliverToFollowers(activity map[string]any) error {
	return s.deliverToFollowers(activity)
}

// PostToInbox signs and POSTs an activity directly to a specific inbox URL.
// Use this to deliver activities to a single actor rather than all followers.
func (s *Server) PostToInbox(inboxURL string, activity map[string]any) error {
	return s.postActivity(inboxURL, activity)
}

// ResolveInbox fetches an actor document and returns the best inbox URL
// (prefers sharedInbox). Useful when delivering to a single target actor.
func (s *Server) ResolveInbox(actorURL string) (string, error) {
	return s.resolveInbox(actorURL)
}

// PublishCreate adds a Create{Note} activity to the outbox and delivers it to
// all followers. The activity is saved to disk before delivery.
func (s *Server) PublishCreate(createActivity map[string]any) error {
	s.mu.Lock()
	s.outbox = prependCapped(s.outbox, createActivity, 500)
	s.mu.Unlock()
	if err := s.saveOutbox(); err != nil {
		log.Printf("activitypub: PublishCreate: save outbox: %v", err)
	}
	return s.deliverToFollowers(createActivity)
}

// DeleteCreate sends a Delete{Note} for any Create{Note} in the outbox whose
// embedded Note matches objectURL via the "quote", "quoteUri", or "id" fields.
// The Create is replaced in-place with a Tombstone and a Delete activity is
// delivered to all followers.
func (s *Server) DeleteCreate(objectURL string) error {
	now := time.Now().UTC().Format(time.RFC3339)

	s.mu.Lock()
	var note map[string]any
	for i, item := range s.outbox {
		if item["type"] != "Create" {
			continue
		}
		obj, _ := item["object"].(map[string]any)
		if obj == nil {
			continue
		}
		if obj["quote"] == objectURL || obj["quoteUri"] == objectURL || obj["id"] == objectURL {
			note = obj
			noteID, _ := obj["id"].(string)
			s.outbox[i] = map[string]any{
				"@context":  "https://www.w3.org/ns/activitystreams",
				"id":        noteID,
				"type":      "Tombstone",
				"published": item["published"],
				"deleted":   now,
			}
			break
		}
	}
	s.mu.Unlock()

	if err := s.saveOutbox(); err != nil {
		log.Printf("activitypub: DeleteCreate: save outbox: %v", err)
	}

	if note == nil {
		log.Printf("activitypub: DeleteCreate: no Create{Note} found for %s", objectURL)
		return nil
	}

	noteID, _ := note["id"].(string)
	del := map[string]any{
		"@context":  "https://www.w3.org/ns/activitystreams",
		"id":        fmt.Sprintf("%s#deletes/%d", s.actorURL(), time.Now().UnixNano()),
		"type":      "Delete",
		"actor":     s.actorURL(),
		"object":    noteID,
		"published": now,
		"to":        []string{"https://www.w3.org/ns/activitystreams#Public"},
		"cc":        []string{s.actorURL() + "/followers"},
	}
	return s.deliverToFollowers(del)
}

// RemoveFollowing removes actorURL from the following list and persists the change.
func (s *Server) RemoveFollowing(actorURL string) {
	s.mu.Lock()
	s.following = remove(s.following, actorURL)
	s.mu.Unlock()
	if err := s.saveFollowing(); err != nil {
		log.Printf("activitypub: RemoveFollowing: save: %v", err)
	}
}

// IsFollowing reports whether this actor is currently following actorURL.
func (s *Server) IsFollowing(actorURL string) bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return contains(s.following, actorURL)
}

// buildActorDoc constructs the current actor document as a map.
func (s *Server) buildActorDoc() (map[string]any, error) {
	pubKeyPEM, err := s.publicKeyPEM()
	if err != nil {
		return nil, fmt.Errorf("publicKeyPEM: %w", err)
	}
	s.iconMu.RLock()
	iconURL := s.iconURL
	s.iconMu.RUnlock()

	actor := map[string]any{
		"@context": []any{
			"https://www.w3.org/ns/activitystreams",
			"https://w3id.org/security/v1",
		},
		"id":                s.actorURL(),
		"type":              s.cfg.ActorType,
		"preferredUsername": s.cfg.ActorName,
		"name":              s.effectiveName(),
		"summary":           s.cfg.Summary,
		"inbox":             s.actorURL() + "/inbox",
		"outbox":            s.actorURL() + "/outbox",
		"followers":         s.actorURL() + "/followers",
		"following":         s.actorURL() + "/following",
		"publicKey": map[string]any{
			"id":           s.actorURL() + "#main-key",
			"owner":        s.actorURL(),
			"publicKeyPem": pubKeyPEM,
		},
		"endpoints": map[string]any{
			"sharedInbox": s.baseURL() + "/inbox",
		},
	}
	if iconURL != "" {
		actor["icon"] = map[string]any{
			"type":      "Image",
			"mediaType": "image/jpeg",
			"url":       iconURL,
		}
	}
	return actor, nil
}

// actorDocFile is where the last delivered actor document is cached inside
// DataDir, for the change comparison in UpdateProfile.
//
// It is deliberately NOT called "actor.json": DataDir is chosen by the
// embedding application, which may well keep its own per-actor config in that
// same directory. booster-bot did exactly that, and the two files silently
// overwrote each other — the actor document won, and the application's
// settings (curator allowlist, display name, avatar id) were lost. A name
// carrying the library's own prefix keeps the two apart.
const actorDocFile = "ap-actor-doc.json"

// UpdateProfile sends an Update{Actor} activity to all followers if the actor
// document has changed since the last save. If force is true, the update is
// delivered unconditionally. Safe to call on every startup with force=false.
func (s *Server) UpdateProfile(force bool) error {
	actor, err := s.buildActorDoc()
	if err != nil {
		return err
	}
	currentJSON, err := json.Marshal(actor)
	if err != nil {
		return fmt.Errorf("marshal actor: %w", err)
	}

	if !force {
		var saved map[string]any
		if err := s.loadJSON(actorDocFile, &saved); err == nil {
			savedJSON, err := json.Marshal(saved)
			if err == nil && bytes.Equal(currentJSON, savedJSON) {
				log.Printf("activitypub: actor doc unchanged, skipping UpdateProfile")
				return nil
			}
		}
		log.Printf("activitypub: actor doc changed, sending UpdateProfile")
	}

	if err := s.saveJSON(actorDocFile, actor); err != nil {
		log.Printf("activitypub: save %s: %v", actorDocFile, err)
	}
	update := map[string]any{
		"@context":  "https://www.w3.org/ns/activitystreams",
		"id":        fmt.Sprintf("%s#updates/%d", s.actorURL(), time.Now().UnixNano()),
		"type":      "Update",
		"actor":     s.actorURL(),
		"object":    actor,
		"published": time.Now().UTC().Format(time.RFC3339),
		"to":        []string{"https://www.w3.org/ns/activitystreams#Public"},
	}
	return s.deliverToFollowers(update)
}

// SetSummary updates the in-memory summary for this actor. The new value is
// reflected immediately in the actor document served at GET /users/{name}.
// Call UpdateProfile() afterwards to push the change to followers.
func (s *Server) SetSummary(summary string) {
	s.cfg.Summary = summary
}

// SetIcon sets the public URL of the actor's avatar image. Pass an empty
// string to remove the icon. The change is reflected immediately in the actor
// document; call UpdateProfile() to push it to followers.
func (s *Server) SetIcon(iconURL string) {
	s.iconMu.Lock()
	s.iconURL = iconURL
	s.iconMu.Unlock()
}

// SetDisplayName sets the actor's display name (the "name" field in the actor
// document). Pass an empty string to fall back to the ActorName. The change
// is reflected immediately; call UpdateProfile() to push it to followers.
func (s *Server) SetDisplayName(name string) {
	s.displayMu.Lock()
	s.displayName = name
	s.displayMu.Unlock()
}

// Close releases the file descriptor held by the server's data directory root.
// It is safe but not required to call Close for servers that live for the
// duration of the process.
func (s *Server) Close() error {
	return s.root.Close()
}

// effectiveName returns the display name, falling back to ActorName.
func (s *Server) effectiveName() string {
	s.displayMu.RLock()
	n := s.displayName
	s.displayMu.RUnlock()
	if n == "" {
		return s.cfg.ActorName
	}
	return n
}

// SetAnnounceField sets an arbitrary extra field on the first Announce in the
// outbox whose object or originalObject matches objectURL. Useful for storing
// application-level metadata (e.g. a content snippet) alongside the activity.
// Returns true if a matching Announce was found and updated.
func (s *Server) SetAnnounceField(objectURL, key string, value any) bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, item := range s.outbox {
		if item["type"] == "Announce" &&
			(item["object"] == objectURL || item["originalObject"] == objectURL) {
			item[key] = value
			go func() { _ = s.saveOutbox() }()
			return true
		}
	}
	return false
}

// Outbox returns a snapshot of the outbox containing only live Announce
// activities (Tombstones are excluded). Safe for concurrent use.
func (s *Server) Outbox() []map[string]any {
	s.mu.RLock()
	defer s.mu.RUnlock()
	var result []map[string]any
	for _, item := range s.outbox {
		t, _ := item["type"].(string)
		if t == "Announce" || t == "Create" {
			cp := make(map[string]any, len(item))
			for k, v := range item {
				cp[k] = v
			}
			result = append(result, cp)
		}
	}
	return result
}

// ---------------------------------------------------------------------------
// WebFinger handler
// ---------------------------------------------------------------------------

func (s *Server) handleWebFinger(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	resource := r.URL.Query().Get("resource")
	if resource == "" {
		http.Error(w, "missing resource parameter", http.StatusBadRequest)
		return
	}

	// Resolve the resource to an actor name on this domain.
	var name string
	if after, ok := strings.CutPrefix(resource, "acct:"); ok {
		parts := strings.SplitN(after, "@", 2)
		if len(parts) != 2 || parts[1] != s.cfg.Domain {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		name = parts[0]
	} else {
		// resource is an actor URL — extract name from path /users/{name}
		prefix := "https://" + s.cfg.Domain + "/users/"
		if !strings.HasPrefix(resource, prefix) {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		name = strings.TrimPrefix(resource, prefix)
	}

	// Look up the actor in the domain registry (covers all actors on this domain)
	actor, ok := s.dom.lookup(name)
	if !ok {
		http.Error(w, "not found", http.StatusNotFound)
		return
	}

	resp := map[string]any{
		"subject": fmt.Sprintf("acct:%s@%s", actor.cfg.ActorName, actor.cfg.Domain),
		"aliases": []string{actor.actorURL()},
		"links": []map[string]any{
			{
				"rel":  "self",
				"type": "application/activity+json",
				"href": actor.actorURL(),
			},
			{
				"rel":  "http://webfinger.net/rel/profile-page",
				"type": "text/html",
				"href": actor.actorURL(),
			},
		},
	}
	w.Header().Set("Content-Type", "application/jrd+json")
	writeJSONRaw(w, resp)
}

// ---------------------------------------------------------------------------
// Actor handler
// ---------------------------------------------------------------------------

func (s *Server) handleActor(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// Content-negotiate: browsers get HTML (or 406), AP clients get JSON.
	accept := r.Header.Get("Accept")
	wantsHTML := strings.Contains(accept, "text/html") &&
		!strings.Contains(accept, "application/activity+json") &&
		!strings.Contains(accept, "application/ld+json")
	if wantsHTML {
		if s.hooks.OnHTML != nil {
			s.hooks.OnHTML(w, r)
		} else {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusNotAcceptable)
			writeJSONRaw(w, map[string]any{
				"error":   "Not Acceptable",
				"message": "This is an ActivityPub actor. Request with Accept: application/activity+json to get the actor document.",
				"actor":   s.actorURL(),
			})
		}
		return
	}

	actor, err := s.buildActorDoc()
	if err != nil {
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/activity+json")
	writeJSON(w, actor)
}

// ---------------------------------------------------------------------------
// Inbox handler
// ---------------------------------------------------------------------------

func (s *Server) handleInbox(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		s.serveOrderedCollection(w, s.inbox, s.actorURL()+"/inbox")
	case http.MethodPost:
		s.receiveInbox(w, r)
	default:
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
	}
}

// ---------------------------------------------------------------------------
// SSRF-safe HTTP client
// ---------------------------------------------------------------------------
//
// All outbound HTTP requests use newSafeClient, which hooks into the TCP
// dialer after DNS resolution to block connections to private/loopback/
// link-local addresses and to restrict to HTTPS (port 443) only.
// This prevents Server-Side Request Forgery via attacker-controlled URLs
// (inbox URLs from actor documents, object URLs from DM content, etc.)
// and also prevents DNS-rebinding attacks because the check happens after
// the OS has resolved the hostname to an IP address.
//
// IP blocklist and structure adapted from Andrew Ayer's public-domain article
// "Preventing Server Side Request Forgery in Golang" (2019).

func ipv4Net(a, b, c, d byte, prefixLen int) net.IPNet {
	return net.IPNet{
		IP:   net.IPv4(a, b, c, d),
		Mask: net.CIDRMask(96+prefixLen, 128),
	}
}

// reservedIPv4Nets lists every IPv4 range that must not be reached.
var reservedIPv4Nets = []net.IPNet{
	ipv4Net(0, 0, 0, 0, 8),       // "This" network
	ipv4Net(10, 0, 0, 0, 8),      // Private
	ipv4Net(100, 64, 0, 0, 10),   // Shared address space (RFC 6598)
	ipv4Net(127, 0, 0, 0, 8),     // Loopback
	ipv4Net(169, 254, 0, 0, 16),  // Link-local (includes AWS metadata 169.254.169.254)
	ipv4Net(172, 16, 0, 0, 12),   // Private
	ipv4Net(192, 0, 0, 0, 24),    // IETF protocol assignments (RFC 6890)
	ipv4Net(192, 0, 2, 0, 24),    // Documentation (TEST-NET-1)
	ipv4Net(192, 88, 99, 0, 24),  // 6to4 relay anycast (deprecated)
	ipv4Net(192, 168, 0, 0, 16),  // Private
	ipv4Net(198, 18, 0, 0, 15),   // Benchmarking (RFC 2544)
	ipv4Net(198, 51, 100, 0, 24), // Documentation (TEST-NET-2)
	ipv4Net(203, 0, 113, 0, 24),  // Documentation (TEST-NET-3)
	ipv4Net(224, 0, 0, 0, 4),     // Multicast
	ipv4Net(240, 0, 0, 0, 4),     // Reserved (broadcast)
}

// globalUnicastIPv6Net is 2000::/3, the only IPv6 range considered public.
var globalUnicastIPv6Net = net.IPNet{
	IP:   net.IP{0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	Mask: net.CIDRMask(3, 128),
}

// isPublicIPAddress returns true if ip is a globally routable address.
func isPublicIPAddress(ip net.IP) bool {
	if ip.To4() != nil {
		for _, reserved := range reservedIPv4Nets {
			if reserved.Contains(ip) {
				return false
			}
		}
		return true
	}
	return globalUnicastIPv6Net.Contains(ip)
}

// safeSocketControl is a net.Dialer.Control function that aborts the dial if
// the resolved address is not a public IP on port 443 (HTTPS only).
func safeSocketControl(network, address string, _ syscall.RawConn) error {
	if network != "tcp4" && network != "tcp6" {
		return fmt.Errorf("activitypub: network %q is not allowed", network)
	}
	host, port, err := net.SplitHostPort(address)
	if err != nil {
		return fmt.Errorf("activitypub: invalid address %q: %w", address, err)
	}
	if port != "443" {
		return fmt.Errorf("activitypub: port %s is not allowed (only 443/HTTPS)", port)
	}
	ip := net.ParseIP(host)
	if ip == nil {
		return fmt.Errorf("activitypub: %q is not a valid IP address", host)
	}
	if !isPublicIPAddress(ip) {
		return fmt.Errorf("activitypub: %s is not a public IP address", ip)
	}
	return nil
}

// newSafeClient returns an *http.Client that enforces SSRF protection via
// safeSocketControl. All outbound requests in this package must use this
// client rather than http.DefaultClient or a bare &http.Client{}.
//
// Redirects are capped at 3. Each redirect target is validated by the safe
// dialer, so a chain cannot escape to a private address mid-redirect.
// Go's default of 10 redirects is intentionally overridden here.
func newSafeClient(timeout time.Duration) *http.Client {
	dialer := &net.Dialer{
		Timeout:   30 * time.Second,
		KeepAlive: 30 * time.Second,
		Control:   safeSocketControl,
	}
	transport := &http.Transport{
		Proxy:                 http.ProxyFromEnvironment,
		DialContext:           dialer.DialContext,
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          100,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	}
	return &http.Client{
		Timeout:   timeout,
		Transport: transport,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if len(via) >= 3 {
				return fmt.Errorf("too many redirects (max 3)")
			}
			return nil
		},
	}
}

// errActorGone is returned when a remote actor's URL responds with 410 Gone,
// indicating the account has been deleted.
var errActorGone = errors.New("actor has been deleted (410 Gone)")

func (s *Server) receiveInbox(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1 MiB max
	if err != nil {
		http.Error(w, "read error", http.StatusBadRequest)
		return
	}

	// Verify HTTP Signature (cavage-12 / draft profile)
	actorURL, err := s.verifyHTTPSignature(r, body)
	if err != nil {
		if errors.Is(err, errActorGone) {
			// Signing key belongs to a deleted actor — silently discard
			log.Printf("activitypub: inbox: discarding request from deleted actor (%v)", err)
			w.WriteHeader(http.StatusAccepted)
			return
		}
		log.Printf("activitypub: inbox signature verification failed: %v", err)
		http.Error(w, "signature verification failed", http.StatusUnauthorized)
		return
	}

	var activity map[string]any
	if err := json.Unmarshal(body, &activity); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}

	// Basic plausibility check
	if _, ok := activity["type"]; !ok {
		http.Error(w, "missing type", http.StatusBadRequest)
		return
	}

	// Verify that the activity's actor is the same owner as the signing key.
	//
	// FEP-fe34 §Signatures:
	//   "In order to minimize damage in the event of a key compromise or
	//   insufficient validation, consumers MUST verify that the signing key
	//   has the same owner as the signed object."
	// FEP-fe34 §Ownership:
	//   "Activities have an actor property … This actor is considered to be
	//   the owner of the activity."
	// FEP-fe34 §Comparing owners:
	//   "Owners are the same if their identifiers are identical after
	//   conversion of their schemes and hosts to lowercase."
	//
	// actorURL is derived from keyId (fragment stripped). The activity's
	// declared actor must be the same owner — exact URL equality (with
	// case-folded scheme and host) rather than same-origin. This prevents
	// a compromised server from injecting activities on behalf of a different
	// actor on the same server.
	//
	// Note: relay forwarding (a relay signing with its own key for an actor
	// on a different server) is intentionally not supported and will be
	// rejected by this check.
	activityActor, _ := activity["actor"].(string)
	if activityActor == "" {
		http.Error(w, "missing actor field", http.StatusBadRequest)
		return
	}
	if !sameOwner(actorURL, activityActor) {
		log.Printf("activitypub: inbox: actor owner mismatch: keyId actor %q vs activity actor %q", actorURL, activityActor)
		http.Error(w, "activity actor does not match signing key owner", http.StatusUnauthorized)
		return
	}

	activityType, _ := activity["type"].(string)
	log.Printf("inbox: received %s from %s", activityType, actorURL)
	bodyJSON, _ := json.MarshalIndent(activity, "  ", "  ")
	log.Printf("inbox body:\n  %s", bodyJSON)

	// Store a copy in our in-memory / persisted inbox (capped at 200)
	s.mu.Lock()
	s.inbox = prependCapped(s.inbox, activity, 200)
	s.mu.Unlock()
	go func() { _ = s.saveInbox() }()

	switch activityType {
	case "Follow":
		s.handleFollow(w, activity, actorURL)
	case "Undo":
		s.handleUndo(w, activity)
	case "Accept":
		s.handleAccept(w, activity)
	case "Reject":
		s.handleReject(w, activity)
	case "Create":
		s.handleCreate(w, activity, actorURL)
	case "Delete":
		s.handleDelete(w, activity)
	default:
		// Accept unknown activity types gracefully
		w.WriteHeader(http.StatusAccepted)
	}
}

// verifyEmbeddedObject checks that an object embedded inside a trusted activity
// satisfies FEP-fe34 §Embedding. The actorURL argument is the verified signing
// actor (from the HTTP signature). The embedded obj must:
//
//  1. Have a same-origin `id` as actorURL, if it has an id at all.
//     Anonymous objects (no id) are unconditionally trusted.
//  2. Have a same-origin owner as actorURL.
//     The owner field is `attributedTo` for Object/Note types and `actor`
//     for Activity types (Follow, Undo, etc.). If neither field is present
//     the object is anonymous with respect to ownership and is accepted.
//
// Returns a non-nil error string suitable for an HTTP 401 response body if
// either check fails. The caller should reject the enclosing activity.
func verifyEmbeddedObject(actorURL string, obj map[string]any) error {
	// Check 1: if the embedded object has an id, it must be same-origin.
	if id := stringField(obj, "id"); id != "" {
		if !sameOrigin(actorURL, id) {
			return fmt.Errorf("embedded object id %q has different origin from signing actor %q", id, actorURL)
		}
	}

	// Check 2: the owner of the embedded object must be the same owner.
	// Owner is `actor` for Activity subtypes, `attributedTo` for Objects.
	// We use sameOwner (exact equality with case-folded scheme+host) rather
	// than sameOrigin, per silverpill's recommendation: if the origin server
	// does poor C2S validation, an attacker could craft an embedded object
	// with attributedTo pointing to a different actor on the same server.
	// Exact owner equality catches this.
	owner := stringField(obj, "actor")
	if owner == "" {
		owner = stringField(obj, "attributedTo")
	}
	if owner != "" && !sameOwner(actorURL, owner) {
		return fmt.Errorf("embedded object owner %q differs from signing actor %q", owner, actorURL)
	}

	return nil
}

// handleFollow processes an incoming Follow activity.
func (s *Server) handleFollow(w http.ResponseWriter, activity map[string]any, senderActorURL string) {
	followerURL := stringField(activity, "actor")
	if followerURL == "" {
		http.Error(w, "missing actor", http.StatusBadRequest)
		return
	}

	// Ask application whether to accept
	decision := AcceptFollow
	if s.hooks.OnFollow != nil {
		decision = s.hooks.OnFollow(followerURL)
	}

	if decision == AcceptFollow {
		// Add to followers
		s.mu.Lock()
		if !contains(s.followers, followerURL) {
			s.followers = append(s.followers, followerURL)
		}
		s.mu.Unlock()
		go func() { _ = s.saveFollowers() }()

		// Send Accept{Follow} back to the follower's inbox
		go s.sendAcceptFollow(followerURL, activity)
	} else {
		go s.sendRejectFollow(followerURL, activity)
	}

	w.WriteHeader(http.StatusAccepted)
}

// handleUndo processes Undo{Follow} (unfollow).
func (s *Server) handleUndo(w http.ResponseWriter, activity map[string]any) {
	actorURL := stringField(activity, "actor")
	obj, ok := activity["object"].(map[string]any)
	if !ok {
		w.WriteHeader(http.StatusAccepted)
		return
	}
	if err := verifyEmbeddedObject(actorURL, obj); err != nil {
		log.Printf("handleUndo: embedded object failed origin check: %v", err)
		http.Error(w, "embedded object origin mismatch", http.StatusUnauthorized)
		return
	}
	if objType, _ := obj["type"].(string); objType == "Follow" {
		followerURL := stringField(activity, "actor")
		s.mu.Lock()
		s.followers = remove(s.followers, followerURL)
		s.mu.Unlock()
		go func() { _ = s.saveFollowers() }()
	}
	w.WriteHeader(http.StatusAccepted)
}

// handleAccept processes Accept{Follow} and notifies the application via OnAccept.
func (s *Server) handleAccept(w http.ResponseWriter, activity map[string]any) {
	obj, ok := activity["object"].(map[string]any)
	if !ok {
		w.WriteHeader(http.StatusAccepted)
		return
	}
	if objType, _ := obj["type"].(string); objType == "Follow" {
		remoteActorURL := stringField(activity, "actor")
		s.mu.Lock()
		if !contains(s.following, remoteActorURL) {
			s.following = append(s.following, remoteActorURL)
		}
		s.mu.Unlock()
		go func() { _ = s.saveFollowing() }()
	}
	if s.hooks.OnAccept != nil {
		go s.hooks.OnAccept(activity)
	}
	w.WriteHeader(http.StatusAccepted)
}

// handleReject notifies the application via OnReject.
func (s *Server) handleReject(w http.ResponseWriter, activity map[string]any) {
	log.Printf("activitypub: inbox: Reject from %s", stringField(activity, "actor"))
	if s.hooks.OnReject != nil {
		go s.hooks.OnReject(activity)
	}
	w.WriteHeader(http.StatusAccepted)
}

// handleDelete processes a Delete activity. If the deleted object matches an
// Announce in our outbox, we send an Undo{Announce} to our followers.
func (s *Server) handleDelete(w http.ResponseWriter, activity map[string]any) {
	actorURL := stringField(activity, "actor")
	// The object field may be a string ID or an embedded object with an id.
	var objectID string
	switch v := activity["object"].(type) {
	case string:
		// A bare string ID — verify it is same-origin as the signing actor.
		// The sender is asserting they own the object at that URL.
		if !sameOrigin(actorURL, v) {
			log.Printf("handleDelete: object id %q has different origin from actor %q", v, actorURL)
			http.Error(w, "object origin mismatch", http.StatusUnauthorized)
			return
		}
		objectID = v
	case map[string]any:
		if err := verifyEmbeddedObject(actorURL, v); err != nil {
			log.Printf("handleDelete: embedded object failed origin check: %v", err)
			http.Error(w, "embedded object origin mismatch", http.StatusUnauthorized)
			return
		}
		objectID, _ = v["id"].(string)
	}

	if objectID == "" {
		log.Printf("handleDelete: no object id found, ignoring")
		w.WriteHeader(http.StatusAccepted)
		return
	}

	log.Printf("handleDelete: object %s deleted, checking outbox for matching Announce", objectID)

	if err := s.UndoAnnounce(objectID); err != nil {
		log.Printf("handleDelete: UndoAnnounce failed: %v", err)
	}
	w.WriteHeader(http.StatusAccepted)
}

// handleCreate processes Create{Note} activities — i.e. incoming posts/DMs.
func (s *Server) handleCreate(w http.ResponseWriter, activity map[string]any, senderActorURL string) {
	if s.hooks.OnDM == nil {
		log.Printf("handleCreate: no OnDM hook set, ignoring")
		w.WriteHeader(http.StatusAccepted)
		return
	}
	obj, ok := activity["object"].(map[string]any)
	if !ok {
		log.Printf("handleCreate: object is not a map (type %T), ignoring", activity["object"])
		w.WriteHeader(http.StatusAccepted)
		return
	}
	objType, _ := obj["type"].(string)
	if objType != "Note" {
		log.Printf("handleCreate: object type is %q, not Note, ignoring", objType)
		w.WriteHeader(http.StatusAccepted)
		return
	}
	if err := verifyEmbeddedObject(senderActorURL, obj); err != nil {
		log.Printf("handleCreate: embedded Note failed origin check: %v", err)
		http.Error(w, "embedded object origin mismatch", http.StatusUnauthorized)
		return
	}

	to := toStringSlice(obj["to"])
	cc := toStringSlice(obj["cc"])
	log.Printf("handleCreate: Note to=%v cc=%v", to, cc)

	// Check all actors on this domain — the shared inbox receives DMs for any
	// of them, not just the actor that happens to have registered /inbox last.
	from := stringField(activity, "actor")
	if from == "" {
		from = senderActorURL
	}
	inReplyTo := stringField(obj, "inReplyTo")
	content, _ := obj["content"].(string)

	dispatched := false
	s.dom.mu.RLock()
	actors := make([]*Server, 0, len(s.dom.actors))
	for _, a := range s.dom.actors {
		actors = append(actors, a)
	}
	s.dom.mu.RUnlock()

	for _, a := range actors {
		if a.hooks.OnDM == nil {
			continue
		}
		if isDM(obj, a.actorURL()) {
			noteID := stringField(obj, "id")
			log.Printf("handleCreate: DM for %s from %s noteID=%q inReplyTo=%q content: %s", a.actorURL(), from, noteID, inReplyTo, content)
			hook := a.hooks.OnDM
			go hook(from, content, noteID, inReplyTo)
			dispatched = true
		}
	}
	if !dispatched {
		log.Printf("handleCreate: Note is not a DM to any of our actors, ignoring")
	}
	w.WriteHeader(http.StatusAccepted)
}

// isDM returns true if the Note is addressed directly to actorURL but NOT to Public.
func isDM(note map[string]any, actorURL string) bool {
	const public = "https://www.w3.org/ns/activitystreams#Public"
	to := toStringSlice(note["to"])
	cc := toStringSlice(note["cc"])
	all := append(to, cc...)
	addressed := false
	for _, r := range all {
		if r == public || r == "as:Public" || r == "Public" {
			return false // public post, not a DM
		}
		if r == actorURL {
			addressed = true
		}
	}
	return addressed
}

// ---------------------------------------------------------------------------
// Outbox handler
// ---------------------------------------------------------------------------

// handleNote serves an individual Note by its ID.
// If the ServeNote hook is set, it is called first; if it returns true the
// request is considered handled. Otherwise the outbox is searched for a
// Create{Note} whose embedded Note id matches the requested URL.
func (s *Server) handleNote(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	noteURL := "https://" + s.cfg.Domain + r.URL.Path

	// Give the application a chance to serve notes not yet in the outbox.
	if s.hooks.ServeNote != nil {
		if s.hooks.ServeNote(w, r, noteURL) {
			return
		}
	}

	// Fall through to outbox lookup.
	var note map[string]any
	s.mu.RLock()
	for _, item := range s.outbox {
		if obj, ok := item["object"].(map[string]any); ok {
			if obj["id"] == noteURL {
				note = obj
				break
			}
		}
	}
	s.mu.RUnlock()

	if note == nil {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "application/activity+json")
	writeJSON(w, note)
}

func (s *Server) handleOutbox(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	s.mu.RLock()
	all := make([]map[string]any, len(s.outbox))
	copy(all, s.outbox)
	s.mu.RUnlock()

	// Serve the full outbox including Tombstones so remote servers can
	// discover retractions. Filtering happens only in the HTML profile view
	// and the Outbox() getter used by the backend UI.
	s.serveOrderedCollection(w, all, s.actorURL()+"/outbox")
}

// ---------------------------------------------------------------------------
// Followers / Following handlers
// ---------------------------------------------------------------------------

func (s *Server) handleFollowers(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	s.mu.RLock()
	items := make([]string, len(s.followers))
	copy(items, s.followers)
	s.mu.RUnlock()

	// Convert []string to []map[string]any for the collection helper
	var objs []map[string]any
	for _, u := range items {
		objs = append(objs, map[string]any{"id": u, "type": "Person"})
	}
	s.serveOrderedCollection(w, objs, s.actorURL()+"/followers")
}

func (s *Server) handleFollowing(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	s.mu.RLock()
	items := make([]string, len(s.following))
	copy(items, s.following)
	s.mu.RUnlock()

	var objs []map[string]any
	for _, u := range items {
		objs = append(objs, map[string]any{"id": u, "type": "Person"})
	}
	s.serveOrderedCollection(w, objs, s.actorURL()+"/following")
}

// ---------------------------------------------------------------------------
// Activity delivery (server-to-server)
// ---------------------------------------------------------------------------

// deliverToFollowers fans out an activity to all known followers' inboxes.
func (s *Server) deliverToFollowers(activity map[string]any) error {
	s.mu.RLock()
	followers := make([]string, len(s.followers))
	copy(followers, s.followers)
	s.mu.RUnlock()

	// Collapse to one inbox per hostname (use sharedInbox where available).
	inboxes := map[string]struct{}{}
	for _, followerActorURL := range followers {
		inbox, err := s.resolveInbox(followerActorURL)
		if err != nil {
			log.Printf("activitypub: resolve inbox for %s: %v", followerActorURL, err)
			continue
		}
		inboxes[inbox] = struct{}{}
	}

	var lastErr error
	for inbox := range inboxes {
		if err := s.postActivity(inbox, activity); err != nil {
			log.Printf("activitypub: deliver to %s: %v", inbox, err)
			lastErr = err
		}
	}
	return lastErr
}

// sendAcceptFollow sends an Accept{Follow} to the follower's inbox.
func (s *Server) sendAcceptFollow(followerActorURL string, followActivity map[string]any) {
	inbox, err := s.resolveInbox(followerActorURL)
	if err != nil {
		log.Printf("activitypub: resolve inbox for accept: %v", err)
		return
	}
	accept := map[string]any{
		"@context": "https://www.w3.org/ns/activitystreams",
		"id":       fmt.Sprintf("%s#accepts/%d", s.actorURL(), time.Now().UnixNano()),
		"type":     "Accept",
		"actor":    s.actorURL(),
		"object":   followActivity,
	}
	if err := s.postActivity(inbox, accept); err != nil {
		log.Printf("activitypub: send Accept: %v", err)
	}
}

// sendRejectFollow sends a Reject{Follow} to the follower's inbox.
func (s *Server) sendRejectFollow(followerActorURL string, followActivity map[string]any) {
	inbox, err := s.resolveInbox(followerActorURL)
	if err != nil {
		log.Printf("activitypub: resolve inbox for reject: %v", err)
		return
	}
	reject := map[string]any{
		"@context": "https://www.w3.org/ns/activitystreams",
		"id":       fmt.Sprintf("%s#rejects/%d", s.actorURL(), time.Now().UnixNano()),
		"type":     "Reject",
		"actor":    s.actorURL(),
		"object":   followActivity,
	}
	if err := s.postActivity(inbox, reject); err != nil {
		log.Printf("activitypub: send Reject: %v", err)
	}
}

// resolveInbox fetches an actor document and returns the inbox URL.
// It prefers sharedInbox where available, and caches actor documents.
func (s *Server) resolveInbox(actorURL string) (string, error) {
	actor, err := s.fetchActor(actorURL)
	if err != nil {
		return "", err
	}
	// Prefer sharedInbox
	if ep, ok := actor["endpoints"].(map[string]any); ok {
		if si, ok := ep["sharedInbox"].(string); ok && si != "" {
			return si, nil
		}
	}
	if inbox, ok := actor["inbox"].(string); ok && inbox != "" {
		return inbox, nil
	}
	// Fallback: guess /inbox on the same host
	u, err := url.Parse(actorURL)
	if err != nil {
		return "", fmt.Errorf("invalid actor URL: %w", err)
	}
	return fmt.Sprintf("%s://%s/inbox", u.Scheme, u.Host), nil
}

// fetchActor retrieves and caches a remote actor document.
func (s *Server) fetchActor(actorURL string) (map[string]any, error) {
	s.actorCacheMu.RLock()
	if actor, ok := s.actorCache[actorURL]; ok {
		s.actorCacheMu.RUnlock()
		return actor, nil
	}
	s.actorCacheMu.RUnlock()

	req, err := http.NewRequest(http.MethodGet, actorURL, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Accept", "application/activity+json, application/ld+json")
	if err := s.signRequest(req, nil); err != nil {
		return nil, fmt.Errorf("sign actor fetch: %w", err)
	}

	resp, err := newSafeClient(10 * time.Second).Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusGone {
		return nil, errActorGone
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("actor fetch returned %d", resp.StatusCode)
	}

	var actor map[string]any
	if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&actor); err != nil {
		return nil, fmt.Errorf("decode actor: %w", err)
	}

	s.actorCacheMu.Lock()
	s.actorCache[actorURL] = actor
	s.actorCacheMu.Unlock()
	return actor, nil
}

// RedirectPolicy controls whether FetchObject resolves redirects before
// signing. Use FollowRedirects when the URL may be a local alias pointing
// to a post on a different instance; use NoRedirects when the URL is
// already canonical.
type RedirectPolicy bool

const (
	// FollowRedirects resolves any redirect first with an unsigned request,
	// then performs a fresh signed GET to the final URL.
	FollowRedirects RedirectPolicy = true
	// NoRedirects sends a single signed GET directly to the given URL.
	NoRedirects RedirectPolicy = false
)

// FetchObject performs a signed GET for an arbitrary AP object URL, returning
// the parsed JSON. Unlike fetchActor it does not cache.
//
// If policy is FollowRedirects, redirects are resolved first with an unsigned
// request and the final URL is then fetched with a fresh signature.
// This is needed when the input URL may be a local alias (e.g. a mastodon.xyz
// permalink for a post on merveilles.town) — the signature must be computed
// for the destination host, not the redirect source.
//
// If policy is NoRedirects, the request goes directly to objectURL with no
// redirect following; use this when objectURL is already canonical.
func (s *Server) FetchObject(objectURL string, policy RedirectPolicy) (map[string]any, error) {
	finalURL := objectURL
	if policy == FollowRedirects {
		// Resolve redirects with a no-follow client to find the canonical URL.
		// The safe client blocks private IPs even on the redirect target.
		noFollow := newSafeClient(10 * time.Second)
		noFollow.CheckRedirect = func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		}
		resolveReq, err := http.NewRequest(http.MethodGet, objectURL, nil)
		if err != nil {
			return nil, err
		}
		resolveReq.Header.Set("Accept", "application/activity+json, application/ld+json")
		resolveResp, err := noFollow.Do(resolveReq)
		if err != nil {
			return nil, fmt.Errorf("resolve redirect: %w", err)
		}
		resolveResp.Body.Close()
		if loc := resolveResp.Header.Get("Location"); loc != "" {
			finalURL = loc
			log.Printf("activitypub: FetchObject: redirect %s -> %s", objectURL, finalURL)
		}
	}

	req, err := http.NewRequest(http.MethodGet, finalURL, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Accept", "application/activity+json, application/ld+json")
	if err := s.signRequest(req, nil); err != nil {
		return nil, fmt.Errorf("sign object fetch: %w", err)
	}
	// No-redirect safe client: the signed request must go exactly to finalURL.
	fetchClient := newSafeClient(10 * time.Second)
	fetchClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		return http.ErrUseLastResponse
	}
	resp, err := fetchClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("object fetch returned %d", resp.StatusCode)
	}
	ct := resp.Header.Get("Content-Type")
	if !strings.Contains(ct, "activity+json") && !strings.Contains(ct, "ld+json") {
		return nil, fmt.Errorf("object fetch returned non-AP content-type %q", ct)
	}
	var obj map[string]any
	if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&obj); err != nil {
		return nil, fmt.Errorf("decode object: %w", err)
	}
	return obj, nil
}

// postActivity JSON-encodes an activity and POSTs it to the given inbox URL,
// signed with this server's private key.
func (s *Server) postActivity(inboxURL string, activity map[string]any) error {
	body, err := json.Marshal(activity)
	if err != nil {
		return fmt.Errorf("marshal activity: %w", err)
	}

	req, err := http.NewRequest(http.MethodPost, inboxURL, bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/activity+json")
	req.Header.Set("Accept", "application/activity+json")
	if err := s.signRequest(req, body); err != nil {
		return fmt.Errorf("sign request: %w", err)
	}

	// ap-next guide §Network — Delivering activities:
	// "Do not follow redirects."
	// A redirect on inbox delivery would invalidate the HTTP signature
	// (the signed (request-target) and Host headers no longer match).
	deliverClient := newSafeClient(15 * time.Second)
	deliverClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
		return http.ErrUseLastResponse
	}
	resp, err := deliverClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf("inbox returned HTTP %d", resp.StatusCode)
	}
	return nil
}

// ---------------------------------------------------------------------------
// HTTP Signatures — signing (draft-cavage-12 profile)
// ---------------------------------------------------------------------------
//
// Signed headers: (request-target) host date digest content-type (if present)
// Algorithm: hs2019 (rsa-sha256 in practice)
//
// Signature header format (all on one line):
//
//	Signature: keyId="...",algorithm="hs2019",headers="...",signature="..."

func (s *Server) signRequest(req *http.Request, body []byte) error {
	now := time.Now().UTC()
	req.Header.Set("Date", now.Format(http.TimeFormat))
	req.Header.Set("Host", req.URL.Host)
	// ap-next guide §Network: "Add User-Agent header."
	req.Header.Set("User-Agent", "activitypub-go/1.0 (https://"+s.cfg.Domain+")")

	// Build (request-target) pseudo-header value
	requestTarget := strings.ToLower(req.Method) + " " + req.URL.RequestURI()

	// Compute body digest (required for POST; included for GET too for consistency)
	digestHeader := ""
	if body != nil {
		sum := sha256.Sum256(body)
		digestHeader = "SHA-256=" + base64.StdEncoding.EncodeToString(sum[:])
		req.Header.Set("Digest", digestHeader)
	}

	// Determine which headers to sign and build the signing string
	type headerPair struct{ name, value string }
	var pairs []headerPair
	pairs = append(pairs, headerPair{"(request-target)", requestTarget})
	pairs = append(pairs, headerPair{"host", req.Header.Get("Host")})
	pairs = append(pairs, headerPair{"date", req.Header.Get("Date")})
	if digestHeader != "" {
		pairs = append(pairs, headerPair{"digest", digestHeader})
	}
	if ct := req.Header.Get("Content-Type"); ct != "" {
		pairs = append(pairs, headerPair{"content-type", ct})
	}

	var signingLines []string
	var headerNames []string
	for _, p := range pairs {
		signingLines = append(signingLines, p.name+": "+p.value)
		headerNames = append(headerNames, p.name)
	}
	signingString := strings.Join(signingLines, "\n")

	// RSA-SHA256 signature over the signing string
	hash := sha256.Sum256([]byte(signingString))
	sig, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, crypto.SHA256, hash[:])
	if err != nil {
		return fmt.Errorf("sign: %w", err)
	}
	sigB64 := base64.StdEncoding.EncodeToString(sig)

	keyID := s.actorURL() + "#main-key"
	headerList := strings.Join(headerNames, " ")
	req.Header.Set("Signature", fmt.Sprintf(
		`keyId="%s",algorithm="hs2019",headers="%s",signature="%s"`,
		keyID, headerList, sigB64,
	))
	return nil
}

// ---------------------------------------------------------------------------
// HTTP Signatures — verification (draft-cavage-12 profile)
// ---------------------------------------------------------------------------

// verifyHTTPSignature verifies the HTTP Signature on an incoming request.
// Returns the actor URL (keyId without fragment) on success.
// Only GET and POST requests are supported; any other method is rejected.
func (s *Server) verifyHTTPSignature(r *http.Request, body []byte) (string, error) {
	if r.Method != http.MethodGet && r.Method != http.MethodPost {
		return "", fmt.Errorf("HTTP method %q not supported for signature verification", r.Method)
	}

	sigHeader := r.Header.Get("Signature")
	if sigHeader == "" {
		return "", errors.New("missing Signature header")
	}

	// Parse the Signature header into key-value pairs
	sigParams := parseSignatureHeader(sigHeader)

	keyID, ok := sigParams["keyId"]
	if !ok {
		return "", errors.New("missing keyId in Signature header")
	}
	headersParam, ok := sigParams["headers"]
	if !ok {
		return "", errors.New("missing headers in Signature header")
	}
	sigB64, ok := sigParams["signature"]
	if !ok {
		return "", errors.New("missing signature value in Signature header")
	}

	// Validate the optional algorithm parameter against our key type.
	//
	// draft-cavage-http-signatures-12 §2.1.3:
	//   "Implementers SHOULD derive the digital signature algorithm used by
	//   an implementation from the key metadata identified by the keyId
	//   rather than from this field. If algorithm is provided and differs
	//   from the key metadata identified by the keyId … then an
	//   implementation MUST produce an error."
	//
	// All keys in this implementation are RSA, so the only acceptable
	// declared algorithms are "hs2019" (the generic placeholder from
	// cavage-12 that defers algorithm selection to key metadata) and
	// "rsa-sha256" (explicitly RSA-SHA256, consistent with our keys).
	// Anything else — "hmac-sha256", "ecdsa-sha256", "rsa-sha1", etc. —
	// is inconsistent with an RSA key and must be rejected.
	if algo, hasAlgo := sigParams["algorithm"]; hasAlgo {
		if algo != "hs2019" && algo != "rsa-sha256" {
			return "", fmt.Errorf("signature algorithm %q is incompatible with RSA key", algo)
		}
	}

	signedHeaders := strings.Fields(headersParam)

	// Enforce a minimum set of signed headers to prevent replay attacks.
	//
	// https://swicg.github.io/activitypub-http-signature/#how-to-verify-a-signature
	//   "Most fediverse software will reject GET requests without signed
	//   (request-target), and POST requests without signed Digest, in order
	//   to prevent replay attacks."
	requiredSigned := []string{"(request-target)", "host", "date"}
	if r.Method == http.MethodPost {
		requiredSigned = append(requiredSigned, "digest")
	}
	signedSet := make(map[string]bool, len(signedHeaders))
	for _, h := range signedHeaders {
		signedSet[h] = true
	}
	for _, required := range requiredSigned {
		if !signedSet[required] {
			return "", fmt.Errorf("required header %q not covered by signature", required)
		}
	}

	// Validate Date header is within ±1 hour (plus a few minutes buffer)
	dateStr := r.Header.Get("Date")
	if dateStr == "" {
		return "", errors.New("missing Date header")
	}
	reqTime, err := http.ParseTime(dateStr)
	if err != nil {
		return "", fmt.Errorf("parse Date header: %w", err)
	}
	diff := time.Since(reqTime)
	if diff < 0 {
		diff = -diff
	}
	if diff > 70*time.Minute {
		return "", fmt.Errorf("Date header too far from current time (%v)", diff)
	}

	// For POST requests the Digest header is required and must be present in
	// the request (it must also be covered by the signature, enforced above).
	// For other methods verify it if present but don't require it.
	//
	// https://swicg.github.io/activitypub-http-signature/#how-to-verify-a-signature
	//   "If the request has a body, compare it to the Digest header. If they
	//   don't match, the signature is invalid, and most fediverse software
	//   will reject it in order to prevent replay attacks."
	digestHeader := r.Header.Get("Digest")
	if r.Method == http.MethodPost && digestHeader == "" {
		return "", errors.New("POST request missing required Digest header")
	}
	if digestHeader != "" {
		if err := verifyDigest(body, digestHeader); err != nil {
			return "", fmt.Errorf("body digest mismatch: %w", err)
		}
	}

	// Reconstruct the signing string.
	// NOTE: Go's net/http moves the Host header out of r.Header into r.Host,
	// so we must read it from r.Host directly.
	var signingLines []string
	for _, hdr := range signedHeaders {
		var val string
		switch hdr {
		case "(request-target)":
			val = strings.ToLower(r.Method) + " " + r.URL.RequestURI()
		case "host":
			// r.Host holds the Host header value; r.Header["Host"] is empty
			val = r.Host
		default:
			val = r.Header.Get(http.CanonicalHeaderKey(hdr))
		}
		line := hdr + ": " + val
		signingLines = append(signingLines, line)
	}
	signingString := strings.Join(signingLines, "\n")

	// Obtain the public key for this keyId
	pubKey, actorURL, err := s.obtainPublicKey(keyID)
	if err != nil {
		return "", fmt.Errorf("obtain public key for %s: %w", keyID, err)
	}

	// Verify RSA-SHA256 signature
	sigBytes, err := base64.StdEncoding.DecodeString(sigB64)
	if err != nil {
		return "", fmt.Errorf("decode signature base64: %w", err)
	}
	hash := sha256.Sum256([]byte(signingString))
	if err := rsa.VerifyPKCS1v15(pubKey, crypto.SHA256, hash[:], sigBytes); err != nil {
		log.Printf("activitypub: RSA verify failed with cached key, re-fetching: %v", err)
		// Key may have rotated — evict cache and retry once
		s.actorCacheMu.Lock()
		delete(s.actorCache, actorURL)
		s.actorCacheMu.Unlock()
		pubKey2, _, err2 := s.obtainPublicKey(keyID)
		if err2 != nil {
			return "", fmt.Errorf("signature verification failed (and key re-fetch failed: %v)", err2)
		}
		if err3 := rsa.VerifyPKCS1v15(pubKey2, crypto.SHA256, hash[:], sigBytes); err3 != nil {
			return "", fmt.Errorf("signature verification failed: %w", err3)
		}
	}

	return actorURL, nil
}

// obtainPublicKey fetches the actor document for the given keyId and extracts
// the RSA public key from publicKey.publicKeyPem.
// Returns (publicKey, actorURL, error).
func (s *Server) obtainPublicKey(keyID string) (*rsa.PublicKey, string, error) {
	// Strip the #fragment to get the actor URL
	actorURL := keyID
	if before, _, ok := strings.Cut(keyID, "#"); ok {
		actorURL = before
	}

	actor, err := s.fetchActor(actorURL)
	if err != nil {
		return nil, actorURL, fmt.Errorf("fetch actor: %w", err)
	}

	pkObj, ok := actor["publicKey"]
	if !ok {
		return nil, actorURL, errors.New("actor has no publicKey")
	}

	// publicKey may be a map or a list; handle both
	var pkMap map[string]any
	switch v := pkObj.(type) {
	case map[string]any:
		pkMap = v
	case []any:
		// Find the key whose id matches our keyId
		for _, item := range v {
			if m, ok := item.(map[string]any); ok {
				if id, _ := m["id"].(string); id == keyID {
					pkMap = m
					break
				}
			}
		}
	}
	if pkMap == nil {
		return nil, actorURL, fmt.Errorf("could not find publicKey with id %s", keyID)
	}

	// Verify key id matches
	if pkID, _ := pkMap["id"].(string); pkID != keyID {
		return nil, actorURL, fmt.Errorf("publicKey id %q does not match keyId %q", pkID, keyID)
	}

	pemStr, ok := pkMap["publicKeyPem"].(string)
	if !ok || pemStr == "" {
		return nil, actorURL, errors.New("publicKeyPem missing or empty")
	}

	pub, err := parsePublicKeyPEM(pemStr)
	if err != nil {
		return nil, actorURL, fmt.Errorf("parse publicKeyPem: %w", err)
	}
	return pub, actorURL, nil
}

// sameOrigin reports whether two URL strings share the same origin.
//
// Origin is defined as the (scheme, host, port) triple per RFC 6454 §3.2 and
// FEP-fe34 §Origin. url.Parse stores host and port together in the Host field,
// so comparing Host directly covers both. Schemes are compared
// case-insensitively. Returns false if either URL cannot be parsed.
func sameOrigin(a, b string) bool {
	ua, err := url.Parse(a)
	if err != nil {
		return false
	}
	ub, err := url.Parse(b)
	if err != nil {
		return false
	}
	// url.Parse stores host:port together in Host; scheme is already lowercase.
	return strings.ToLower(ua.Scheme) == strings.ToLower(ub.Scheme) &&
		strings.ToLower(ua.Host) == strings.ToLower(ub.Host)
}

// sameOwner reports whether two actor URL strings refer to the same owner.
//
// FEP-fe34 §Comparing owners:
//
//	"Owners are the same if their identifiers are identical after conversion
//	of their schemes and hosts to lowercase."
//
// Scheme and host are case-folded; the path, query, and fragment are compared
// exactly (actor paths like /users/Alice and /users/alice are distinct).
// Returns false if either URL cannot be parsed.
func sameOwner(a, b string) bool {
	ua, err := url.Parse(a)
	if err != nil {
		return false
	}
	ub, err := url.Parse(b)
	if err != nil {
		return false
	}
	return strings.ToLower(ua.Scheme) == strings.ToLower(ub.Scheme) &&
		strings.ToLower(ua.Host) == strings.ToLower(ub.Host) &&
		ua.Path == ub.Path &&
		ua.RawQuery == ub.RawQuery
}

// verifyDigest checks the SHA-256 body digest against the Digest header value.
func verifyDigest(body []byte, digestHeader string) error {
	if !strings.HasPrefix(digestHeader, "SHA-256=") {
		return fmt.Errorf("unsupported digest algorithm in %q", digestHeader)
	}
	expected := strings.TrimPrefix(digestHeader, "SHA-256=")
	sum := sha256.Sum256(body)
	actual := base64.StdEncoding.EncodeToString(sum[:])
	if actual != expected {
		return fmt.Errorf("expected %s, got %s", expected, actual)
	}
	return nil
}

// parseSignatureHeader parses a cavage-12 Signature header value into a map.
// Example input:
//
//	keyId="https://example.com/users/alice#main-key",algorithm="hs2019",headers="...",signature="..."
//
// Values are quoted strings per RFC 7235 §4.1. We split on ',' only outside
// quoted strings (tracked with a simple bool toggle), then strip the surrounding
// quotes from each value. This correctly handles commas and '=' characters
// inside quoted values (e.g. base64 signatures with padding, URLs with query
// strings).
func parseSignatureHeader(header string) map[string]string {
	result := map[string]string{}

	// Split on ',' outside quoted strings.
	var parts []string
	inQuote := false
	start := 0
	for i, ch := range header {
		switch ch {
		case '"':
			inQuote = !inQuote
		case ',':
			if !inQuote {
				parts = append(parts, header[start:i])
				start = i + 1
			}
		}
	}
	parts = append(parts, header[start:])

	for _, part := range parts {
		part = strings.TrimSpace(part)
		// Split on the first '=' only; values may contain '=' (base64 padding).
		before, after, ok := strings.Cut(part, "=")
		if !ok {
			continue
		}
		key := strings.TrimSpace(before)
		val := strings.TrimSpace(after)
		// Strip surrounding double-quotes from the value.
		val = strings.Trim(val, `"`)
		result[key] = val
	}
	return result
}

// ---------------------------------------------------------------------------
// Activity construction helpers
// ---------------------------------------------------------------------------

func (s *Server) buildAnnounce(objectURL string) map[string]any {
	id := fmt.Sprintf("%s/announces/%d", s.actorURL(), time.Now().UnixNano())
	return map[string]any{
		"@context":  "https://www.w3.org/ns/activitystreams",
		"id":        id,
		"type":      "Announce",
		"actor":     s.actorURL(),
		"object":    objectURL,
		"published": time.Now().UTC().Format(time.RFC3339),
		"to":        []string{"https://www.w3.org/ns/activitystreams#Public"},
		"cc":        []string{s.actorURL() + "/followers"},
	}
}

// ---------------------------------------------------------------------------
// OrderedCollection serialisation
// ---------------------------------------------------------------------------

func (s *Server) serveOrderedCollection(w http.ResponseWriter, items []map[string]any, id string) {
	col := map[string]any{
		"@context":     "https://www.w3.org/ns/activitystreams",
		"id":           id,
		"type":         "OrderedCollection",
		"totalItems":   len(items),
		"orderedItems": items,
	}
	w.Header().Set("Content-Type", "application/activity+json")
	writeJSON(w, col)
}

// ---------------------------------------------------------------------------
// Key management
// ---------------------------------------------------------------------------

func (s *Server) loadOrGenerateKey() (*rsa.PrivateKey, error) {
	f, err := s.root.Open("key.pem")
	if err == nil {
		// File exists — parse it
		data, readErr := io.ReadAll(f)
		f.Close()
		if readErr != nil {
			return nil, fmt.Errorf("activitypub: read key file: %w", readErr)
		}
		block, _ := pem.Decode(data)
		if block == nil {
			return nil, fmt.Errorf("activitypub: failed to decode PEM block from key.pem")
		}
		key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
		if err != nil {
			return nil, fmt.Errorf("activitypub: parse private key: %w", err)
		}
		log.Printf("activitypub: loaded RSA key from %s/key.pem", s.cfg.DataDir)
		return key, nil
	}
	if !errors.Is(err, os.ErrNotExist) {
		return nil, fmt.Errorf("activitypub: read key file: %w", err)
	}

	// Generate a new 2048-bit RSA key
	log.Printf("activitypub: generating new RSA-2048 key, saving to %s/key.pem", s.cfg.DataDir)
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, fmt.Errorf("activitypub: generate key: %w", err)
	}
	pemData := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	})
	wf, err := s.root.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
	if err != nil {
		return nil, fmt.Errorf("activitypub: create key file: %w", err)
	}
	_, werr := wf.Write(pemData)
	cerr := wf.Close()
	if werr != nil {
		return nil, fmt.Errorf("activitypub: save key: %w", werr)
	}
	if cerr != nil {
		return nil, fmt.Errorf("activitypub: close key file: %w", cerr)
	}
	return key, nil
}

// publicKeyPEM returns the PEM-encoded public key for the actor document.
// Uses PKIX/SPKI encoding ("BEGIN PUBLIC KEY") which is what Mastodon and
// most fediverse servers expect. PKCS#1 ("BEGIN RSA PUBLIC KEY") is not
// widely recognised by AP implementations.
func (s *Server) publicKeyPEM() (string, error) {
	pub, err := x509.MarshalPKIXPublicKey(s.publicKey)
	if err != nil {
		return "", err
	}
	block := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pub,
	}
	return string(pem.EncodeToMemory(block)), nil
}

// parsePublicKeyPEM parses a PEM-encoded RSA public key (PKCS#1 or SPKI/X.509).
func parsePublicKeyPEM(pemStr string) (*rsa.PublicKey, error) {
	block, _ := pem.Decode([]byte(pemStr))
	if block == nil {
		return nil, errors.New("failed to decode PEM block")
	}
	// Try PKCS#1 first
	if key, err := x509.ParsePKCS1PublicKey(block.Bytes); err == nil {
		return key, nil
	}
	// Try X.509 SPKI (used by most fediverse servers)
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("parse public key: %w", err)
	}
	rsaKey, ok := pub.(*rsa.PublicKey)
	if !ok {
		return nil, errors.New("public key is not RSA")
	}
	return rsaKey, nil
}

// ---------------------------------------------------------------------------
// WebFinger client — handle resolution
// ---------------------------------------------------------------------------

// ResolveHandle resolves a fediverse handle to an actor URL via WebFinger.
// Accepts "@alice@example.com" or "alice@example.com".
// Signs the WebFinger GET with this server's key (supports authorized fetch).
func (s *Server) ResolveHandle(handle string) (string, error) {
	// Normalise: strip a single leading @ if present
	handle = strings.TrimPrefix(handle, "@")
	parts := strings.SplitN(handle, "@", 2)
	if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
		return "", fmt.Errorf("invalid fediverse handle %q: expected user@host", handle)
	}
	user, host := parts[0], parts[1]

	wfURL := fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s@%s",
		host, url.QueryEscape(user), host)

	req, err := http.NewRequest(http.MethodGet, wfURL, nil)
	if err != nil {
		return "", fmt.Errorf("build webfinger request: %w", err)
	}
	req.Header.Set("Accept", "application/jrd+json, application/json")
	// Sign so servers with authorized fetch enabled will respond
	if err := s.signRequest(req, nil); err != nil {
		return "", fmt.Errorf("sign webfinger request: %w", err)
	}

	resp, err := newSafeClient(10 * time.Second).Do(req)
	if err != nil {
		return "", fmt.Errorf("webfinger request: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("webfinger returned HTTP %d", resp.StatusCode)
	}

	var wf struct {
		Links []struct {
			Rel  string `json:"rel"`
			Type string `json:"type"`
			Href string `json:"href"`
		} `json:"links"`
	}
	if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&wf); err != nil {
		return "", fmt.Errorf("decode webfinger response: %w", err)
	}

	for _, link := range wf.Links {
		if link.Rel == "self" &&
			(link.Type == "application/activity+json" ||
				link.Type == "application/ld+json") &&
			link.Href != "" {
			return link.Href, nil
		}
	}
	return "", fmt.Errorf("no ActivityPub actor link found in WebFinger response for %s@%s", user, host)
}

// ---------------------------------------------------------------------------
// URL helpers
// ---------------------------------------------------------------------------

// Domain returns the configured domain for this server.
func (s *Server) Domain() string {
	return s.cfg.Domain
}

// ActorName returns the actor's username (the name component of its URL).
func (s *Server) ActorName() string {
	return s.cfg.ActorName
}

// ActorURL returns the canonical actor URL for this server.
func (s *Server) ActorURL() string {
	return s.actorURL()
}

func (s *Server) baseURL() string {
	return "https://" + s.cfg.Domain
}

func (s *Server) actorURL() string {
	return s.baseURL() + "/users/" + s.cfg.ActorName
}

// ---------------------------------------------------------------------------
// JSON persistence
// ---------------------------------------------------------------------------

func (s *Server) loadJSON(filename string, v any) error {
	f, err := s.root.Open(filename)
	if err != nil {
		return err
	}
	defer f.Close()
	data, err := io.ReadAll(f)
	if err != nil {
		return err
	}
	return json.Unmarshal(data, v)
}

func (s *Server) saveJSON(filename string, v any) error {
	data, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		return err
	}
	// Atomic write via temp file + rename.
	// os.Root does not yet have Rename, so we use os.Rename with full paths.
	// Both paths are constructed from cfg.DataDir which is already validated
	// by the os.Root we hold.
	tmp := filename + ".tmp"
	wf, err := s.root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
	if err != nil {
		return err
	}
	_, werr := wf.Write(data)
	cerr := wf.Close()
	if werr != nil {
		return werr
	}
	if cerr != nil {
		return cerr
	}
	return os.Rename(
		filepath.Join(s.cfg.DataDir, tmp),
		filepath.Join(s.cfg.DataDir, filename),
	)
}

func (s *Server) saveFollowers() error {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.saveJSON("followers.json", s.followers)
}

func (s *Server) saveFollowing() error {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.saveJSON("following.json", s.following)
}

func (s *Server) saveOutbox() error {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.saveJSON("outbox.json", s.outbox)
}

func (s *Server) saveInbox() error {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.saveJSON("inbox.json", s.inbox)
}

// ---------------------------------------------------------------------------
// Generic helpers
// ---------------------------------------------------------------------------

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/activity+json")
	writeJSONRaw(w, v)
}

// writeJSONRaw encodes v as indented JSON without setting Content-Type,
// allowing the caller to set it beforehand.
func writeJSONRaw(w http.ResponseWriter, v any) {
	enc := json.NewEncoder(w)
	enc.SetIndent("", "  ")
	if err := enc.Encode(v); err != nil {
		log.Printf("activitypub: write JSON: %v", err)
	}
}

// stringField safely extracts a string field from a map.
func stringField(m map[string]any, key string) string {
	v, _ := m[key].(string)
	return v
}

// toStringSlice converts an any that may be a string or []any of strings
// into a []string.
func toStringSlice(v any) []string {
	switch t := v.(type) {
	case string:
		return []string{t}
	case []any:
		var result []string
		for _, item := range t {
			if s, ok := item.(string); ok {
				result = append(result, s)
			}
		}
		return result
	default:
		return nil
	}
}

// contains returns true if s is in slice.
func contains(slice []string, s string) bool {
	return slices.Contains(slice, s)
}

// remove returns a new slice with all occurrences of s removed.
func remove(slice []string, s string) []string {
	var result []string
	for _, v := range slice {
		if v != s {
			result = append(result, v)
		}
	}
	return result
}

// prependCapped inserts item at the front of slice and caps its length at max.
func prependCapped(slice []map[string]any, item map[string]any, max int) []map[string]any {
	result := make([]map[string]any, 0, len(slice)+1)
	result = append(result, item)
	result = append(result, slice...)
	if len(result) > max {
		result = result[:max]
	}
	return result
}