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
// link-booster: an ActivityPub bot that boosts links sent to it via DM.
//
// Static config (domain, port, admins) lives in config.json.
// The list of actors is read from <data_dir>/actors.json at startup.
// Per-actor config (summary, allowlist/curators) lives in
// <data_dir>/actors/<name>/actor.json and is read on every request so
// changes take effect immediately without restarting the server.
//
// Usage:
//
//	go run . [-config ./config.json]
package main

import (
	"bytes"
	"crypto/rand"
	"database/sql"
	"embed"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"html/template"
	"image"
	_ "image/gif"
	"image/jpeg"
	_ "image/png"
	"io"
	"log"
	"math/big"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"slices"
	"strings"
	"sync"
	"time"

	"activitypub"
	"golang.org/x/image/draw"
	_ "golang.org/x/image/webp"
)

// ---------------------------------------------------------------------------
// Templates
// ---------------------------------------------------------------------------

//go:embed templates/*.html
var templateFS embed.FS

func mustParseTemplate(files ...string) *template.Template {
	// Always include base.html so every page template has access to {{template "base" .}}
	files = append([]string{"templates/base.html"}, files...)
	return template.Must(template.ParseFS(templateFS, files...))
}

var (
	tmplLoginForm = mustParseTemplate("templates/login_form.html")
	tmplLoginPin  = mustParseTemplate("templates/login_pin.html")
	tmplPicker    = mustParseTemplate("templates/picker.html")
	tmplDashboard = mustParseTemplate("templates/dashboard.html")
)

func renderTemplate(w http.ResponseWriter, t *template.Template, data any) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := t.ExecuteTemplate(w, "base", data); err != nil {
		log.Printf("template render: %v", err)
	}
}

// Template data structs

type loginFormData struct{}

type loginPinData struct {
	BotHandle string
	Handle    string
	PIN       string
	Token     string
	Msg       string
}

type pickerData struct {
	Handle      string
	VisibleBots []string
	IsAdmin     bool
}

// statusRecorder wraps http.ResponseWriter to capture the response status code.
type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (r *statusRecorder) WriteHeader(status int) {
	r.status = status
	r.ResponseWriter.WriteHeader(status)
}

type outboxItem struct {
	Object    string
	Published string
	Snippet   string
	OpenURL   string
	Kind      string // "boost" or "quote"
}

type curatorItem struct {
	Handle string
	URL    string
}

type dashboardData struct {
	ActorName     string
	BotOpenURL    string
	UserInstance  string
	Handle        string
	VisibleBots   []string
	AllActorsLink bool
	Curators      []curatorItem
	Outbox        []outboxItem
	IsAdmin       bool
	// admin-only
	DisplayName string
	Summary     string
	Allowlist   string
	AvatarURL   string
}

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

// Config is the static server configuration loaded from config.json.
// Requires a restart to change.
type Config struct {
	Domain         string   `json:"domain"`
	Port           string   `json:"port"`
	DataDir        string   `json:"data_dir"`
	Admins         []string `json:"admins"`          // actor URLs that may use the web UI
	BootstrapToken string   `json:"bootstrap_token"` // one-time token for first login when no actors exist
}

// ActorEntry is one entry in <data_dir>/actors.json.
// The actor's data lives at <data_dir>/actors/<name>/.
type ActorEntry struct {
	Name string `json:"name"`
}

// ActorMeta is the per-actor dynamic config stored in
// <data_dir>/actors/<name>/actor.json.
// Read on every request; write via the web UI.
type ActorMeta struct {
	DisplayName string   `json:"display_name"`
	Summary     string   `json:"summary"`
	Allowlist   []string `json:"allowlist"` // curator actor URLs; empty means admins only
	AvatarID    string   `json:"avatar_id"` // random token, empty if no avatar
}

func loadConfig(path string) (Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return Config{}, err
	}
	defer f.Close()
	var cfg Config
	if err := json.NewDecoder(f).Decode(&cfg); err != nil {
		return Config{}, err
	}
	if cfg.Port == "" {
		cfg.Port = "8080"
	}
	if cfg.DataDir == "" {
		cfg.DataDir = "./data"
	}
	return cfg, nil
}

// actorDataDir returns the data directory path (relative to dataDir) for the
// named actor. Used only to construct the DataDir string passed to
// activitypub.New, which opens its own os.Root on that path.
func actorDataDir(dataDir, name string) string {
	return filepath.Join(dataDir, "actors", name)
}

// loadActors reads <data_dir>/actors.json.
// If the file does not exist, it returns an empty list.
func loadActors(dataDir string) ([]ActorEntry, error) {
	data, err := os.ReadFile(filepath.Join(dataDir, "actors.json"))
	if os.IsNotExist(err) {
		return []ActorEntry{}, nil
	}
	if err != nil {
		return nil, err
	}
	var entries []ActorEntry
	if err := json.Unmarshal(data, &entries); err != nil {
		return nil, err
	}
	return entries, nil
}

// saveActors writes <data_dir>/actors.json atomically.
func saveActors(dataDir string, entries []ActorEntry) error {
	data, err := json.MarshalIndent(entries, "", "  ")
	if err != nil {
		return err
	}
	tmp := filepath.Join(dataDir, "actors.json.tmp")
	if err := os.WriteFile(tmp, data, 0o644); err != nil {
		return err
	}
	return os.Rename(tmp, filepath.Join(dataDir, "actors.json"))
}

// loadActorMeta reads actors/<name>/actor.json relative to root.
// Returns an empty ActorMeta (not an error) if the file doesn't exist yet.
func loadActorMeta(root *os.Root, name string) (ActorMeta, error) {
	f, err := root.Open("actors/" + name + "/actor.json")
	if os.IsNotExist(err) {
		return ActorMeta{}, nil
	}
	if err != nil {
		return ActorMeta{}, err
	}
	defer f.Close()
	data, err := io.ReadAll(f)
	if err != nil {
		return ActorMeta{}, err
	}
	// Older versions of activitypub-go cached the AP actor document in this
	// very file, silently replacing our settings with it. Such a file still
	// unmarshals into ActorMeta without error — "summary" exists in both
	// schemas — yielding an empty allowlist that looks deliberate. Say so
	// loudly instead of quietly running with lost settings.
	var probe map[string]any
	if err := json.Unmarshal(data, &probe); err == nil {
		if _, isActorDoc := probe["publicKey"]; isActorDoc {
			log.Printf("WARNING: [%s] actor.json contains an ActivityPub actor "+
				"document, not this actor's settings — display name, curator "+
				"allowlist and avatar have been lost and need to be re-entered "+
				"in the web UI. Only admins may boost via DM until then.", name)
			return ActorMeta{}, nil
		}
	}
	var meta ActorMeta
	if err := json.Unmarshal(data, &meta); err != nil {
		return ActorMeta{}, err
	}
	return meta, nil
}

// saveActorMeta writes actors/<name>/actor.json atomically relative to root.
// dataDir is still needed for the os.Rename call since os.Root lacks Rename.
func saveActorMeta(root *os.Root, dataDir, name string, meta ActorMeta) error {
	dir := actorDataDir(dataDir, name)
	if err := os.MkdirAll(dir, 0o755); err != nil {
		return err
	}
	data, err := json.MarshalIndent(meta, "", "  ")
	if err != nil {
		return err
	}
	tmp := "actors/" + name + "/actor.json.tmp"
	wf, err := 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(dataDir, tmp),
		filepath.Join(dir, "actor.json"),
	)
}

// ---------------------------------------------------------------------------
// URL extraction
// ---------------------------------------------------------------------------

// hrefRe matches href="..." attributes in anchor tags.
// Mastodon wraps URLs in <a href="..."> with the visible text split across
// <span class="invisible">, <span class="ellipsis">, etc., so we must
// extract from href rather than from the stripped text content.
var hrefRe = regexp.MustCompile(`(?i)<a\s[^>]*href="(https?://[^"]+)"`)

// mentionClassRe identifies mention links we want to skip (user @-mentions).
var mentionClassRe = regexp.MustCompile(`(?i)class="[^"]*\bu-url mention\b[^"]*"`)

// plainURLRe catches bare URLs in plain-text content (fallback).
var plainURLRe = regexp.MustCompile(`https?://[^\s<>"]+`)

// extractURLs pulls https?:// URLs out of Mastodon-flavoured HTML content.
// It prefers href attributes of non-mention anchor tags; falls back to
// scanning stripped text for any remaining bare URLs.
func extractURLs(content string) []string {
	seen := map[string]bool{}
	var result []string

	add := func(u string) {
		u = strings.TrimRight(u, ".,;:!?)")
		if u != "" && !seen[u] {
			seen[u] = true
			result = append(result, u)
		}
	}

	// Extract from <a href="..."> — but skip mention links
	anchorRe := regexp.MustCompile(`(?i)<a\s([^>]*)>`)
	for _, m := range anchorRe.FindAllStringSubmatchIndex(content, -1) {
		attrs := content[m[2]:m[3]]
		if mentionClassRe.MatchString(attrs) {
			continue
		}
		if sub := hrefRe.FindStringSubmatch("<a " + attrs + ">"); len(sub) == 2 {
			add(sub[1])
		}
	}

	// Fallback: scan stripped text for bare URLs not caught above
	stripped := regexp.MustCompile(`<[^>]*>`).ReplaceAllString(content, " ")
	for _, u := range plainURLRe.FindAllString(stripped, -1) {
		add(u)
	}

	return result
}

// ---------------------------------------------------------------------------
// AP object resolution
// ---------------------------------------------------------------------------

// resolveAPObjectID fetches a URL with an ActivityPub Accept header and returns
// the canonical AP object id, converting HTML post URLs to their AP id.
// fetchAPObject fetches a URL with a signed AP GET and returns the parsed
// object plus the canonical AP id. Returns nil obj if the URL is not an AP
// object. Always uses HTTP signatures so servers requiring signed GETs work.
// Set followRedirects=true when the URL may be a local alias pointing to a
// post on a different instance (e.g. from a DM mention URL).
func fetchAPObject(rawURL string, srv *activitypub.Server, policy activitypub.RedirectPolicy) (obj map[string]any, apID string, err error) {
	fetched, err := srv.FetchObject(rawURL, policy)
	if err != nil {
		return nil, "", err
	}
	if id, ok := fetched["id"].(string); ok && id != "" {
		return fetched, id, nil
	}
	return nil, "", nil
}

// ---------------------------------------------------------------------------
// Per-actor setup
// ---------------------------------------------------------------------------

func setupActor(mux *http.ServeMux, domain, dataDir string, root *os.Root, db *sql.DB, admins []string, ae ActorEntry) (*activitypub.Server, *quotingState, error) {
	// Load initial meta to get summary and display name for the AP actor document.
	// The allowlist is re-read live from disk on every incoming DM.
	meta, err := loadActorMeta(root, ae.Name)
	if err != nil {
		return nil, nil, fmt.Errorf("load actor meta for %s: %w", ae.Name, err)
	}

	dir := actorDataDir(dataDir, ae.Name)
	srv, err := activitypub.New(activitypub.Config{
		Domain:    domain,
		ActorName: ae.Name,
		ActorType: "Service",
		Summary:   meta.Summary,
		DataDir:   dir,
	})
	if err != nil {
		return nil, nil, err
	}

	srv.SetDisplayName(meta.DisplayName)

	qs := newQuotingState()

	srv.SetHooks(activitypub.Hooks{
		OnFollow: func(followerActorURL string) activitypub.FollowDecision {
			log.Printf("[%s] new follower: %s", ae.Name, followerActorURL)
			return activitypub.AcceptFollow
		},

		OnAccept: func(activity map[string]any) {
			qs.handleAcceptActivity(activity)
		},

		OnReject: func(activity map[string]any) {
			qs.handleRejectActivity(activity)
		},

		ServeNote: qs.serveNoteHook,

		OnHTML: func(w http.ResponseWriter, r *http.Request) {
			actorHTML(w, srv)
		},

		OnDM: func(from, content, dmNoteID, inReplyTo string) {
			log.Printf("[%s] DM from %s: %s", ae.Name, from, content)
			checkLoginPin(from, content)

			// Helper to reply to the incoming DM. target is the URL the reply
			// is about; it is remembered so that a later reply to this very
			// message (e.g. "unboost") can be resolved back to it. Pass "" for
			// replies that are not about a particular post.
			reply := func(msg, target string) {
				noteID, err := srv.SendDM(from, msg, dmNoteID)
				if err != nil {
					log.Printf("[%s]   -> reply DM failed: %v", ae.Name, err)
					return
				}
				recordDMThread(db, noteID, target, ae.Name, from, dmOutgoing)
			}

			// Re-read allowlist from disk on every DM so changes take effect
			// without restarting the server.
			currentMeta, err := loadActorMeta(root, ae.Name)
			if err != nil {
				log.Printf("[%s]   -> failed to load actor meta: %v", ae.Name, err)
				return
			}
			// Resolve any handles in the allowlist to actor URLs.
			var allowlist []string
			for _, entry := range currentMeta.Allowlist {
				resolved, err := resolveAllowlistEntry(srv, entry)
				if err != nil {
					log.Printf("[%s]   -> resolve allowlist entry %s: %v", ae.Name, entry, err)
					allowlist = append(allowlist, entry) // keep original as fallback
				} else {
					allowlist = append(allowlist, resolved)
				}
			}

			if !mayBoost(admins, allowlist, from) {
				log.Printf("[%s]   -> ignored: %s is neither an admin nor one of the %d curator(s)",
					ae.Name, from, len(allowlist))
				return
			}

			// "unboost" has to be tested first: "boost" is a substring of it.
			unboost := hasCommand(content, "unboost")
			boost := !unboost && hasCommand(content, "boost")

			urls := extractURLs(content)

			// A DM carrying no URL can still name a post: either by replying
			// in a thread the bot already knows about, or by replying to the
			// post itself. Both require an explicit command word, so that
			// ordinary chatter in a thread can never (un)boost by accident.
			knownTargets := false
			if len(urls) == 0 {
				if !boost && !unboost {
					log.Printf("[%s]   -> no URLs and no command in DM", ae.Name)
					return
				}
				if inReplyTo == "" {
					log.Printf("[%s]   -> command without URL and not a reply, ignoring", ae.Name)
					reply("Send me a URL, or reply to the post you want me to boost.", "")
					return
				}
				if known := lookupDMThread(db, inReplyTo, ae.Name); len(known) > 0 {
					// A reply inside one of our own DM conversations.
					urls = known
					knownTargets = true
					log.Printf("[%s]   -> resolved reply to %s -> %v", ae.Name, inReplyTo, urls)
				} else {
					// Not a conversation we know about, so the DM is a reply
					// to a post somewhere: that post is what is meant.
					urls = []string{inReplyTo}
					log.Printf("[%s]   -> targeting the post replied to: %s", ae.Name, inReplyTo)
				}
			}

			for _, u := range urls {
				original := u
				var apObj map[string]any
				// URLs from the thread index are already canonical AP ids, and
				// unboosting only has to match our own outbox entry — skip the
				// fetch so it still works once the post is unreachable.
				if !knownTargets {
					if obj, apID, err := fetchAPObject(u, srv, activitypub.FollowRedirects); err != nil {
						log.Printf("[%s]   -> fetch AP object for %s failed: %v, using as-is", ae.Name, u, err)
					} else if apID != "" {
						if apID != u {
							log.Printf("[%s]   -> resolved %s -> %s", ae.Name, u, apID)
							u = apID
						}
						apObj = obj
					}
				}

				// Remember what this DM was about, so a later reply to it
				// resolves back to the post even when it carries no URL.
				recordDMThread(db, dmNoteID, u, ae.Name, from, dmIncoming)

				if unboost {
					log.Printf("[%s]   -> unboosting %s", ae.Name, u)
					if err := DeleteQuote(srv, u); err != nil {
						log.Printf("[%s]   -> delete quote failed: %v", ae.Name, err)
					}
					if err := srv.UndoAnnounce(u); err != nil {
						log.Printf("[%s]   -> undo announce failed: %v", ae.Name, err)
					}
					if original != u {
						_ = DeleteQuote(srv, original)
						_ = srv.UndoAnnounce(original)
					}
					reply(fmt.Sprintf("Unboosted %s", dmLink(u)), u)
				} else if apObj != nil {
					// Always try to quote-post AP objects — sends a QuoteRequest
					// and waits up to 5s for approval. Falls back to Announce on
					// timeout (e.g. followers-only policy and bot isn't a follower).
					authorURL, _ := apObj["attributedTo"].(string)
					log.Printf("[%s]   -> quote-posting %s (author: %s, quote policy: %s)", ae.Name, u, authorURL, quotePolicy(apObj))
					approved, err := QuotePost(srv, qs, u, authorURL)
					if err != nil {
						log.Printf("[%s]   -> quote-post failed: %v, falling back to announce", ae.Name, err)
					} else if !approved && quoteRequiresFollow(apObj, authorURL) {
						log.Printf("[%s]   -> quote requires follow, trying FollowAndQuote for %s", ae.Name, u)
						approved, err = FollowAndQuote(srv, qs, u, authorURL)
						if err != nil {
							log.Printf("[%s]   -> follow-and-quote failed: %v, falling back to announce", ae.Name, err)
						}
					}
					if err != nil || !approved {
						if err == nil {
							log.Printf("[%s]   -> quote-post timed out/rejected, falling back to announce", ae.Name)
						}
						if err := srv.AnnounceWithOriginal(u, original); err != nil {
							log.Printf("[%s]   -> announce fallback failed: %v", ae.Name, err)
							reply(fmt.Sprintf("Boosted %s (could not quote: timed out)", dmLink(u)), u)
						} else {
							reply(fmt.Sprintf("Boosted %s (could not quote: timed out)", dmLink(u)), u)
						}
					} else {
						reply(fmt.Sprintf("Quoted %s", dmLink(u)), u)
					}
				} else {
					log.Printf("[%s]   -> boosting %s (not an AP object)", ae.Name, u)
					if err := srv.AnnounceWithOriginal(u, original); err != nil {
						log.Printf("[%s]   -> boost failed: %v", ae.Name, err)
						reply(fmt.Sprintf("Failed to boost %s: %v", dmLink(u), err), u)
					} else {
						if snippet := fetchContentSnippet(srv, u); snippet != "" {
							srv.SetAnnounceField(u, "contentSnippet", snippet)
						}
						reply(fmt.Sprintf("Boosted %s", dmLink(u)), u)
					}
				}
			}
		},
	})

	srv.RegisterActor(mux)

	// Build and push the summary with the curated-by list in the background
	// so startup isn't blocked by remote actor fetches.
	go func() {
		summary := buildSummaryWithCurators(srv, meta.Summary, meta.Allowlist)
		srv.SetSummary(summary)
		if err := srv.UpdateProfile(false); err != nil {
			log.Printf("[%s] update profile with curators: %v", ae.Name, err)
		}
	}()

	log.Printf("actor @%s@%s ready (data: %s, allowlist: %d)", ae.Name, domain, dir, len(meta.Allowlist))
	return srv, qs, nil
}

// resolveAllowlistEntry resolves an allowlist entry to an actor URL.
// Entries may be actor URLs (https://...) or fediverse handles (@user@host or user@host).
func resolveAllowlistEntry(srv *activitypub.Server, entry string) (string, error) {
	if strings.HasPrefix(entry, "https://") || strings.HasPrefix(entry, "http://") {
		return entry, nil
	}
	return srv.ResolveHandle(entry)
}

// buildSummaryWithCurators appends a "Curated by" section to base, fetching
// each curator's preferredUsername and profile URL for the link text.
func buildSummaryWithCurators(srv *activitypub.Server, base string, allowlist []string) string {
	if len(allowlist) == 0 {
		return base
	}
	var links []string
	for _, entry := range allowlist {
		actorURL, err := resolveAllowlistEntry(srv, entry)
		if err != nil {
			log.Printf("buildSummaryWithCurators: resolve %s: %v", entry, err)
			continue
		}
		obj, err := srv.FetchObject(actorURL, activitypub.NoRedirects)
		if err != nil {
			log.Printf("buildSummaryWithCurators: fetch %s: %v", actorURL, err)
			// Fall back to just the actor URL as a link.
			links = append(links, fmt.Sprintf(`<a href="%s">%s</a>`,
				template.HTMLEscapeString(actorURL),
				template.HTMLEscapeString(actorURL)))
			continue
		}
		username, _ := obj["preferredUsername"].(string)
		profileURL, _ := obj["url"].(string)
		if profileURL == "" {
			profileURL = actorURL
		}
		if username == "" {
			username = actorURL
		}
		// Extract host for @user@host display.
		handle := username
		if u, err := url.Parse(actorURL); err == nil {
			handle = "@" + username + "@" + u.Host
		}
		links = append(links, fmt.Sprintf(`<a href="%s" rel="nofollow noopener noreferrer">%s</a>`,
			template.HTMLEscapeString(profileURL),
			template.HTMLEscapeString(handle)))
	}
	if len(links) == 0 {
		return base
	}
	curated := "<p>Curated by " + strings.Join(links, ", ") + "</p>"
	if base == "" {
		return curated
	}
	return base + "\n" + curated
}

// ---------------------------------------------------------------------------
// Fediverse PIN login
// ---------------------------------------------------------------------------

type loginSession struct {
	actorURL  string // resolved AP actor URL of the user
	handle    string // original handle as typed, for display
	pin       string // 4-digit string "0000"–"9999"
	createdAt time.Time
	verified  bool
}

var (
	loginMu       sync.Mutex
	loginSessions = map[string]*loginSession{}
	sessionsPath  string // set once in main() to <dataDir>/sessions.json
)

// newToken returns a cryptographically random base64url-encoded 128-bit token.
func newToken() string {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		panic("crypto/rand unavailable: " + err.Error())
	}
	return base64.RawURLEncoding.EncodeToString(b[:])
}

// newPIN returns a zero-padded random 4-digit string "0000"–"9999".
func newPIN() string {
	n, err := rand.Int(rand.Reader, big.NewInt(10000))
	if err != nil {
		panic("crypto/rand unavailable: " + err.Error())
	}
	return fmt.Sprintf("%04d", n.Int64())
}

// pinRe matches the first standalone 4-digit sequence in stripped text.
var pinRe = regexp.MustCompile(`\b(\d{4})\b`)

// stripTags removes HTML tags from s.
func stripTags(s string) string {
	return regexp.MustCompile(`<[^>]*>`).ReplaceAllString(s, " ")
}

// checkLoginPin is called for every incoming DM. If the content contains a
// 4-digit PIN that matches a pending session for actorURL, it marks it verified.
func checkLoginPin(actorURL, content string) {
	stripped := stripTags(content)
	m := pinRe.FindStringSubmatch(stripped)
	if m == nil {
		return
	}
	pin := m[1]

	loginMu.Lock()
	defer loginMu.Unlock()
	for _, sess := range loginSessions {
		if !sess.verified && sess.actorURL == actorURL && sess.pin == pin {
			sess.verified = true
			log.Printf("login: PIN verified for %s (%s)", sess.handle, actorURL)
			saveSessions()
			return
		}
	}
}

// gcLoginSession deletes the session after 10 minutes if still unverified.
func gcLoginSession(token string) {
	time.Sleep(10 * time.Minute)
	loginMu.Lock()
	defer loginMu.Unlock()
	sess, ok := loginSessions[token]
	if ok && !sess.verified {
		delete(loginSessions, token)
		log.Printf("login: session for %s expired", sess.handle)
	}
}

// sessionRecord is the on-disk representation of a verified session.
// Only verified sessions are persisted; pending ones are transient.
type sessionRecord struct {
	Token     string    `json:"token"`
	Handle    string    `json:"handle"`
	ActorURL  string    `json:"actor_url"`
	CreatedAt time.Time `json:"created_at"`
}

// loadSessions reads verified sessions from disk into loginSessions.
// Called once at startup; non-fatal if the file is missing.
func loadSessions() {
	if sessionsPath == "" {
		return
	}
	data, err := os.ReadFile(sessionsPath)
	if err != nil {
		if !os.IsNotExist(err) {
			log.Printf("login: load sessions: %v", err)
		}
		return
	}
	var records []sessionRecord
	if err := json.Unmarshal(data, &records); err != nil {
		log.Printf("login: parse sessions.json: %v", err)
		return
	}
	loginMu.Lock()
	defer loginMu.Unlock()
	for _, rec := range records {
		loginSessions[rec.Token] = &loginSession{
			actorURL:  rec.ActorURL,
			handle:    rec.Handle,
			pin:       "", // not needed after verification
			createdAt: rec.CreatedAt,
			verified:  true,
		}
	}
	log.Printf("login: loaded %d verified session(s) from disk", len(records))
}

// saveSessions writes all verified sessions to disk atomically.
// Must be called with loginMu held.
func saveSessions() {
	if sessionsPath == "" {
		return
	}
	var records []sessionRecord
	for token, sess := range loginSessions {
		if sess.verified {
			records = append(records, sessionRecord{
				Token:     token,
				Handle:    sess.handle,
				ActorURL:  sess.actorURL,
				CreatedAt: sess.createdAt,
			})
		}
	}
	data, err := json.MarshalIndent(records, "", "  ")
	if err != nil {
		log.Printf("login: marshal sessions: %v", err)
		return
	}
	tmp := sessionsPath + ".tmp"
	if err := os.WriteFile(tmp, data, 0o600); err != nil {
		log.Printf("login: write sessions.tmp: %v", err)
		return
	}
	if err := os.Rename(tmp, sessionsPath); err != nil {
		log.Printf("login: rename sessions: %v", err)
	}
}

// makeLoginHandler returns a /login handler.
// apSrv is used for WebFinger resolution.
// admins and allServers are used to check that the resolved actor is either
// an admin or a curator of at least one actor.
func makeLoginHandler(apSrv *activitypub.Server, firstActorName string, dataDir string, root *os.Root, admins []string, registry *actorRegistry) http.HandlerFunc {
	// Pick any bot handle for the PIN instruction — use the first actor.
	botHandle := fmt.Sprintf("@%s@%s", firstActorName, apSrv.Domain())

	return func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {

		case http.MethodGet:
			handle := strings.TrimSpace(r.URL.Query().Get("user"))
			if handle == "" {
				renderTemplate(w, tmplLoginForm, loginFormData{})
				return
			}

			actorURL, err := apSrv.ResolveHandle(handle)
			if err != nil {
				log.Printf("login: resolve handle %q: %v", handle, err)
				http.Error(w,
					fmt.Sprintf("Could not resolve fediverse handle %q: %v", handle, err),
					http.StatusBadRequest)
				return
			}
			log.Printf("login: resolved %q -> %s", handle, actorURL)

			// Allow admins and any curator of at least one actor.
			permitted := inAllowlist(admins, actorURL)
			if !permitted {
				for _, name := range registry.names() {
					meta, err := loadActorMeta(root, name)
					if err == nil && inAllowlist(meta.Allowlist, actorURL) {
						permitted = true
						break
					}
				}
			}
			if !permitted {
				log.Printf("login: rejected %s (not an admin or curator)", actorURL)
				http.Error(w, "This handle is not permitted to log in.", http.StatusForbidden)
				return
			}

			token := newToken()
			pin := newPIN()
			loginMu.Lock()
			loginSessions[token] = &loginSession{
				actorURL:  actorURL,
				handle:    handle,
				pin:       pin,
				createdAt: time.Now(),
			}
			loginMu.Unlock()
			go gcLoginSession(token)

			renderTemplate(w, tmplLoginPin, loginPinData{
				BotHandle: botHandle,
				Handle:    handle,
				PIN:       pin,
				Token:     token,
			})

		case http.MethodPost:
			if err := r.ParseForm(); err != nil {
				http.Error(w, "bad form data", http.StatusBadRequest)
				return
			}
			token := r.FormValue("session_id")
			if token == "" {
				http.Error(w, "missing session_id", http.StatusBadRequest)
				return
			}

			loginMu.Lock()
			sess, ok := loginSessions[token]
			loginMu.Unlock()

			if !ok {
				http.Error(w,
					"Session expired or not found. Please start again: /login?user=@you@instance",
					http.StatusUnauthorized)
				return
			}

			if !sess.verified {
				renderTemplate(w, tmplLoginPin, loginPinData{
					BotHandle: botHandle,
					Handle:    sess.handle,
					PIN:       sess.pin,
					Token:     token,
					Msg:       "PIN not confirmed yet — check you sent the right code, then try again.",
				})
				return
			}

			// Verified — issue session cookie and redirect to /backend
			http.SetCookie(w, &http.Cookie{
				Name:     "session",
				Value:    token,
				Path:     "/",
				MaxAge:   365 * 24 * 60 * 60, // 1 year
				HttpOnly: true,
				Secure:   true,
				SameSite: http.SameSiteLaxMode,
			})
			http.Redirect(w, r, "/backend", http.StatusSeeOther)

		default:
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		}
	}
}

// sessionFromRequest looks up the session cookie and returns the verified
// session, or redirects to /login and returns nil.
func sessionFromRequest(w http.ResponseWriter, r *http.Request) *loginSession {
	cookie, err := r.Cookie("session")
	if err != nil {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return nil
	}
	loginMu.Lock()
	sess, ok := loginSessions[cookie.Value]
	loginMu.Unlock()
	if !ok || !sess.verified {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return nil
	}
	return sess
}

// makeBackendHandler returns the /backend handler.
// allServers maps actor name -> *activitypub.Server.
// dataDir is the top-level data directory (used to read/write actor.json).
// admins is used to verify the session is still authorised.
func makeBackendHandler(dataDir string, root *os.Root, admins []string, registry *actorRegistry) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		sess := sessionFromRequest(w, r)
		if sess == nil {
			return
		}

		switch r.Method {
		case http.MethodGet:
			backendGET(w, r, dataDir, root, admins, registry, sess)
		case http.MethodPost:
			if err := r.ParseForm(); err != nil {
				http.Error(w, "bad form data", http.StatusBadRequest)
				return
			}
			backendPOST(w, r, dataDir, root, admins, registry, sess)
		default:
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		}
	}
}

func backendGET(w http.ResponseWriter, r *http.Request, dataDir string, root *os.Root, admins []string, registry *actorRegistry, sess *loginSession) {
	isAdmin := inAllowlist(admins, sess.actorURL)

	// Collect actor names this session is allowed to see:
	// admins see all; curators see only actors whose allowlist includes them.
	var visibleNames []string
	for _, name := range registry.names() {
		if isAdmin {
			visibleNames = append(visibleNames, name)
		} else {
			meta, err := loadActorMeta(root, name)
			if err == nil && inAllowlist(meta.Allowlist, sess.actorURL) {
				visibleNames = append(visibleNames, name)
			}
		}
	}
	if len(visibleNames) == 0 && !isAdmin {
		http.Error(w, "You are not a curator of any bot.", http.StatusForbidden)
		return
	}

	actorName := r.URL.Query().Get("actor")

	// No actor selected — admins always see the picker (so they can create actors);
	// non-admin curators with only one actor get redirected directly.
	if actorName == "" {
		if len(visibleNames) == 1 && !isAdmin {
			http.Redirect(w, r, "/backend?actor="+visibleNames[0], http.StatusSeeOther)
			return
		}
		renderTemplate(w, tmplPicker, pickerData{
			Handle:      sess.handle,
			VisibleBots: visibleNames,
			IsAdmin:     isAdmin,
		})
		return
	}

	// Specific actor selected — check the session can see it
	srv, ok := registry.get(actorName)
	if !ok {
		http.Error(w, "Unknown actor.", http.StatusNotFound)
		return
	}
	if !isAdmin {
		meta0, err := loadActorMeta(root, actorName)
		if err != nil || !inAllowlist(meta0.Allowlist, sess.actorURL) {
			http.Error(w, "You are not a curator of this bot.", http.StatusForbidden)
			return
		}
	}

	// Load live actor meta (summary + allowlist)
	meta, err := loadActorMeta(root, actorName)
	if err != nil {
		http.Error(w, fmt.Sprintf("load actor meta: %v", err), http.StatusInternalServerError)
		return
	}

	userInstance := instanceHost(sess.actorURL)

	// Build outbox items
	outboxItems := buildOutboxItems(srv.Outbox(), userInstance)

	// Build curator items
	var curators []curatorItem
	for _, cu := range meta.Allowlist {
		href := cu
		if userInstance != "" {
			href = fmt.Sprintf("https://%s/authorize_interaction?uri=%s",
				userInstance, url.QueryEscape(cu))
		}
		curators = append(curators, curatorItem{Handle: actorHandle(cu), URL: href})
	}

	// Bot open URL
	botOpenURL := ""
	if userInstance != "" {
		botOpenURL = fmt.Sprintf("https://%s/authorize_interaction?uri=%s",
			userInstance, url.QueryEscape(srv.ActorURL()))
	}

	// Avatar URL (admin only, but safe to compute always)
	avatarURL := ""
	if meta.AvatarID != "" {
		avatarURL = avatarPublicURL(srv.Domain(), actorName, meta.AvatarID)
	}

	renderTemplate(w, tmplDashboard, dashboardData{
		ActorName:     actorName,
		BotOpenURL:    botOpenURL,
		UserInstance:  userInstance,
		Handle:        sess.handle,
		VisibleBots:   visibleNames,
		AllActorsLink: len(visibleNames) > 1 || isAdmin,
		Curators:      curators,
		Outbox:        outboxItems,
		IsAdmin:       isAdmin,
		DisplayName:   meta.DisplayName,
		Summary:       meta.Summary,
		Allowlist:     strings.Join(meta.Allowlist, "\n"),
		AvatarURL:     avatarURL,
	})
}

func backendPOST(w http.ResponseWriter, r *http.Request, dataDir string, root *os.Root, admins []string, registry *actorRegistry, sess *loginSession) {
	isAdmin := inAllowlist(admins, sess.actorURL)

	actorName := r.URL.Query().Get("actor")
	if actorName == "" {
		actorName = r.FormValue("actor")
	}
	if actorName == "" {
		http.Error(w, "missing actor parameter", http.StatusBadRequest)
		return
	}

	entry, ok := registry.getEntry(actorName)
	if !ok {
		http.Error(w, "Unknown actor.", http.StatusNotFound)
		return
	}
	srv := entry.srv
	qs := entry.qs

	action := r.FormValue("action")

	// save_meta is admin-only
	if action == "save_meta" {
		if !isAdmin {
			http.Error(w, "Only admins can edit actor settings.", http.StatusForbidden)
			return
		}
		displayName := strings.TrimSpace(r.FormValue("display_name"))
		summary := strings.TrimSpace(r.FormValue("summary"))
		var allowlist []string
		for line := range strings.SplitSeq(r.FormValue("allowlist"), "\n") {
			if u := strings.TrimSpace(line); u != "" {
				allowlist = append(allowlist, u)
			}
		}
		// Load-then-modify so fields not present in this form (currently
		// AvatarID, which is written by the avatar upload handler) survive
		// the save instead of being reset to their zero value.
		meta, err := loadActorMeta(root, actorName)
		if err != nil {
			http.Error(w, fmt.Sprintf("load actor meta: %v", err), http.StatusInternalServerError)
			return
		}
		meta.DisplayName = displayName
		meta.Summary = summary
		meta.Allowlist = allowlist
		if err := saveActorMeta(root, dataDir, actorName, meta); err != nil {
			http.Error(w, fmt.Sprintf("save failed: %v", err), http.StatusInternalServerError)
			return
		}
		// Update in-memory fields and push Update{Actor} to followers.
		// The curated-by list is appended here exactly as it is at startup,
		// otherwise saving settings would strip it from the public profile
		// until the next restart. It is derived from the allowlist rather
		// than stored, so meta.Summary stays the plain text the user typed.
		srv.SetDisplayName(displayName)
		go func() {
			srv.SetSummary(buildSummaryWithCurators(srv, summary, allowlist))
			if err := srv.UpdateProfile(true); err != nil {
				log.Printf("backend: UpdateProfile for %s: %v", actorName, err)
			}
		}()
		http.Redirect(w, r, "/backend?actor="+actorName, http.StatusSeeOther)
		return
	}

	// boost/unboost: allowed for admins and curators of this actor
	if !isAdmin {
		meta, err := loadActorMeta(root, actorName)
		if err != nil || !inAllowlist(meta.Allowlist, sess.actorURL) {
			http.Error(w, "You are not a curator of this bot.", http.StatusForbidden)
			return
		}
	}

	rawURL := strings.TrimSpace(r.FormValue("url"))
	if rawURL == "" {
		http.Error(w, "missing url", http.StatusBadRequest)
		return
	}

	switch action {
	case "boost":
		original := rawURL
		var apObj map[string]any
		if obj, apID, err := fetchAPObject(rawURL, srv, activitypub.FollowRedirects); err != nil {
			log.Printf("backend: fetch AP object for %s: %v, using as-is", rawURL, err)
		} else if apID != "" {
			if apID != rawURL {
				log.Printf("backend: resolved %s -> %s", rawURL, apID)
				rawURL = apID
			}
			apObj = obj
		}
		if apObj != nil {
			authorURL, _ := apObj["attributedTo"].(string)
			log.Printf("backend: quote-posting %s (author: %s, quote policy: %s)", rawURL, authorURL, quotePolicy(apObj))
			approved, err := QuotePost(srv, qs, rawURL, authorURL)
			if err != nil {
				log.Printf("backend: quote-post failed: %v, falling back to announce", err)
			} else if !approved && quoteRequiresFollow(apObj, authorURL) {
				log.Printf("backend: quote requires follow, trying FollowAndQuote for %s", rawURL)
				approved, err = FollowAndQuote(srv, qs, rawURL, authorURL)
				if err != nil {
					log.Printf("backend: follow-and-quote failed: %v, falling back to announce", err)
				}
			}
			if err != nil || !approved {
				if err == nil {
					log.Printf("backend: quote-post timed out/rejected, falling back to announce")
				}
				if err := srv.AnnounceWithOriginal(rawURL, original); err != nil {
					log.Printf("backend: boost fallback %s: %v", rawURL, err)
					http.Error(w, fmt.Sprintf("boost failed: %v", err), http.StatusInternalServerError)
					return
				}
			}
		} else {
			log.Printf("backend: boosting %s (no public quote policy)", rawURL)
			if err := srv.AnnounceWithOriginal(rawURL, original); err != nil {
				log.Printf("backend: boost %s: %v", rawURL, err)
				http.Error(w, fmt.Sprintf("boost failed: %v", err), http.StatusInternalServerError)
				return
			} else if snippet := fetchContentSnippet(srv, rawURL); snippet != "" {
				srv.SetAnnounceField(rawURL, "contentSnippet", snippet)
			}
		}
	case "unboost":
		if err := DeleteQuote(srv, rawURL); err != nil {
			log.Printf("backend: delete quote %s: %v", rawURL, err)
		}
		if err := srv.UndoAnnounce(rawURL); err != nil {
			log.Printf("backend: unboost %s: %v", rawURL, err)
			http.Error(w, fmt.Sprintf("unboost failed: %v", err), http.StatusInternalServerError)
			return
		}
	default:
		http.Error(w, "unknown action", http.StatusBadRequest)
		return
	}

	http.Redirect(w, r, "/backend?actor="+actorName, http.StatusSeeOther)
}

// ---------------------------------------------------------------------------
// Actor registry (thread-safe, mutable at runtime)
// ---------------------------------------------------------------------------

type actorEntry struct {
	srv *activitypub.Server
	qs  *quotingState
}

type actorRegistry struct {
	mu      sync.RWMutex
	entries map[string]actorEntry
}

func newActorRegistry() *actorRegistry {
	return &actorRegistry{entries: make(map[string]actorEntry)}
}

func (ar *actorRegistry) get(name string) (*activitypub.Server, bool) {
	ar.mu.RLock()
	e, ok := ar.entries[name]
	ar.mu.RUnlock()
	return e.srv, ok
}

func (ar *actorRegistry) getEntry(name string) (actorEntry, bool) {
	ar.mu.RLock()
	e, ok := ar.entries[name]
	ar.mu.RUnlock()
	return e, ok
}

func (ar *actorRegistry) set(name string, srv *activitypub.Server) {
	ar.mu.Lock()
	e := ar.entries[name]
	e.srv = srv
	ar.entries[name] = e
	ar.mu.Unlock()
}

func (ar *actorRegistry) setEntry(name string, srv *activitypub.Server, qs *quotingState) {
	ar.mu.Lock()
	ar.entries[name] = actorEntry{srv: srv, qs: qs}
	ar.mu.Unlock()
}

func (ar *actorRegistry) names() []string {
	ar.mu.RLock()
	names := make([]string, 0, len(ar.entries))
	for n := range ar.entries {
		names = append(names, n)
	}
	ar.mu.RUnlock()
	return names
}

func (ar *actorRegistry) snapshot() map[string]*activitypub.Server {
	ar.mu.RLock()
	m := make(map[string]*activitypub.Server, len(ar.entries))
	for k, e := range ar.entries {
		m[k] = e.srv
	}
	ar.mu.RUnlock()
	return m
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

func main() {
	configPath := flag.String("config", "./config.json", "Path to config.json")
	flag.Parse()

	cfg, err := loadConfig(*configPath)
	if err != nil {
		log.Fatalf("load config: %v", err)
	}

	actors, err := loadActors(cfg.DataDir)
	if err != nil {
		log.Fatalf("load actors from %s/actors.json: %v", cfg.DataDir, err)
	}

	// Open a traversal-resistant root on the data directory.
	// All file operations under cfg.DataDir use this root.
	if err := os.MkdirAll(cfg.DataDir, 0o755); err != nil {
		log.Fatalf("create data dir: %v", err)
	}
	dataRoot, err := os.OpenRoot(cfg.DataDir)
	if err != nil {
		log.Fatalf("open data dir root: %v", err)
	}

	db, err := openDB(cfg.DataDir)
	if err != nil {
		log.Fatalf("open database: %v", err)
	}
	defer db.Close()

	mux := http.NewServeMux()
	registry := newActorRegistry()

	// The "auth" actor always exists — it's used for login PIN delivery via DM.
	// This allows admins to log in even when no Service actors are configured yet.
	authSrv, err := activitypub.New(activitypub.Config{
		Domain:    cfg.Domain,
		ActorName: "auth",
		ActorType: "Service",
		Summary:   "Authentication actor — DM me your PIN to log in.",
		DataDir:   filepath.Join(cfg.DataDir, "auth"),
	})
	if err != nil {
		log.Fatalf("setup auth actor: %v", err)
	}
	authSrv.SetDisplayName("Auth")
	authSrv.SetHooks(activitypub.Hooks{
		OnDM: func(from, content, noteID, inReplyTo string) {
			log.Printf("[auth] DM from %s: %s", from, content)
			checkLoginPin(from, content)
		},
	})
	authSrv.RegisterActor(mux)

	for _, ae := range actors {
		srv, qs, err := setupActor(mux, cfg.Domain, cfg.DataDir, dataRoot, db, cfg.Admins, ae)
		if err != nil {
			log.Fatalf("setup actor %s: %v", ae.Name, err)
		}
		registry.setEntry(ae.Name, srv, qs)
	}
	// Domain-wide routes (WebFinger + shared inbox) registered once.
	// The auth server handles domain routes — it always exists.
	authSrv.RegisterDomain(mux)

	// Restore avatar URLs for actors that already have a saved avatar.
	for _, ae := range actors {
		meta, err := loadActorMeta(dataRoot, ae.Name)
		if err == nil && meta.AvatarID != "" {
			if srv, ok := registry.get(ae.Name); ok {
				srv.SetIcon(avatarPublicURL(cfg.Domain, ae.Name, meta.AvatarID))
			}
		}
	}

	sessionsPath = cfg.DataDir + "/sessions.json"
	loadSessions()
	mux.HandleFunc("/login", makeLoginHandler(authSrv, "auth", cfg.DataDir, dataRoot, cfg.Admins, registry))
	mux.HandleFunc("/backend", makeBackendHandler(cfg.DataDir, dataRoot, cfg.Admins, registry))
	mux.HandleFunc("/backend/new-actor", makeNewActorHandler(cfg.DataDir, cfg.Domain, dataRoot, db, cfg.Admins, registry, mux))
	mux.HandleFunc("/avatars/", makeAvatarHandler(cfg.DataDir, dataRoot))
	mux.HandleFunc("/backend/avatar", makeAvatarUploadHandler(cfg.DataDir, cfg.Domain, dataRoot, cfg.Admins, registry))

	log.Printf("link-booster starting on :%s (domain: %s, actors: %d, admins: %d)",
		cfg.Port, cfg.Domain, len(actors), len(cfg.Admins))
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rw := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		mux.ServeHTTP(rw, r)
		if rw.status == http.StatusNotFound &&
			(strings.HasPrefix(r.URL.Path, "/users/") ||
				strings.HasPrefix(r.URL.Path, "/.well-known/")) {
			log.Printf("404 %s %s (from %s)", r.Method, r.URL.Path, r.RemoteAddr)
		}
	})
	if err := http.ListenAndServe(":"+cfg.Port, handler); err != nil {
		log.Fatalf("ListenAndServe: %v", err)
	}
}

// ---------------------------------------------------------------------------
// Avatar helpers
// ---------------------------------------------------------------------------

const avatarSize = 400

// resizeToJPEG decodes an image from src, center-crops it to a square, scales
// it to avatarSize×avatarSize using CatmullRom resampling, and encodes the
// result as JPEG quality 90.
func resizeToJPEG(src []byte) ([]byte, error) {
	img, _, err := image.Decode(bytes.NewReader(src))
	if err != nil {
		return nil, fmt.Errorf("decode image: %w", err)
	}

	// Center-crop to square.
	b := img.Bounds()
	w, h := b.Dx(), b.Dy()
	var cropRect image.Rectangle
	if w > h {
		// Wider than tall: trim left and right.
		x0 := b.Min.X + (w-h)/2
		cropRect = image.Rect(x0, b.Min.Y, x0+h, b.Max.Y)
	} else {
		// Taller than wide (or already square): trim top and bottom.
		y0 := b.Min.Y + (h-w)/2
		cropRect = image.Rect(b.Min.X, y0, b.Max.X, y0+w)
	}

	dst := image.NewRGBA(image.Rect(0, 0, avatarSize, avatarSize))
	draw.CatmullRom.Scale(dst, dst.Bounds(), img, cropRect, draw.Over, nil)
	var buf bytes.Buffer
	if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: 90}); err != nil {
		return nil, fmt.Errorf("encode jpeg: %w", err)
	}
	return buf.Bytes(), nil
}

// avatarRootPath returns the path of the avatar JPEG relative to the data root.
// id is the random token stored in actor.json.
func avatarRootPath(actorName, id string) string {
	return "actors/" + actorName + "/avatar-" + id + ".jpg"
}

// avatarPath returns the full filesystem path where the avatar JPEG is stored.
// Used only for os.Rename (os.Root does not yet support Rename).
func avatarPath(dataDir, actorName, id string) string {
	return actorDataDir(dataDir, actorName) + "/avatar-" + id + ".jpg"
}

// avatarPublicURL returns the public URL at which the avatar is served.
func avatarPublicURL(domain, actorName, id string) string {
	return "https://" + domain + "/avatars/" + actorName + "-" + id + ".jpg"
}

// makeAvatarHandler serves actor avatar images from disk.
// Route: GET /avatars/{name}-{id}.jpg
func makeAvatarHandler(dataDir string, root *os.Root) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		// filename is "<name>-<id>.jpg"; strip prefix and suffix then read directly.
		filename := strings.TrimPrefix(r.URL.Path, "/avatars/")
		if filename == "" || strings.ContainsAny(filename, "/\\") || !strings.HasSuffix(filename, ".jpg") {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		// Extract actor name: everything before the last "-"
		base := strings.TrimSuffix(filename, ".jpg")
		dash := strings.LastIndex(base, "-")
		if dash < 0 {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		actorName := base[:dash]
		id := base[dash+1:]
		if actorName == "" || id == "" {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		f, err := root.Open(avatarRootPath(actorName, id))
		if err != nil {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		defer f.Close()
		data, err := io.ReadAll(f)
		if err != nil {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "image/jpeg")
		// Immutable: the URL changes on every upload so we can cache forever.
		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
		w.Write(data)
	}
}

// makeAvatarUploadHandler returns a POST handler for /backend/avatar?actor=...
// Accepts multipart/form-data with a field named "avatar".
func makeAvatarUploadHandler(dataDir, domain string, root *os.Root, admins []string, registry *actorRegistry) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		sess := sessionFromRequest(w, r)
		if sess == nil {
			return
		}
		if !inAllowlist(admins, sess.actorURL) {
			http.Error(w, "Only admins can upload avatars.", http.StatusForbidden)
			return
		}
		actorName := r.URL.Query().Get("actor")
		if actorName == "" {
			http.Error(w, "missing actor parameter", http.StatusBadRequest)
			return
		}
		srv, ok := registry.get(actorName)
		if !ok {
			http.Error(w, "unknown actor", http.StatusNotFound)
			return
		}

		// 8 MiB max upload
		if err := r.ParseMultipartForm(8 << 20); err != nil {
			http.Error(w, "bad multipart form", http.StatusBadRequest)
			return
		}
		file, _, err := r.FormFile("avatar")
		if err != nil {
			http.Error(w, "missing avatar file", http.StatusBadRequest)
			return
		}
		defer file.Close()

		var raw bytes.Buffer
		if _, err := raw.ReadFrom(file); err != nil {
			http.Error(w, "read error", http.StatusInternalServerError)
			return
		}

		resized, err := resizeToJPEG(raw.Bytes())
		if err != nil {
			http.Error(w, fmt.Sprintf("image processing failed: %v", err), http.StatusBadRequest)
			return
		}

		// Generate a new random ID so the URL changes and caches are busted.
		newID := newToken()

		// Load current meta to get old avatar ID (for cleanup) and preserve other fields.
		meta, err := loadActorMeta(root, actorName)
		if err != nil {
			http.Error(w, fmt.Sprintf("load actor meta: %v", err), http.StatusInternalServerError)
			return
		}
		oldID := meta.AvatarID

		wf, err := root.OpenFile(avatarRootPath(actorName, newID), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
		if err != nil {
			http.Error(w, "save failed", http.StatusInternalServerError)
			return
		}
		_, werr := wf.Write(resized)
		cerr := wf.Close()
		if werr != nil || cerr != nil {
			http.Error(w, "save failed", http.StatusInternalServerError)
			return
		}

		// Persist new ID into actor.json.
		meta.AvatarID = newID
		if err := saveActorMeta(root, dataDir, actorName, meta); err != nil {
			http.Error(w, fmt.Sprintf("save meta failed: %v", err), http.StatusInternalServerError)
			return
		}

		// Delete old avatar file now that the new one is safely written.
		if oldID != "" {
			_ = os.Remove(avatarPath(dataDir, actorName, oldID))
		}

		iconURL := avatarPublicURL(domain, actorName, newID)
		srv.SetIcon(iconURL)
		go func() {
			if err := srv.UpdateProfile(true); err != nil {
				log.Printf("avatar: UpdateProfile for %s: %v", actorName, err)
			}
		}()

		http.Redirect(w, r, "/backend?actor="+actorName, http.StatusSeeOther)
	}
}

// ---------------------------------------------------------------------------
// New actor handler
// ---------------------------------------------------------------------------

// validActorName matches only safe actor names (lowercase letters, digits, hyphens).
var validActorName = regexp.MustCompile(`^[a-z0-9-]+$`)

// makeNewActorHandler returns a handler for POST /backend/new-actor (admin-only).
// It creates the data directory, writes a blank actor.json, registers the actor
// with the AP library, mounts its routes on mux, and saves actors.json.
func makeNewActorHandler(dataDir, domain string, root *os.Root, db *sql.DB, admins []string, registry *actorRegistry, mux *http.ServeMux) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		sess := sessionFromRequest(w, r)
		if sess == nil {
			return
		}
		if !inAllowlist(admins, sess.actorURL) {
			http.Error(w, "Only admins can create actors.", http.StatusForbidden)
			return
		}
		if err := r.ParseForm(); err != nil {
			http.Error(w, "bad form data", http.StatusBadRequest)
			return
		}

		name := strings.TrimSpace(r.FormValue("name"))
		if name == "" {
			http.Error(w, "missing actor name", http.StatusBadRequest)
			return
		}
		if !validActorName.MatchString(name) {
			http.Error(w, "actor name may only contain lowercase letters, digits and hyphens", http.StatusBadRequest)
			return
		}
		if _, exists := registry.get(name); exists {
			http.Error(w, "actor already exists", http.StatusConflict)
			return
		}

		// Create data directory and blank actor.json.
		if err := os.MkdirAll(actorDataDir(dataDir, name), 0o755); err != nil {
			http.Error(w, fmt.Sprintf("create data dir: %v", err), http.StatusInternalServerError)
			return
		}
		if err := saveActorMeta(root, dataDir, name, ActorMeta{}); err != nil {
			http.Error(w, fmt.Sprintf("save actor meta: %v", err), http.StatusInternalServerError)
			return
		}

		// Start the AP server and mount its routes.
		ae := ActorEntry{Name: name}
		srv, qs, err := setupActor(mux, domain, dataDir, root, db, admins, ae)
		if err != nil {
			http.Error(w, fmt.Sprintf("setup actor: %v", err), http.StatusInternalServerError)
			return
		}
		registry.setEntry(name, srv, qs)

		// Persist updated actors.json.
		var entries []ActorEntry
		for _, n := range registry.names() {
			entries = append(entries, ActorEntry{Name: n})
		}
		if err := saveActors(dataDir, entries); err != nil {
			log.Printf("new-actor: save actors.json: %v", err)
		}

		log.Printf("new-actor: created @%s@%s", name, domain)
		http.Redirect(w, r, "/backend?actor="+name, http.StatusSeeOther)
	}
}

// buildOutboxItems converts the raw outbox from an activitypub.Server into a
// slice of outboxItem values suitable for display. userInstance is used to
// construct "open on your instance" links; pass an empty string to omit them.
func buildOutboxItems(outbox []map[string]any, userInstance string) []outboxItem {
	var items []outboxItem
	for _, item := range outbox {
		published, _ := item["published"].(string)
		snippet, _ := item["contentSnippet"].(string)
		// Announce: object is a string URL
		// Create(Note): object is a map with a "quote" field
		var obj string
		kind := "boost"
		switch v := item["object"].(type) {
		case string:
			obj = v
		case map[string]any:
			if q, ok := v["quote"].(string); ok {
				obj = q
				kind = "quote"
			}
		}
		if obj == "" {
			continue
		}
		openURL := ""
		if userInstance != "" {
			openURL = fmt.Sprintf("https://%s/authorize_interaction?uri=%s",
				userInstance, url.QueryEscape(obj))
		}
		items = append(items, outboxItem{
			Object:    obj,
			Published: published,
			Snippet:   snippet,
			OpenURL:   openURL,
			Kind:      kind,
		})
	}
	return items
}

func inAllowlist(allowlist []string, actorURL string) bool {
	return slices.Contains(allowlist, actorURL)
}

// commandRes holds one word-boundary matcher per command word. Precompiled
// rather than built on demand because DMs are handled concurrently.
//
// The word boundaries keep a command from firing on a longer word that merely
// contains it ("boosting", "rebooting") and from matching inside a URL.
var commandRes = map[string]*regexp.Regexp{
	"boost":   regexp.MustCompile(`(?i)\bboost\b`),
	"unboost": regexp.MustCompile(`(?i)\bunboost\b`),
}

// hasCommand reports whether the DM content contains cmd as a standalone
// word, ignoring HTML markup (mentions arrive wrapped in tags) and case.
func hasCommand(content, cmd string) bool {
	re, ok := commandRes[cmd]
	if !ok {
		return false
	}
	return re.MatchString(stripTags(content))
}

// mayBoost reports whether actorURL is allowed to make this actor boost
// things by DM. Admins always are; everyone else has to be a curator of
// this particular actor.
//
// An empty allowlist means nobody (except admins), NOT everybody. This is
// deliberate: the allowlist is read from disk on every DM, so treating an
// empty one as "no restriction" would turn any failure to load it — a
// missing file, a parse error, a file overwritten by something else — into
// an open boost relay. Failing closed degrades to "no service" instead.
func mayBoost(admins, allowlist []string, actorURL string) bool {
	return inAllowlist(admins, actorURL) || inAllowlist(allowlist, actorURL)
}

// fetchContentSnippet fetches an AP object by URL using a signed request and
// returns the first 100 runes of its stripped plain-text content, or empty
// string on any error. Uses srv.FetchObject so requests are HTTP-signed and
// go through the SSRF-safe client (port-443-only, public IPs only).
func fetchContentSnippet(srv *activitypub.Server, objectURL string) string {
	obj, err := srv.FetchObject(objectURL, activitypub.NoRedirects)
	if err != nil {
		return ""
	}
	content, _ := obj["content"].(string)
	if content == "" {
		return ""
	}
	// Strip HTML tags
	plain := stripTags(content)
	// Collapse whitespace
	plain = strings.Join(strings.Fields(plain), " ")
	// Truncate to 100 runes
	runes := []rune(plain)
	if len(runes) > 100 {
		return string(runes[:100]) + "…"
	}
	return plain
}

// instanceHost extracts the hostname from an actor URL, e.g.
// "https://mastodon.xyz/users/Profpatsch" -> "mastodon.xyz".
// Returns empty string if the URL cannot be parsed.
func instanceHost(actorURL string) string {
	u, err := url.Parse(actorURL)
	if err != nil || u.Host == "" {
		return ""
	}
	return u.Host
}

// dmLink returns an HTML anchor tag for a URL, for use in DM reply content.
func dmLink(u string) string {
	escaped := template.HTMLEscapeString(u)
	return fmt.Sprintf(`<a href="%s">%s</a>`, escaped, escaped)
}

// quotePolicy returns a short human-readable description of the quote
// policy from an AP object's interactionPolicy, for logging purposes.
func quotePolicy(apObj map[string]any) string {
	policy, _ := apObj["interactionPolicy"].(map[string]any)
	if policy == nil {
		return "none"
	}
	canQuote, _ := policy["canQuote"].(map[string]any)
	if canQuote == nil {
		return "none"
	}
	auto := canQuote["automaticApproval"]
	manual := canQuote["manualApproval"]

	describe := func(v any) string {
		if v == nil {
			return "nobody"
		}
		var entries []string
		switch val := v.(type) {
		case string:
			entries = []string{val}
		case []any:
			for _, e := range val {
				if s, ok := e.(string); ok {
					entries = append(entries, s)
				}
			}
		}
		var parts []string
		for _, e := range entries {
			switch {
			case e == "https://www.w3.org/ns/activitystreams#Public":
				parts = append(parts, "public")
			case strings.HasSuffix(e, "/followers"):
				parts = append(parts, "followers")
			case strings.HasSuffix(e, "/following"):
				parts = append(parts, "following")
			default:
				parts = append(parts, e)
			}
		}
		if len(parts) == 0 {
			return "nobody"
		}
		return strings.Join(parts, ",")
	}

	return fmt.Sprintf("auto=%s manual=%s", describe(auto), describe(manual))
}

// quoteRequiresFollow returns true when apObj's interactionPolicy indicates
// that only the author's followers may quote (i.e. the followers collection is
// in automaticApproval and as:Public is not). authorURL is the attributedTo URL.
func quoteRequiresFollow(apObj map[string]any, authorURL string) bool {
	const asPublic = "https://www.w3.org/ns/activitystreams#Public"
	followersURL := authorURL + "/followers"

	policy, _ := apObj["interactionPolicy"].(map[string]any)
	if policy == nil {
		return false
	}
	canQuote, _ := policy["canQuote"].(map[string]any)
	if canQuote == nil {
		return false
	}
	raw := canQuote["automaticApproval"]
	if raw == nil {
		return false
	}

	// automaticApproval may be a single string or an array.
	var entries []string
	switch v := raw.(type) {
	case string:
		entries = []string{v}
	case []any:
		for _, e := range v {
			if s, ok := e.(string); ok {
				entries = append(entries, s)
			}
		}
	}

	hasFollowers := false
	for _, e := range entries {
		if e == asPublic {
			return false // public → no follow needed
		}
		if e == followersURL {
			hasFollowers = true
		}
	}
	return hasFollowers
}

// actorHandle converts an actor URL to a fediverse handle, e.g.
// "https://mastodon.xyz/users/Profpatsch" -> "@Profpatsch@mastodon.xyz".
// Falls back to the raw URL if the form cannot be determined.
func actorHandle(actorURL string) string {
	u, err := url.Parse(actorURL)
	if err != nil || u.Host == "" {
		return actorURL
	}
	// Last non-empty path segment is the username
	parts := strings.Split(strings.Trim(u.Path, "/"), "/")
	name := parts[len(parts)-1]
	if name == "" {
		return actorURL
	}
	return "@" + name + "@" + u.Host
}