Eventually-decentralized project hosting and management platform
Clone
HTTPS:
darcs clone https://vervis.peers.community/repos/WvWbo
SSH:
darcs clone USERNAME@vervis.peers.community:WvWbo
Tags
TODO
ActivityPub.hs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 | {- This file is part of Vervis.
-
- Written in 2019, 2020, 2021, 2022, 2023
- by fr33domlover <fr33domlover@riseup.net>.
-
- ♡ Copying is an act of love. Please copy, reuse and share.
-
- The author(s) have dedicated all copyright and related and neighboring
- rights to this software to the public domain worldwide. This software is
- distributed without any warranty.
-
- You should have received a copy of the CC0 Public Domain Dedication along
- with this software. If not, see
- <http://creativecommons.org/publicdomain/zero/1.0/>.
-}
module Web.ActivityPub
( -- * Type-safe manipulation tools
--
-- Types and functions that make handling URIs and JSON-LD contexts less
-- error-prone and safer by recording safety checks in the type and
-- placing the checks in a single clear place.
ActivityPub (..)
, Doc (..)
-- * Actor
--
-- ActivityPub actor document including a public key, with a 'FromJSON'
-- instance for fetching and a 'ToJSON' instance for publishing.
, ActorType (..)
--, Algorithm (..)
, Owner (..)
, PublicKey (..)
, SshKeyAlgorithm (..)
, SshPublicKey (..)
, ActorLocal (..)
, ActorDetail (..)
, Actor (..)
, Repo (..)
, TicketTracker (..)
, CollectionType (..)
, Collection (..)
, CollectionPageType (..)
, CollectionPage (..)
, Recipient (..)
, Resource (..)
-- * Content objects
, Note (..)
, TicketDependency (..)
, PatchLocal (..)
, Patch (..)
, BundleLocal (..)
, Bundle (..)
, TicketLocal (..)
, MergeRequest (..)
, Ticket (..)
, Author (..)
, Hash (..)
, Commit (..)
, Branch (..)
, Role (..)
-- * Activity
, Accept (..)
, AddObject (..)
, Add (..)
, Apply (..)
, CreateObject (..)
, Create (..)
, Follow (..)
, Grant (..)
, Invite (..)
, Join (..)
, OfferObject (..)
, Offer (..)
, Push (..)
, Reject (..)
, Resolve (..)
, Undo (..)
, Audience (..)
, SpecificActivity (..)
, activityType
, Action (..)
, makeActivity
, Activity (..)
-- * Utilities
, emptyAudience
, emptyActivity
, hActivityPubActor
, provideAP
, provideAP'
, APGetError (..)
, httpGetAP
, APPostError (..)
, hActivityPubForwarder
, hForwardingSignature
, hForwardedSignature
, Envelope ()
, Errand ()
, sending
, retrying
, deliver
, forwarding
, forward
, Fetched (..)
, fetchAP
, fetchAP_T
, fetchAPID
, fetchAPID'
, fetchTip
, fetchRecipient
, fetchResource
, keyListedByActor
, fetchUnknownKey
, fetchKnownPersonalKey
, fetchKnownSharedKey
, Obj (..)
)
where
import Control.Applicative ((<|>), optional)
import Control.Exception (Exception, displayException, try)
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Control.Monad.Trans.Writer (Writer)
import Crypto.Hash hiding (Context)
import Data.Aeson
import Data.Aeson.Encoding (pair)
import Data.Aeson.Types (Parser, typeMismatch, listEncoding)
import Data.Bifunctor
import Data.Bitraversable
import Data.ByteString (ByteString)
import Data.Char
import Data.Foldable (for_)
import Data.List
import Data.List.NonEmpty (NonEmpty (..))
import Data.Proxy
import Data.Semigroup (Endo, First (..))
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8, decodeUtf8, decodeUtf8')
import Data.Time.Clock
import Data.Traversable
import Network.HTTP.Client hiding (Proxy, proxy)
import Network.HTTP.Client.Conduit.ActivityPub (httpAPEither)
import Network.HTTP.Simple (JSONException)
import Network.HTTP.Types.Header (HeaderName, hContentType)
import Text.Email.Parser (EmailAddress)
import Yesod.Core.Content (ContentType)
import Yesod.Core.Handler (ProvidedRep, provideRepType)
import Network.HTTP.Client.Signature
import qualified Data.Attoparsec.ByteString as A
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as M
import qualified Data.List.NonEmpty as NE
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Vector as V
import qualified Network.HTTP.Signature as S
import qualified Text.Email.Parser as E
import Crypto.PublicVerifKey
import Development.PatchMediaType
import Development.PatchMediaType.JSON
import Network.FedURI
import Network.HTTP.Digest
import Web.Text
import Data.Aeson.Local
{-
data Link = Link
{ linkHref :: URI
, linkRel ::
, linkMediaType ::
, linkName ::
, linkHreflang ::
, linkHeight ::
, linkWidth ::
, linkPreview ::
, linkRest :: Object
}
data X = X
{ xId :: LocalURI
, x
}
data Object' u = Object'
{ objectId :: ObjURI
, objectType ::
, objectSubject ::
, objectRelationship ::
, objectActor ::
, objectAttributedTo ::
, objectAttachment ::
, objectBcc ::
, objectBto ::
, objectCc ::
, objectContext ::
, objectCurrent ::
, objectFirst ::
, objectGenerator ::
, objectIcon ::
, objectImage ::
, objectInReplyTo ::
, objectItems ::
, objectInstrument ::
, objectOrderedItems ::
, objectLast ::
, objectLocation ::
, objectNext ::
, objectObject ::
, objectOneOf ::
, objectAnyOf ::
, objectClosed ::
, objectOrigin ::
, objectAccuracy ::
, objectPrev ::
, objectPreview ::
, objectProvider ::
, objectReplies ::
, objectResult ::
, objectAudience ::
, objectPartOf ::
, objectTag ::
, objectTags ::
, objectTarget ::
, objectTo ::
, objectUrl ::
, objectAltitude ::
, objectContent ::
, objectContentMap ::
, objectName ::
, objectNameMap ::
, objectDuration ::
, objectEndTime ::
, objectHeight ::
, objectHref ::
, objectHreflang ::
, objectLatitude ::
, objectLongitude ::
, objectMediaType ::
, objectPublished ::
, objectRadius ::
, objectRating ::
, objectRel ::
, objectStartIndex ::
, objectStartTime ::
, objectSummary ::
, objectSummaryMap ::
, objectTotalItems ::
, objectUnits ::
, objectUpdated ::
, objectWidth ::
, objectDescribes ::
, objectFormerType ::
, objectDeleted ::
, objectEndpoints ::
, objectFollowing ::
, objectFollowers ::
, objectInbox ::
, objectLiked ::
, objectShares ::
, objectLikes ::
, objectOauthAuthorizationEndpoint ::
, objectOauthTokenEndpoint ::
, objectOutbox ::
, objectPreferredUsername ::
, objectProvideClientKey ::
, objectProxyUrl ::
, objectSharedInbox ::
, objectSignClientKey ::
, objectSource ::
, objectStreams ::
, objectUploadMedia ::
, objectRest :: Object
}
-}
proxy :: a u -> Proxy a
proxy _ = Proxy
as2Context :: Text
as2Context = "https://www.w3.org/ns/activitystreams"
secContext :: Text
secContext = "https://w3id.org/security/v2"
forgeContext :: Text
forgeContext = "https://forgefed.org/ns"
publicURI :: Text
publicURI = "https://www.w3.org/ns/activitystreams#Public"
class ActivityPub a where
jsonldContext :: Proxy a -> [Text]
parseObject :: UriMode u => Object -> Parser (Authority u, a u)
toSeries :: UriMode u => Authority u -> a u -> Series
data Doc a u = Doc
{ docAuthority :: Authority u
, docValue :: a u
}
instance (ActivityPub a, UriMode u) => FromJSON (Doc a u) where
parseJSON = withObject "Doc" $ \ o -> uncurry Doc <$> parseObject o
instance (ActivityPub a, UriMode u) => ToJSON (Doc a u) where
toJSON = error "toJSON Doc"
toEncoding (Doc h v) =
pairs
$ context (jsonldContext $ proxy v)
<> toSeries h v
where
context [] = mempty
context [t] = "@context" .= t
context ts = "@context" .= ts
data ActorType
= ActorTypePerson
| ActorTypeRepo
| ActorTypeTicketTracker
| ActorTypePatchTracker
| ActorTypeOther Text
deriving Eq
instance FromJSON ActorType where
parseJSON = withText "ActorType" $ pure . parse
where
parse t
| t == "Person" = ActorTypePerson
| t == "Repository" = ActorTypeRepo
| t == "TicketTracker" = ActorTypeTicketTracker
| t == "PatchTracker" = ActorTypePatchTracker
| otherwise = ActorTypeOther t
instance ToJSON ActorType where
toJSON = error "toJSON ActorType"
toEncoding at =
toEncoding $ case at of
ActorTypePerson -> "Person"
ActorTypeRepo -> "Repository"
ActorTypeTicketTracker -> "TicketTracker"
ActorTypePatchTracker -> "PatchTracker"
ActorTypeOther t -> t
data Owner = OwnerInstance | OwnerActor LocalURI
ownerShared :: Owner -> Bool
ownerShared OwnerInstance = True
ownerShared (OwnerActor _) = False
data PublicKey u = PublicKey
{ publicKeyId :: LocalRefURI
, publicKeyExpires :: Maybe UTCTime
, publicKeyOwner :: Owner
, publicKeyMaterial :: PublicVerifKey
}
instance ActivityPub PublicKey where
jsonldContext _ = [secContext]
parseObject o = do
mtyp <- optional $ o .: "@type" <|> o .: "type"
for_ mtyp $ \ t ->
unless (t == ("Key" :: Text) || t == "CryptographicKey") $
fail "PublicKey @type isn't Key or CryptographicKey"
RefURI authority id_ <- o .: "@id" <|> o .: "id"
shared <- o .:|? "isShared" .!= False
fmap (authority,) $
PublicKey id_
<$> o .:? "expires"
<*> (mkOwner shared =<< withAuthorityO authority (o .: "owner"))
<*> (either fail return . decodePublicVerifKeyPEM =<<
o .: "publicKeyPem"
)
where
mkOwner True lu
| lu == topLocalURI = return OwnerInstance
mkOwner True _ = fail "Shared key but owner isn't instance URI"
mkOwner False lu = return $ OwnerActor lu
toSeries authority (PublicKey id_ mexpires owner mat)
= "@id" .= RefURI authority id_
<> "expires" .=? mexpires
<> "owner" .= mkOwner authority owner
<> "publicKeyPem" .= encodePublicVerifKeyPEM mat
<> "isShared" .= ownerShared owner
where
mkOwner a OwnerInstance = ObjURI a topLocalURI
mkOwner a (OwnerActor lu) = ObjURI a lu
parsePublicKeySet
:: UriMode u
=> Value
-> Parser (Authority u, [Either LocalURI (PublicKey u)])
parsePublicKeySet v =
case v of
Array a ->
case V.toList a of
[] -> fail "No public keys"
k : ks -> do
(a, e) <- parseKey k
es <- traverse (withAuthorityT a . parseKey) ks
return (a, e : es)
_ -> second (: []) <$> parseKey v
where
parseKey v@(String _) = second Left . f2l <$> parseJSON v
where
f2l (ObjURI a l) = (a, l)
parseKey (Object o) = second Right <$> parseObject o
parseKey v = typeMismatch "PublicKeySet Item" v
encodePublicKeySet
:: UriMode u => Authority u -> [Either LocalURI (PublicKey u)] -> Encoding
encodePublicKeySet authority es =
case es of
[e] -> renderKey e
_ -> listEncoding renderKey es
where
renderKey (Left lu) = toEncoding $ ObjURI authority lu
renderKey (Right pk) = pairs $ toSeries authority pk
data SshKeyAlgorithm
= SshKeyAlgorithmRSA
| SshKeyAlgorithmDSA
| SshKeyAlgorithmECDSA
| SshKeyAlgorithmEd25519
instance FromJSON SshKeyAlgorithm where
parseJSON = withText "SshKeyAlgorithm" parse
where
parse t
| t == "ssh-rsa" = pure SshKeyAlgorithmRSA
| t == "ssh-dsa" = pure SshKeyAlgorithmDSA
| t == "ssh-ecdsa" = pure SshKeyAlgorithmECDSA
| t == "ssh-ed25519" = pure SshKeyAlgorithmEd25519
| otherwise =
fail $ "Unrecognized ssh key algo: " ++ T.unpack t
instance ToJSON SshKeyAlgorithm where
toJSON = error "toJSON SshKeyAlgorithm"
toEncoding = toEncoding . render
where
render :: SshKeyAlgorithm -> Text
render SshKeyAlgorithmRSA = "ssh-rsa"
render SshKeyAlgorithmDSA = "ssh-dsa"
render SshKeyAlgorithmECDSA = "ssh-ecdsa"
render SshKeyAlgorithmEd25519 = "ssh-ed25519"
data SshPublicKey u = SshPublicKey
{ sshPublicKeyId :: LocalURI
, sshPublicKeyExpires :: Maybe UTCTime
, sshPublicKeyOwner :: LocalURI
, sshPublicKeyAlgorithm :: SshKeyAlgorithm
, sshPublicKeyMaterial :: ByteString
}
instance ActivityPub SshPublicKey where
jsonldContext _ = [secContext, forgeContext]
parseObject o = do
mtyp <- optional $ o .: "@type" <|> o .: "type"
for_ mtyp $ \ t ->
when (t /= ("SshKey" :: Text)) $
fail "SshKey @type isn't SshKey"
mediaType <- o .: "mediaType"
unless (mediaType == ("application/octet-stream" :: Text)) $
fail "mediaType isn't octet-stream"
ObjURI authority luId <- o .: "@id" <|> o .: "id"
fmap (authority,) $
SshPublicKey luId
<$> o .:? "expires"
<*> withAuthorityO authority (o .: "owner")
<*> o .: "sshKeyType"
<*> (decodeBase64 . encodeUtf8 =<< o .: "content")
where
decodeBase64 = either fail return . B64.decode
toSeries authority (SshPublicKey luId mexpires owner algo mat)
= "@id" .= ObjURI authority luId
<> "expires" .=? mexpires
<> "owner" .= ObjURI authority owner
<> "sshKeyType" .= algo
<> "mediaType" .= ("application/octet-stream" :: Text)
<> "content" .= decodeUtf8 (B64.encode mat)
data ActorLocal u = ActorLocal
{ actorId :: LocalURI
, actorInbox :: LocalURI
, actorOutbox :: Maybe LocalURI
, actorFollowers :: Maybe LocalURI
, actorFollowing :: Maybe LocalURI
, actorPublicKeys :: [Either LocalURI (PublicKey u)]
, actorSshKeys :: [LocalURI]
}
parseActorLocal :: UriMode u => Object -> Parser (Maybe (Authority u, ActorLocal u))
parseActorLocal o = do
mid <- o .:? "id"
case mid of
Nothing -> do
verifyNothing "inbox"
verifyNothing "outbox"
verifyNothing "followers"
verifyNothing "following"
verifyNothing "publicKey"
verifyNothing "sshKey"
return Nothing
Just (ObjURI a id_) ->
fmap (Just . (a,)) $
ActorLocal
<$> pure id_
<*> withAuthorityO a (o .: "inbox")
<*> withAuthorityMaybeO a (o .:? "outbox")
<*> withAuthorityMaybeO a (o .:? "followers")
<*> withAuthorityMaybeO a (o .:? "following")
<*> withAuthorityT a (parsePublicKeySet =<< o .: "publicKey")
<*> (traverse (withAuthorityO a . return) =<< o .:? "sshKey" .!= [])
where
verifyNothing t =
if t `M.member` o
then fail $ T.unpack t ++ " field found, expected none"
else return ()
encodeActorLocal :: UriMode u => Authority u -> ActorLocal u -> Series
encodeActorLocal a (ActorLocal id_ inbox outbox followers following pkeys skeys)
= "id" .= ObjURI a id_
<> "inbox" .= ObjURI a inbox
<> "outbox" .=? (ObjURI a <$> outbox)
<> "followers" .=? (ObjURI a <$> followers)
<> "following" .=? (ObjURI a <$> following)
<> "publicKey" `pair` encodePublicKeySet a pkeys
<> "sshKey" .=% map (ObjURI a) skeys
data ActorDetail = ActorDetail
{ actorType :: ActorType
, actorUsername :: Maybe Text
, actorName :: Maybe Text
, actorSummary :: Maybe Text
}
parseActorDetail :: Object -> Parser ActorDetail
parseActorDetail o =
ActorDetail
<$> o .: "type"
<*> o .:? "preferredUsername"
<*> o .:? "name"
<*> o .:? "summary"
encodeActorDetail :: ActorDetail -> Series
encodeActorDetail (ActorDetail typ musername mname msummary)
= "type" .= typ
<> "preferredUsername" .=? musername
<> "name" .=? mname
<> "summary" .=? msummary
data Actor u = Actor
{ actorLocal :: ActorLocal u
, actorDetail :: ActorDetail
}
instance ActivityPub Actor where
jsonldContext _ = [as2Context, secContext, forgeContext]
parseObject o = do
mlocal <- parseActorLocal o
(h, local) <-
case mlocal of
Nothing -> fail "No ActorLocal"
Just l -> return l
detail <- parseActorDetail o
return (h, Actor local detail)
toSeries h (Actor local detail) =
encodeActorLocal h local <> encodeActorDetail detail
data Repo u = Repo
{ repoActor :: Actor u
, repoTeam :: Maybe LocalURI
, repoVcs :: VersionControlSystem
, repoLoom :: Maybe LocalURI
, repoClone :: NonEmpty LocalURI
}
instance ActivityPub Repo where
jsonldContext _ = [as2Context, secContext, forgeContext]
parseObject o = do
(h, a) <- parseObject o
unless (actorType (actorDetail a) == ActorTypeRepo) $
fail "Actor type isn't Repository"
fmap (h,) $
Repo a
<$> withAuthorityMaybeO h (o .:|? "team")
<*> o .: "versionControlSystem"
<*> withAuthorityMaybeO h (o .:? "sendPatchesTo")
<*> (traverse (withAuthorityO h . pure) =<< o .:*+ "cloneUri")
toSeries authority (Repo actor team vcs loom clone)
= toSeries authority actor
<> "team" .= (ObjURI authority <$> team)
<> "versionControlSystem" .= vcs
<> "sendPatchesTo" .=? (ObjURI authority <$> loom)
<> "cloneUri" .=*+ (ObjURI authority <$> clone)
data TicketTracker u = TicketTracker
{ ticketTrackerActor :: Actor u
, ticketTrackerTeam :: Maybe LocalURI
}
instance ActivityPub TicketTracker where
jsonldContext _ = [as2Context, secContext, forgeContext]
parseObject o = do
(h, a) <- parseObject o
unless (actorType (actorDetail a) == ActorTypeTicketTracker) $
fail "Actor type isn't TicketTracker"
fmap (h,) $
TicketTracker a
<$> withAuthorityMaybeO h (o .:|? "team")
toSeries authority (TicketTracker actor team)
= toSeries authority actor
<> "team" .= (ObjURI authority <$> team)
data CollectionType = CollectionTypeUnordered | CollectionTypeOrdered
instance FromJSON CollectionType where
parseJSON = withText "CollectionType" parse
where
parse "Collection" = pure CollectionTypeUnordered
parse "OrderedCollection" = pure CollectionTypeOrdered
parse t = fail $ "Unknown collection type: " ++ T.unpack t
instance ToJSON CollectionType where
toJSON = error "toJSON CollectionType"
toEncoding ct =
toEncoding $ case ct of
CollectionTypeUnordered -> "Collection" :: Text
CollectionTypeOrdered -> "OrderedCollection"
data Collection a u = Collection
{ collectionId :: LocalURI
, collectionType :: CollectionType
, collectionTotalItems :: Maybe Int
, collectionCurrent :: Maybe LocalURI
, collectionFirst :: Maybe LocalPageURI
, collectionLast :: Maybe LocalPageURI
, collectionItems :: [a]
}
instance (FromJSON a, ToJSON a) => ActivityPub (Collection a) where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
ObjURI authority id_ <- o .: "id"
fmap (authority,) $
Collection id_
<$> o .: "type"
<*> o .:? "totalItems"
<*> withAuthorityMaybeO authority (o .:? "current")
<*> withAuthorityMaybeP authority (o .:? "first")
<*> withAuthorityMaybeP authority (o .:? "last")
<*> optional (o .: "items" <|> o .: "orderedItems") .!= []
toSeries authority (Collection id_ typ total curr firzt last items)
= "id" .= ObjURI authority id_
<> "type" .= typ
<> "totalItems" .=? total
<> "current" .=? (ObjURI authority <$> curr)
<> "first" .=? (PageURI authority <$> firzt)
<> "last" .=? (PageURI authority <$> last)
<> itemsProp .=% items
where
itemsProp =
case typ of
CollectionTypeUnordered -> "items"
CollectionTypeOrdered -> "orderedItems"
data CollectionPageType
= CollectionPageTypeUnordered
| CollectionPageTypeOrdered
instance FromJSON CollectionPageType where
parseJSON = withText "CollectionPageType" parse
where
parse "CollectionPage" = pure CollectionPageTypeUnordered
parse "OrderedCollectionPage" = pure CollectionPageTypeOrdered
parse t = fail $ "Unknown collection page type: " ++ T.unpack t
instance ToJSON CollectionPageType where
toJSON = error "toJSON CollectionPageType"
toEncoding ct =
toEncoding $ case ct of
CollectionPageTypeUnordered -> "CollectionPage" :: Text
CollectionPageTypeOrdered -> "OrderedCollectionPage"
data CollectionPage a u = CollectionPage
{ collectionPageId :: LocalPageURI
, collectionPageType :: CollectionPageType
, collectionPageTotalItems :: Maybe Int
, collectionPageCurrent :: Maybe LocalPageURI
, collectionPageFirst :: Maybe LocalPageURI
, collectionPageLast :: Maybe LocalPageURI
, collectionPagePartOf :: LocalURI
, collectionPagePrev :: Maybe LocalPageURI
, collectionPageNext :: Maybe LocalPageURI
, collectionPageStartIndex :: Maybe Int
, collectionPageItems :: [a]
}
instance (FromJSON a, ToJSON a) => ActivityPub (CollectionPage a) where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
PageURI authority id_ <- o .: "id"
fmap (authority,) $
CollectionPage id_
<$> o .: "type"
<*> o .:? "totalItems"
<*> withAuthorityMaybeP authority (o .:? "current")
<*> withAuthorityMaybeP authority (o .:? "first")
<*> withAuthorityMaybeP authority (o .:? "last")
<*> withAuthorityO authority (o .: "partOf")
<*> withAuthorityMaybeP authority (o .:? "prev")
<*> withAuthorityMaybeP authority (o .:? "next")
<*> o .:? "startIndex"
<*> optional (o .: "items" <|> o .: "orderedItems") .!= []
toSeries authority (CollectionPage id_ typ total curr firzt last partOf prev next ind items)
= "id" .= PageURI authority id_
<> "type" .= typ
<> "totalItems" .=? total
<> "current" .=? (PageURI authority <$> curr)
<> "first" .=? (PageURI authority <$> firzt)
<> "last" .=? (PageURI authority <$> last)
<> "partOf" .= (ObjURI authority partOf)
<> "prev" .=? (PageURI authority <$> prev)
<> "next" .=? (PageURI authority <$> next)
<> "startIndex" .=? ind
<> itemsProp .=% items
where
itemsProp =
case typ of
CollectionPageTypeUnordered -> "items"
CollectionPageTypeOrdered -> "orderedItems"
data Recipient u = RecipientActor (Actor u) | RecipientCollection (Collection (ObjURI u) u)
instance ActivityPub Recipient where
jsonldContext _ = [as2Context, secContext, forgeContext]
parseObject o =
second RecipientActor <$> parseObject o <|>
second RecipientCollection <$> parseObject o
toSeries h (RecipientActor a) = toSeries h a
toSeries h (RecipientCollection c) = toSeries h c
data Resource u = ResourceActor (Actor u) | ResourceChild LocalURI LocalURI
instance ActivityPub Resource where
jsonldContext _ = [as2Context, secContext, forgeContext]
parseObject o =
second ResourceActor <$> parseObject o <|> do
ObjURI h luId <- o .: "id" <|> o .: "@id"
(h,) . ResourceChild luId <$> withAuthorityO h (o .: "managedBy")
toSeries h (ResourceActor a) = toSeries h a
toSeries h (ResourceChild luId luManager)
= "id" .= ObjURI h luId
<> "managedBy" .= ObjURI h luManager
data Audience u = Audience
{ audienceTo :: [ObjURI u]
, audienceBto :: [ObjURI u]
, audienceCc :: [ObjURI u]
, audienceBcc :: [ObjURI u]
, audienceGeneral :: [ObjURI u]
, audienceNonActors :: [ObjURI u]
}
newtype AdaptAudience u = AdaptAudience
{ unAdapt :: ObjURI u
}
instance UriMode u => FromJSON (AdaptAudience u) where
parseJSON = fmap AdaptAudience . parseJSON . adapt
where
adapt v =
case v of
String t
| t == "as:Public" -> String "Public"
| t == publicURI -> String "Public"
_ -> v
parseAudience :: UriMode u => Object -> Parser (Audience u)
parseAudience o =
Audience
<$> o .:& "to"
<*> o .:& "bto"
<*> o .:& "cc"
<*> o .:& "bcc"
<*> o .:& "audience"
<*> o .:|& "nonActors"
where
obj .:& key = do
l <- obj .:? key .!= []
return $ map unAdapt l
obj .:|& key = do
l <- obj .:|? key .!= []
return $ map unAdapt l
encodeAudience :: UriMode u => Audience u -> Series
encodeAudience (Audience to bto cc bcc aud nons)
= "to" .=% to
<> "bto" .=% bto
<> "cc" .=% cc
<> "bcc" .=% bcc
<> "audience" .=% aud
<> "nonActors" .=% nons
data Note u = Note
{ noteId :: Maybe LocalURI
, noteAttrib :: LocalURI
, noteAudience :: Audience u
, noteReplyTo :: Maybe (ObjURI u)
, noteContext :: Maybe (ObjURI u)
, notePublished :: Maybe UTCTime
, noteSource :: PandocMarkdown
, noteContent :: HTML
}
withAuthorityT a m = do
(a', v) <- m
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityO a m = do
ObjURI a' v <- m
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityS a m = do
SubURI a' v <- m
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityP a m = do
PageURI a' v <- m
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityD a m = do
Doc a' v <- m
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityMaybeT a m = do
mu <- m
for mu $ \ (a', v) ->
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityMaybeO a m = do
mu <- m
for mu $ \ (ObjURI a' v) ->
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityMaybeS a m = do
mu <- m
for mu $ \ (SubURI a' v) ->
if a == a'
then return v
else fail "URI authority mismatch"
withAuthorityMaybeP a m = do
mu <- m
for mu $ \ (PageURI a' v) ->
if a == a'
then return v
else fail "URI authority mismatch"
instance ActivityPub Note where
jsonldContext _ = [as2Context]
parseObject o = do
typ <- o .: "type"
unless (typ == ("Note" :: Text)) $
fail "type isn't Note"
mediaType <- o .: "mediaType"
unless (mediaType == ("text/html" :: Text)) $
fail "mediaType isn't HTML"
source <- o .: "source"
sourceType <- source .: "mediaType"
unless (sourceType == ("text/markdown; variant=Pandoc" :: Text)) $
fail "source mediaType isn't Pandoc Markdown"
ObjURI a attrib <- o .: "attributedTo"
fmap (a,) $
Note
<$> withAuthorityMaybeO a (o .:? "id")
<*> pure attrib
<*> parseAudience o
<*> o .:? "inReplyTo"
<*> o .:? "context"
<*> o .:? "published"
<*> source .: "content"
<*> o .: "content"
toSeries authority (Note mid attrib aud mreply mcontext mpublished src content)
= "type" .= ("Note" :: Text)
<> "id" .=? (ObjURI authority <$> mid)
<> "attributedTo" .= ObjURI authority attrib
<> encodeAudience aud
<> "inReplyTo" .=? mreply
<> "context" .=? mcontext
<> "published" .=? mpublished
<> "source" .= object
[ "content" .= src
, "mediaType" .= ("text/markdown; variant=Pandoc" :: Text)
]
<> "content" .= content
<> "mediaType" .= ("text/html" :: Text)
data RelationshipProperty = RelDependsOn deriving Eq
instance FromJSON RelationshipProperty where
parseJSON = withText "RelationshipProperty" parse
where
parse t
| t == "dependsOn" = pure RelDependsOn
| otherwise = fail $ "Unrecognized relationship: " ++ T.unpack t
instance ToJSON RelationshipProperty where
toJSON = error "toJSON RelationshipProperty"
toEncoding at =
toEncoding $ case at of
RelDependsOn -> "dependsOn" :: Text
data Relationship u = Relationship
{ relationshipId :: Maybe (ObjURI u)
, relationshipExtraTypes :: [Text]
, relationshipSubject :: ObjURI u
, relationshipProperty :: Either RelationshipProperty Text
, relationshipObject :: ObjURI u
, relationshipAttributedTo :: LocalURI
, relationshipPublished :: Maybe UTCTime
, relationshipUpdated :: Maybe UTCTime
}
instance ActivityPub Relationship where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
typs <- o .: "type"
unless (("Relationship" :: Text) `elem` typs) $
fail "type isn't Relationship"
ObjURI a attributedTo <- o .: "attributedTo"
fmap (a,) $
Relationship
<$> o .:? "id"
<*> pure (delete "Relationship" typs)
<*> o .: "subject"
<*> o .:+ "relationship"
<*> o .: "object"
<*> pure attributedTo
<*> o .:? "published"
<*> o .:? "updated"
toSeries authority
(Relationship id_ typs subject property object attributedTo published
updated)
= "id" .=? id_
<> "type" .= ("Relationship" : typs)
<> "subject" .= subject
<> "relationship" .=+ property
<> "object" .= object
<> "attributedTo" .= ObjURI authority attributedTo
<> "published" .=? published
<> "updated" .=? updated
data TicketDependency u = TicketDependency
{ ticketDepId :: Maybe (ObjURI u)
, ticketDepParent :: ObjURI u
, ticketDepChild :: ObjURI u
, ticketDepAttributedTo :: LocalURI
, ticketDepPublished :: Maybe UTCTime
, ticketDepUpdated :: Maybe UTCTime
}
instance ActivityPub TicketDependency where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
(a, rel) <- parseObject o
unless ("TicketDependency" `elem` relationshipExtraTypes rel) $
fail "type isn't TicketDependency"
unless (relationshipProperty rel == Left RelDependsOn) $
fail "relationship isn't dependsOn"
return (a, rel2td rel)
where
rel2td rel = TicketDependency
{ ticketDepId = relationshipId rel
, ticketDepParent = relationshipSubject rel
, ticketDepChild = relationshipObject rel
, ticketDepAttributedTo = relationshipAttributedTo rel
, ticketDepPublished = relationshipPublished rel
, ticketDepUpdated = relationshipUpdated rel
}
toSeries a = toSeries a . td2rel
where
td2rel td = Relationship
{ relationshipId = ticketDepId td
, relationshipExtraTypes = ["TicketDependency"]
, relationshipSubject = ticketDepParent td
, relationshipProperty = Left RelDependsOn
, relationshipObject = ticketDepChild td
, relationshipAttributedTo = ticketDepAttributedTo td
, relationshipPublished = ticketDepPublished td
, relationshipUpdated = ticketDepUpdated td
}
data PatchLocal = PatchLocal
{ patchId :: LocalURI
, patchContext :: LocalURI
}
parsePatchLocal
:: UriMode u => Object -> Parser (Maybe (Authority u, PatchLocal))
parsePatchLocal o = do
mid <- o .:? "id"
case mid of
Nothing -> do
verifyNothing "context"
return Nothing
Just (ObjURI a id_) ->
fmap (Just . (a,)) $
PatchLocal
<$> pure id_
<*> withAuthorityO a (o .: "context")
where
verifyNothing t =
if t `M.member` o
then fail $ T.unpack t ++ " field found, expected none"
else return ()
encodePatchLocal :: UriMode u => Authority u -> PatchLocal -> Series
encodePatchLocal a (PatchLocal id_ context)
= "id" .= ObjURI a id_
<> "context" .= ObjURI a context
data Patch u = Patch
{ patchLocal :: Maybe (Authority u, PatchLocal)
, patchAttributedTo :: LocalURI
, patchPublished :: Maybe UTCTime
, patchType :: PatchMediaType
, patchContent :: Text
}
instance ActivityPub Patch where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
typ <- o .: "type"
unless (typ == ("Patch" :: Text)) $
fail "type isn't Patch"
ObjURI a attrib <- o .: "attributedTo"
fmap (a,) $
Patch
<$> parsePatchLocal o
<*> pure attrib
<*> o .:? "published"
<*> o .: "mediaType"
<*> o .: "content"
toSeries a (Patch local attrib published typ content)
= maybe mempty (uncurry encodePatchLocal) local
<> "type" .= ("Patch" :: Text)
<> "attributedTo" .= ObjURI a attrib
<> "published" .=? published
<> "mediaType" .= typ
<> "content" .= content
data BundleLocal = BundleLocal
{ bundleId :: LocalURI
, bundleContext :: LocalURI
, bundlePrevVersions :: [LocalURI]
, bundleCurrentVersion :: Maybe LocalURI
}
parseBundleLocal
:: UriMode u => Object -> Parser (Maybe (Authority u, BundleLocal))
parseBundleLocal o = do
mid <- o .:? "id"
case mid of
Nothing -> do
verifyNothing "context"
verifyNothing "previousVersions"
verifyNothing "currentVersion"
return Nothing
Just (ObjURI a id_) ->
fmap (Just . (a,)) $
BundleLocal
<$> pure id_
<*> withAuthorityO a (o .: "context")
<*> (traverse (withAuthorityO a . return) =<< o .:? "previousVersions" .!= [])
<*> withAuthorityMaybeO a (o .:? "currentVersion")
where
verifyNothing t =
if t `M.member` o
then fail $ T.unpack t ++ " field found, expected none"
else return ()
encodeBundleLocal :: UriMode u => Authority u -> BundleLocal -> Series
encodeBundleLocal a (BundleLocal id_ context versions mcurrent)
= "id" .= ObjURI a id_
<> "context" .= ObjURI a context
<> "previousVersions" .= map (ObjURI a) versions
<> "currentVersion" .=? (ObjURI a <$> mcurrent)
data Bundle u
= BundleHosted (Maybe BundleLocal) (NonEmpty LocalURI)
| BundleOffer (Maybe (Authority u, BundleLocal)) (NonEmpty (Patch u))
instance ActivityPub Bundle where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
typ <- o .: "type"
unless (typ == ("OrderedCollection" :: Text)) $
fail "type isn't OrderedCollection"
mlocal <- parseBundleLocal o
mtotal <- o .:? "totalItems"
items <- toEither <$> o .: "orderedItems" <|> o .: "items"
case items of
Left (ObjURI h lu :| us) -> do
for_ mlocal $ \ (h', _) ->
unless (h == h') $
fail "Patches in bundle not on the same host as bundle"
unless (all (== h) $ map objUriAuthority us) $
fail "Patches in bundle on different hosts"
for_ mtotal $ \ total ->
unless (length us + 1 == total) $
fail "Incorrect totalItems"
return (h, BundleHosted (snd <$> mlocal) $ lu :| map objUriLocal us)
Right (Doc h p :| ps) -> do
unless (all (== h) $ map docAuthority ps) $
fail "Patches in bundle have different authors"
for_ mtotal $ \ total ->
unless (length ps + 1 == total) $
fail "Incorrect totalItems"
return (h, BundleOffer mlocal $ p :| map docValue ps)
toSeries hBundle (BundleHosted mlocal lus)
= maybe mempty (encodeBundleLocal hBundle) mlocal
<> "type" .= ("OrderedCollection" :: Text)
<> "totalItems" .= length lus
<> "orderedItems" .= NE.map (ObjURI hBundle) lus
toSeries hAttrib (BundleOffer mlocal patches)
= maybe mempty (uncurry encodeBundleLocal) mlocal
<> "type" .= ("OrderedCollection" :: Text)
<> "totalItems" .= length patches
<> "orderedItems" .= NE.map (Doc hAttrib) patches
data TicketLocal = TicketLocal
{ ticketId :: LocalURI
, ticketReplies :: LocalURI
, ticketParticipants :: LocalURI
, ticketTeam :: Maybe LocalURI
, ticketEvents :: LocalURI
, ticketDeps :: LocalURI
, ticketReverseDeps :: LocalURI
}
parseTicketLocal :: UriMode u => Object -> Parser (Maybe (Authority u, TicketLocal))
parseTicketLocal o = do
mid <- o .:? "id"
case mid of
Nothing -> do
verifyNothing "replies"
verifyNothing "participants"
verifyNothing "followers"
verifyNothing "team"
verifyNothing "history"
verifyNothing "dependencies"
verifyNothing "dependants"
return Nothing
Just (ObjURI a id_) ->
fmap (Just . (a,)) $
TicketLocal
<$> pure id_
<*> withAuthorityO a (o .: "replies")
<*> withAuthorityO a (o .: "participants" <|> o .: "followers")
<*> withAuthorityMaybeO a (o .:? "team")
<*> withAuthorityO a (o .: "history")
<*> withAuthorityO a (o .: "dependencies")
<*> withAuthorityO a (o .: "dependants")
where
verifyNothing t =
if t `M.member` o
then fail $ T.unpack t ++ " field found, expected none"
else return ()
encodeTicketLocal :: UriMode u => Authority u -> TicketLocal -> Series
encodeTicketLocal
a (TicketLocal id_ replies followers team events deps rdeps)
= "id" .= ObjURI a id_
<> "replies" .= ObjURI a replies
<> "followers" .= ObjURI a followers
<> "team" .=? (ObjURI a <$> team)
<> "history" .= ObjURI a events
<> "dependencies" .= ObjURI a deps
<> "dependants" .= ObjURI a rdeps
data MergeRequest u = MergeRequest
{ mrOrigin :: Maybe (Either (ObjURI u) (Authority u, Branch u))
, mrTarget :: Either LocalURI (Branch u)
, mrBundle :: Maybe (Either (ObjURI u) (Authority u, Bundle u))
}
instance ActivityPub MergeRequest where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
typ <- o .: "type"
unless (typ == ("Offer" :: Text)) $
fail "type isn't Offer"
target <- o .:+ "target"
let (a, target') =
case target of
Left (ObjURI h lu) -> (h, Left lu)
Right (Doc h branch) -> (h, Right branch)
fmap (a,) $
MergeRequest
<$> (fmap (second fromDoc) <$> o .:+? "origin")
<*> pure target'
<*> (fmap (second fromDoc) <$> o .:+? "object")
where
fromDoc (Doc h v) = (h, v)
toSeries h (MergeRequest morigin target bundle)
= "type" .= ("Offer" :: Text)
<> "origin" .=+? fmap (second $ uncurry Doc) morigin
<> "target" .=+ bimap (ObjURI h) (Doc h) target
<> "object" .=+? fmap (second $ uncurry Doc) bundle
data Ticket u = Ticket
{ ticketLocal :: Maybe (Authority u, TicketLocal)
, ticketAttributedTo :: LocalURI
, ticketPublished :: Maybe UTCTime
, ticketUpdated :: Maybe UTCTime
, ticketContext :: Maybe (ObjURI u)
-- , ticketName :: Maybe Text
, ticketSummary :: Escaped
, ticketContent :: HTML
, ticketSource :: PandocMarkdown
, ticketAssignedTo :: Maybe (ObjURI u)
, ticketResolved :: Maybe (Maybe (ObjURI u), Maybe UTCTime)
, ticketAttachment :: Maybe (Authority u, MergeRequest u)
}
instance ActivityPub Ticket where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
typ <- o .: "type"
unless (typ == ("Ticket" :: Text)) $
fail "type isn't Ticket"
mediaType <- o .: "mediaType"
unless (mediaType == ("text/html" :: Text)) $
fail "mediaType isn't HTML"
source <- o .: "source"
sourceType <- source .: "mediaType"
unless (sourceType == ("text/markdown; variant=Pandoc" :: Text)) $
fail "source mediaType isn't Pandoc Markdown"
ObjURI a attributedTo <- o .: "attributedTo"
mresolved <- do
is <- o .:? "isResolved" .!= False
if is
then do
at <- o .:? "resolved"
by <- o .:? "resolvedBy"
return $ Just (by, at)
else do
verifyNothing "resolved"
verifyNothing "resolvedBy"
return Nothing
fmap (a,) $
Ticket
<$> parseTicketLocal o
<*> pure attributedTo
<*> o .:? "published"
<*> o .:? "updated"
<*> o .:? "context"
-- <*> o .:? "name"
<*> o .: "summary"
<*> o .: "content"
<*> source .: "content"
<*> o .:? "assignedTo"
<*> pure mresolved
<*> (traverse parseObject =<< o .:? "attachment")
where
verifyNothing t =
if t `M.member` o
then fail $ T.unpack t ++ " field found, expected none"
else return ()
toSeries authority
(Ticket local attributedTo published updated context {-name-}
summary content source assignedTo mresolved mmr)
= maybe mempty (uncurry encodeTicketLocal) local
<> "type" .= ("Ticket" :: Text)
<> "attributedTo" .= ObjURI authority attributedTo
<> "published" .=? published
<> "updated" .=? updated
<> "context" .=? context
-- <> "name" .=? name
<> "summary" .= summary
<> "content" .= content
<> "mediaType" .= ("text/html" :: Text)
<> "source" .= object
[ "content" .= source
, "mediaType" .= ("text/markdown; variant=Pandoc" :: Text)
]
<> "assignedTo" .=? assignedTo
<> maybe
("isResolved" .= False)
(\ (mby, mat)
-> "isResolved" .= True
<> "resolvedBy" .=? mby
<> "resolved" .=? mat
)
mresolved
<> maybe
mempty
(\ (h, mr) -> "attachment" `pair` pairs (toSeries h mr))
mmr
data Author = Author
{ authorName :: Text
, authorEmail :: EmailAddress
}
instance FromJSON Author where
parseJSON = withObject "Author" $ \ o ->
Author
<$> o .: "name"
<*> (parseMailto =<< o .: "mbox")
where
parseMailto =
either fail return .
A.parseOnly (A.string "mailto:" *> E.addrSpec <* A.endOfInput) .
encodeUtf8
instance ToJSON Author where
toJSON = error "toJSON Author"
toEncoding (Author name email) =
pairs
$ "name" .= name
<> "mbox" .= ("mailto:" <> decodeUtf8 (E.toByteString email))
newtype Hash = Hash ByteString
instance FromJSON Hash where
parseJSON = withText "Hash" $ \ t ->
let b = encodeUtf8 t
in if not (BC.null b) && BC.all isHexDigit b
then return $ Hash b
else fail "Hash should be a non-empty hex string"
instance ToJSON Hash where
toJSON (Hash b) = toJSON $ decodeUtf8 b
toEncoding (Hash b) = toEncoding $ decodeUtf8 b
data Commit u = Commit
{ commitId :: LocalURI
, commitRepository :: LocalURI
, commitAuthor :: Either Author (ObjURI u)
, commitCommitter :: Maybe (Either Author (ObjURI u))
, commitTitle :: Text
, commitHash :: Hash
, commitDescription :: Maybe Text
, commitWritten :: UTCTime
, commitCommitted :: Maybe UTCTime
}
instance ActivityPub Commit where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
typ <- o .: "type"
unless (typ == ("Commit" :: Text)) $
fail "type isn't Commit"
mdesc <- o .:? "description"
mdescContent <- for mdesc $ \ desc -> do
descType <- desc .: "mediaType"
unless (descType == ("text/plain" :: Text)) $
fail "description mediaType isn't \"text/plain\""
desc .: "content"
ObjURI a id_ <- o .: "id"
fmap (a,) $
Commit id_
<$> withAuthorityO a (o .: "context")
<*> o .:+ "attributedTo"
<*> o .:+? "committedBy"
<*> o .: "name"
<*> o .: "hash"
<*> pure mdescContent
<*> o .: "created"
<*> o .:? "committed"
toSeries authority
(Commit id_ repo author committer title hash mdesc written mcommitted)
= "id" .= ObjURI authority id_
<> "type" .= ("Commit" :: Text)
<> "context" .= ObjURI authority repo
<> "attributedTo" .=+ author
<> "committedBy" .=+? committer
<> "name" .= title
<> "hash" .= hash
<> maybe
mempty
(\ desc -> "description" .= object
[ "content" .= desc
, "mediaType" .= ("text/plain" :: Text)
]
)
mdesc
<> "created" .= written
<> "committed" .=? mcommitted
data Branch u = Branch
{ branchName :: Text
, branchRef :: Text
, branchRepo :: LocalURI
}
instance ActivityPub Branch where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
typ <- o .: "type"
unless (typ == ("Branch" :: Text)) $
fail "type isn't Branch"
ObjURI a repo <- o .: "context"
fmap (a,) $
Branch
<$> o .: "name"
<*> o .: "ref"
<*> pure repo
toSeries authority (Branch name ref repo)
= "type" .= ("Branch" :: Text)
<> "name" .= name
<> "ref" .= ref
<> "context" .= ObjURI authority repo
data Role = RoleAdmin deriving Eq
instance FromJSON Role where
parseJSON = withText "Role" parse
where
parse "https://forgefed.org/ns#admin" = pure RoleAdmin
parse t = fail $ "Unknown role: " ++ T.unpack t
instance ToJSON Role where
toJSON = error "toJSON Role"
toEncoding r =
toEncoding $ case r of
RoleAdmin -> "https://forgefed.org/ns#admin" :: Text
data Accept u = Accept
{ acceptObject :: ObjURI u
, acceptResult :: Maybe LocalURI
}
parseAccept :: UriMode u => Authority u -> Object -> Parser (Accept u)
parseAccept a o =
Accept
<$> o .: "object"
<*> withAuthorityMaybeO a (o .:? "result")
encodeAccept :: UriMode u => Authority u -> Accept u -> Series
encodeAccept authority (Accept obj mresult)
= "object" .= obj
<> "result" .=? (ObjURI authority <$> mresult)
data AddObject u = AddBundle (NonEmpty (Patch u))
instance ActivityPub AddObject where
jsonldContext = error "jsonldContext AddObject"
parseObject o = do
(h, b) <- parseObject o
patches <-
case b of
BundleHosted _ _ -> fail "Patches specified as URIs"
BundleOffer mlocal pts -> do
for_ mlocal $ \ _ -> fail "Bundle 'id' specified"
return pts
return (h, AddBundle patches)
toSeries h (AddBundle ps) = toSeries h $ BundleOffer Nothing ps
data Add u = Add
{ addObject :: Either (ObjURI u) (AddObject u)
, addTarget :: ObjURI u
}
parseAdd :: UriMode u => Object -> Authority u -> Parser (Add u)
parseAdd o h = Add
<$> (bitraverse pure (withAuthorityD h . pure) =<<
toEither <$> o .: "object"
)
<*> o .: "target"
encodeAdd :: UriMode u => Authority u -> Add u -> Series
encodeAdd h (Add obj target)
= case obj of
Left u -> "object" .= u
Right o -> "object" `pair` pairs (toSeries h o)
<> "target" .= target
data Apply u = Apply
{ applyObject :: ObjURI u
, applyTarget :: Either (ObjURI u) (Authority u, Branch u)
}
parseApply :: UriMode u => Object -> Parser (Apply u)
parseApply o =
Apply
<$> o .: "object"
<*> (second fromDoc <$> o .:+ "target")
where
fromDoc (Doc h v) = (h, v)
encodeApply :: UriMode u => Apply u -> Series
encodeApply (Apply obj target)
= "object" .= obj
<> "target" .=+ second (uncurry Doc) target
data CreateObject u
= CreateNote (Authority u) (Note u)
| CreateTicket (Authority u) (Ticket u)
| CreateTicketTracker ActorDetail (Maybe (Authority u, ActorLocal u))
| CreateRepository ActorDetail VersionControlSystem (Maybe (Authority u, ActorLocal u))
| CreatePatchTracker ActorDetail (NonEmpty (ObjURI u)) (Maybe (Authority u, ActorLocal u))
parseCreateObject :: UriMode u => Object -> Parser (CreateObject u)
parseCreateObject o
= uncurry CreateNote <$> parseObject o
<|> uncurry CreateTicket <$> parseObject o
<|> do d <- parseActorDetail o
unless (actorType d == ActorTypeTicketTracker) $
fail "type isn't TicketTracker"
ml <- parseActorLocal o
return $ CreateTicketTracker d ml
<|> do d <- parseActorDetail o
unless (actorType d == ActorTypeRepo) $
fail "type isn't Repository"
vcs <- o .: "versionControlSystem"
ml <- parseActorLocal o
return $ CreateRepository d vcs ml
<|> do d <- parseActorDetail o
unless (actorType d == ActorTypePatchTracker) $
fail "type isn't PatchTracker"
repos <- o .:*+ "tracksPatchesFor"
ml <- parseActorLocal o
return $ CreatePatchTracker d repos ml
encodeCreateObject :: UriMode u => CreateObject u -> Series
encodeCreateObject (CreateNote h note) = toSeries h note
encodeCreateObject (CreateTicket h ticket) = toSeries h ticket
encodeCreateObject (CreateTicketTracker d ml) =
encodeActorDetail d <> maybe mempty (uncurry encodeActorLocal) ml
encodeCreateObject (CreateRepository d vcs ml)
= encodeActorDetail d
<> "versionControlSystem" .= vcs
<> maybe mempty (uncurry encodeActorLocal) ml
encodeCreateObject (CreatePatchTracker d repos ml)
= encodeActorDetail d
<> "tracksPatchesFor" .=*+ repos
<> maybe mempty (uncurry encodeActorLocal) ml
data Create u = Create
{ createObject :: CreateObject u
, createTarget :: Maybe (ObjURI u)
}
parseCreate :: UriMode u => Object -> Authority u -> LocalURI -> Parser (Create u)
parseCreate o a luActor = do
obj <- parseCreateObject =<< o .: "object"
case obj of
CreateNote h note ->
unless (a == h && luActor == noteAttrib note) $
fail "Create actor != note attrib"
CreateTicket h ticket ->
unless (a == h && luActor == ticketAttributedTo ticket) $
fail "Create actor != note attrib"
CreateTicketTracker _ _ -> return ()
CreateRepository _ _ _ -> return ()
CreatePatchTracker _ _ _ -> return ()
Create obj <$> o .:? "target"
encodeCreate :: UriMode u => Create u -> Series
encodeCreate (Create obj target)
= "object" `pair` pairs (encodeCreateObject obj)
<> "target" .=? target
data Follow u = Follow
{ followObject :: ObjURI u
, followContext :: Maybe LocalURI
, followHide :: Bool
}
parseFollow :: UriMode u => Object -> Parser (Follow u)
parseFollow o = do
u@(ObjURI h _) <- o .: "object"
Follow u
<$> withAuthorityMaybeO h (o .:? "context")
<*> o .:? "hide" .!= False
encodeFollow :: UriMode u => Follow u -> Series
encodeFollow (Follow obj mcontext hide)
= "object" .= obj
<> "context" .=? (ObjURI (objUriAuthority obj) <$> mcontext)
<> "hide" .= hide
data Grant u = Grant
{ grantObject :: Either Role (ObjURI u)
, grantContext :: ObjURI u
, grantTarget :: ObjURI u
}
parseGrant :: UriMode u => Object -> Parser (Grant u)
parseGrant o =
Grant
<$> o .:+ "object"
<*> o .: "context"
<*> o .: "target"
encodeGrant :: UriMode u => Grant u -> Series
encodeGrant (Grant obj context target)
= "object" .=+ obj
<> "context" .= context
<> "target" .= target
data Invite u = Invite
{ inviteInstrument :: Either Role (ObjURI u)
, inviteObject :: ObjURI u
, inviteTarget :: ObjURI u
}
parseInvite :: UriMode u => Object -> Parser (Invite u)
parseInvite o =
Invite
<$> o .:+ "instrument"
<*> o .: "object"
<*> o .: "target"
encodeInvite :: UriMode u => Invite u -> Series
encodeInvite (Invite obj context target)
= "object" .=+ obj
<> "context" .= context
<> "target" .= target
data Join u = Join
{ joinInstrument :: Either Role (ObjURI u)
, joinObject :: ObjURI u
}
parseJoin :: UriMode u => Object -> Parser (Join u)
parseJoin o =
Join
<$> o .:+ "instrument"
<*> o .: "object"
encodeJoin :: UriMode u => Join u -> Series
encodeJoin (Join obj context)
= "object" .=+ obj
<> "context" .= context
data OfferObject u = OfferTicket (Ticket u) | OfferDep (TicketDependency u)
instance ActivityPub OfferObject where
jsonldContext = error "jsonldContext OfferObject"
parseObject o
= second OfferTicket <$> parseObject o
<|> second OfferDep <$> parseObject o
toSeries h (OfferTicket t) = toSeries h t
toSeries h (OfferDep d) = toSeries h d
data Offer u = Offer
{ offerObject :: OfferObject u
, offerTarget :: ObjURI u
}
parseOffer :: UriMode u => Object -> Authority u -> LocalURI -> Parser (Offer u)
parseOffer o a luActor = do
obj <- withAuthorityT a $ parseObject =<< o .: "object"
target@(ObjURI hTarget luTarget) <- o .: "target"
case obj of
OfferTicket ticket -> do
unless (luActor == ticketAttributedTo ticket) $
fail "Offer actor != Ticket attrib"
for_ (ticketContext ticket) $ \ (ObjURI hContext luContext) -> do
unless (hTarget == hContext) $
fail "Offer target host != Ticket context host"
unless (luTarget == luContext) $
fail "Offer target != Ticket context"
OfferDep dep -> do
unless (luActor == ticketDepAttributedTo dep) $
fail "Offer actor != TicketDependency attrib"
return $ Offer obj target
encodeOffer :: UriMode u => Authority u -> LocalURI -> Offer u -> Series
encodeOffer authority actor (Offer obj target)
= "object" `pair` pairs (toSeries authority obj)
<> "target" .= target
data Push u = Push
{ pushCommitsLast :: NonEmpty (Commit u)
, pushCommitsFirst :: Maybe (NonEmpty (Commit u))
, pushCommitsTotal :: Int
, pushTarget :: Either LocalURI (Branch u)
, pushAttrib :: ObjURI u
, pushHashBefore :: Maybe Text
, pushHashAfter :: Maybe Text
}
parsePush :: UriMode u => Authority u -> Object -> Parser (Push u)
parsePush a o = do
c <- o .: "object"
Push
<$> (traverse (withAuthorityT a . parseObject) =<< c .: "items" <|> c .: "orderedItems")
<*> (traverse (traverse $ withAuthorityT a . parseObject) =<< c .:? "earlyItems")
<*> c .: "totalItems"
<*> (do target <- o .:+ "target"
let (h, target') =
case target of
Left (ObjURI h lu) -> (h, Left lu)
Right (Doc h branch) -> (h, Right branch)
unless (h == a) $ fail "target host != Push host"
return target'
)
<*> o .: "attributedTo"
<*> o .:? "hashBefore"
<*> o .:? "hashAfter"
encodePush :: UriMode u => Authority u -> Push u -> Series
encodePush a (Push lateCommits earlyCommits total target attrib before after)
= "object" `pair` pairs
( "type" .= ("OrderedCollection" :: Text)
<> pair "orderedItems" (objectList lateCommits)
<> maybe mempty (pair "earlyItems" . objectList) earlyCommits
<> "totalItems" .= total
)
<> "target" .=+ bimap (ObjURI a) (Doc a) target
<> "attributedTo" .= attrib
<> "hashBefore" .=? before
<> "hashAfter" .=? after
where
objectList items = listEncoding (pairs . toSeries a) (NE.toList items)
data Reject u = Reject
{ rejectObject :: ObjURI u
}
parseReject :: UriMode u => Object -> Parser (Reject u)
parseReject o = Reject <$> o .: "object"
encodeReject :: UriMode u => Reject u -> Series
encodeReject (Reject obj) = "object" .= obj
data Resolve u = Resolve
{ resolveObject :: ObjURI u
}
parseResolve :: UriMode u => Object -> Parser (Resolve u)
parseResolve o = Resolve <$> o .: "object"
encodeResolve :: UriMode u => Resolve u -> Series
encodeResolve (Resolve obj) = "object" .= obj
data Undo u = Undo
{ undoObject :: ObjURI u
}
parseUndo :: UriMode u => Authority u -> Object -> Parser (Undo u)
parseUndo a o = Undo <$> o .: "object"
encodeUndo :: UriMode u => Authority u -> Undo u -> Series
encodeUndo a (Undo obj) = "object" .= obj
data SpecificActivity u
= AcceptActivity (Accept u)
| AddActivity (Add u)
| ApplyActivity (Apply u)
| CreateActivity (Create u)
| FollowActivity (Follow u)
| GrantActivity (Grant u)
| InviteActivity (Invite u)
| JoinActivity (Join u)
| OfferActivity (Offer u)
| PushActivity (Push u)
| RejectActivity (Reject u)
| ResolveActivity (Resolve u)
| UndoActivity (Undo u)
activityType :: SpecificActivity u -> Text
activityType (AcceptActivity _) = "Accept"
activityType (AddActivity _) = "Add"
activityType (ApplyActivity _) = "Apply"
activityType (CreateActivity _) = "Create"
activityType (FollowActivity _) = "Follow"
activityType (GrantActivity _) = "Grant"
activityType (InviteActivity _) = "Invite"
activityType (JoinActivity _) = "Join"
activityType (OfferActivity _) = "Offer"
activityType (PushActivity _) = "Push"
activityType (RejectActivity _) = "Reject"
activityType (ResolveActivity _) = "Resolve"
activityType (UndoActivity _) = "Undo"
data Action u = Action
{ actionCapability :: Maybe (ObjURI u)
, actionSummary :: Maybe HTML
, actionAudience :: Audience u
, actionFulfills :: [ObjURI u]
, actionSpecific :: SpecificActivity u
}
makeActivity :: LocalURI -> LocalURI -> Action u -> Activity u
makeActivity luId luActor Action{..} = Activity
{ activityId = Just luId
, activityActor = luActor
, activityCapability = actionCapability
, activitySummary = actionSummary
, activityAudience = actionAudience
, activityFulfills = actionFulfills
, activitySpecific = actionSpecific
}
data Activity u = Activity
{ activityId :: Maybe LocalURI
, activityActor :: LocalURI
, activityCapability :: Maybe (ObjURI u)
, activitySummary :: Maybe HTML
, activityAudience :: Audience u
, activityFulfills :: [ObjURI u]
, activitySpecific :: SpecificActivity u
}
instance ActivityPub Activity where
jsonldContext _ = [as2Context, forgeContext]
parseObject o = do
ObjURI a actor <- o .: "actor"
fmap (a,) $
Activity
<$> withAuthorityMaybeO a (o .:? "id")
<*> pure actor
<*> o .:? "capability"
<*> o .:? "summary"
<*> parseAudience o
<*> o .:? "fulfills" .!= []
<*> do
typ <- o .: "type"
case typ of
"Accept" -> AcceptActivity <$> parseAccept a o
"Add" -> AddActivity <$> parseAdd o a
"Apply" -> ApplyActivity <$> parseApply o
"Create" -> CreateActivity <$> parseCreate o a actor
"Follow" -> FollowActivity <$> parseFollow o
"Grant" -> GrantActivity <$> parseGrant o
"Invite" -> InviteActivity <$> parseInvite o
"Join" -> JoinActivity <$> parseJoin o
"Offer" -> OfferActivity <$> parseOffer o a actor
"Push" -> PushActivity <$> parsePush a o
"Reject" -> RejectActivity <$> parseReject o
"Resolve" -> ResolveActivity <$> parseResolve o
"Undo" -> UndoActivity <$> parseUndo a o
_ ->
fail $
"Unrecognized activity type: " ++ T.unpack typ
toSeries authority (Activity id_ actor mcap summary audience fulfills specific)
= "type" .= activityType specific
<> "id" .=? (ObjURI authority <$> id_)
<> "actor" .= ObjURI authority actor
<> "capability" .=? mcap
<> "summary" .=? summary
<> encodeAudience audience
<> "fulfills" .=% fulfills
<> encodeSpecific authority actor specific
where
encodeSpecific h _ (AcceptActivity a) = encodeAccept h a
encodeSpecific h _ (AddActivity a) = encodeAdd h a
encodeSpecific _ _ (ApplyActivity a) = encodeApply a
encodeSpecific _ _ (CreateActivity a) = encodeCreate a
encodeSpecific _ _ (FollowActivity a) = encodeFollow a
encodeSpecific _ _ (GrantActivity a) = encodeGrant a
encodeSpecific _ _ (InviteActivity a) = encodeInvite a
encodeSpecific _ _ (JoinActivity a) = encodeJoin a
encodeSpecific h u (OfferActivity a) = encodeOffer h u a
encodeSpecific h _ (PushActivity a) = encodePush h a
encodeSpecific _ _ (RejectActivity a) = encodeReject a
encodeSpecific _ _ (ResolveActivity a) = encodeResolve a
encodeSpecific h _ (UndoActivity a) = encodeUndo h a
emptyAudience :: Audience u
emptyAudience = Audience [] [] [] [] [] []
emptyActivity :: Activity u
emptyActivity = Activity
{ activityId = Nothing
, activityActor = topLocalURI
, activityCapability = Nothing
, activitySummary = Nothing
, activityAudience = emptyAudience
, activityFulfills = []
, activitySpecific =
RejectActivity $ Reject $ ObjURI (Authority "" Nothing) topLocalURI
}
typeActivityStreams2 :: ContentType
typeActivityStreams2 = "application/activity+json"
typeActivityStreams2LD :: ContentType
typeActivityStreams2LD =
"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""
hActivityPubActor :: HeaderName
hActivityPubActor = "ActivityPub-Actor"
provideAP :: (Monad m, ToJSON a) => m a -> Writer (Endo [ProvidedRep m]) ()
provideAP mk =
-- let enc = toEncoding v
-- provideRepType typeActivityStreams2 $ return enc
provideRepType typeActivityStreams2LD $ toEncoding <$> mk
provideAP' :: Monad m => m ByteString -> Writer (Endo [ProvidedRep m]) ()
provideAP' = provideRepType typeActivityStreams2LD
data APGetError
= APGetErrorHTTP HttpException
| APGetErrorJSON JSONException
| APGetErrorContentType Text
deriving Show
instance Exception APGetError
-- | Perform an HTTP GET request to fetch an ActivityPub object.
--
-- * Verify the URI scheme is _https:_ and authority part is present
-- * Set _Accept_ request header
-- * Perform the GET request
-- * Verify the _Content-Type_ response header
-- * Parse the JSON response body
httpGetAP
:: (MonadIO m, UriMode u, FromJSON a)
=> Manager
-> Either (ObjURI u) (SubURI u)
-> m (Either APGetError (Response a))
httpGetAP manager uri =
liftIO $
mkResult <$> try (httpAPEither manager =<< requestFromURI (toURI uri))
where
toURI = either uriFromObjURI uriFromSubURI
lookup' x = map snd . filter ((== x) . fst)
mkResult (Left e) = Left $ APGetErrorHTTP e
mkResult (Right r) =
case lookup' hContentType $ responseHeaders r of
[] -> Left $ APGetErrorContentType "No Content-Type"
[b] -> if b == typeActivityStreams2LD || b == typeActivityStreams2
then case responseBody r of
Left e -> Left $ APGetErrorJSON e
Right v -> Right $ v <$ r
else Left $ APGetErrorContentType $ "Non-AP Content-Type: " <> decodeUtf8 b
_ -> Left $ APGetErrorContentType "Multiple Content-Type"
data APPostError
= APPostErrorSig S.HttpSigGenError
| APPostErrorHTTP HttpException
deriving Show
instance Exception APPostError
hActivityPubForwarder :: HeaderName
hActivityPubForwarder = "ActivityPub-Forwarder"
hForwardingSignature :: HeaderName
hForwardingSignature = "Forwarding-Signature"
hForwardedSignature :: HeaderName
hForwardedSignature = "Forwarded-Signature"
-- | Perform an HTTP POST request to submit an ActivityPub object.
--
-- * Verify the URI scheme is _https:_ and authority part is present
-- * Set _Content-Type_ request header
-- * Set _ActivityPub-Actor_ request header
-- * Set _Digest_ request header using SHA-256 hash
-- * If recipient is given, set _ActivityPub-Forwarder_ header and compute
-- _Forwarding-Signature_ header
-- * If forwarded signature is given, set set _ActivityPub-Forwarder_ and
-- _Forwarded-Signature_ headers
-- * Compute HTTP signature and add _Signature_ request header
-- * Perform the POST request
-- * Verify the response status is 2xx
{-
httpPostAP
:: (MonadIO m, UriMode u, ToJSON a)
=> Manager
-> NonEmpty HeaderName
-> S.KeyId
-> (ByteString -> S.Signature)
-> Text
-> a
-> ObjURI u
-> Maybe (Either (ObjURI u) ByteString)
-> m (Either APPostError (Response ()))
httpPostAP manager headers keyid sign uSender value =
httpPostAPBytes manager headers keyid sign uSender $ encode value
-}
data ForwardMode u
= SendNoForward
| SendAllowForward LocalURI
| ForwardBy (ObjURI u) ByteString
data Envelope u = Envelope
{ envelopeKey :: RefURI u
, envelopeSign :: ByteString -> S.Signature
, envelopeHolder :: Maybe LocalURI
, envelopeBody :: BL.ByteString
}
data Errand u = Errand
{ errandKey :: RefURI u
, errandSign :: ByteString -> S.Signature
, errandHolder :: Bool
, errandFwder :: LocalURI
, errandBody :: BL.ByteString
, errandProof :: ByteString
}
-- | Like 'httpPostAP', except it takes the object as a raw lazy
-- 'BL.ByteString'. It's your responsibility to make sure it's valid JSON.
httpPostAPBytes
:: (MonadIO m, UriMode u)
=> Manager
-> NonEmpty HeaderName
-> RefURI u
-> (ByteString -> S.Signature)
-> Maybe LocalURI
-> BL.ByteString
-> ForwardMode u
-> ObjURI u
-> m (Either APPostError (Response ()))
httpPostAPBytes manager headers ruKey@(RefURI hKey _) sign mluHolder body fwd uInbox@(ObjURI hInbox _) =
liftIO $ runExceptT $ do
req <- requestFromURI $ uriFromObjURI uInbox
let digest = formatHttpBodyDigest SHA256 "SHA-256" $ hashlazy body
req' =
setRequestCheckStatus $
consHeader hContentType typeActivityStreams2LD $
maybe id (consHeader hActivityPubActor . TE.encodeUtf8 . renderObjURI . ObjURI hKey) mluHolder $
consHeader hDigest digest $
req { method = "POST"
, requestBody = RequestBodyLBS body
}
keyid = S.KeyId $ TE.encodeUtf8 $ renderRefURI ruKey
now <- lift getCurrentTime
req'' <- except $ first APPostErrorSig $ signRequest headers Nothing keyid sign now req'
req''' <-
case fwd of
SendNoForward -> return req''
SendAllowForward luRecip ->
except $ first APPostErrorSig $
signRequestInto hForwardingSignature (hDigest :| [hActivityPubForwarder]) Nothing keyid sign now $
consHeader hActivityPubForwarder (encodeUtf8 $ renderObjURI $ ObjURI hInbox luRecip) req''
ForwardBy uSender sig ->
return $
consHeader hForwardedSignature sig $
consHeader hActivityPubForwarder (encodeUtf8 $ renderObjURI uSender)
req''
tryExceptT APPostErrorHTTP $ httpNoBody req''' manager
where
consHeader n b r = r { requestHeaders = (n, b) : requestHeaders r }
tryExceptT adapt action = ExceptT $ first adapt <$> try action
sending
:: UriMode u
=> LocalRefURI
-> (ByteString -> S.Signature)
-> Bool
-> ObjURI u
-> LocalURI
-> Action u
-> Envelope u
sending lruKey sign holder uActor@(ObjURI hActor luActor) luId action =
Envelope
{ envelopeKey = RefURI hActor lruKey
, envelopeSign = sign
, envelopeHolder = guard holder >> Just luActor
, envelopeBody = encode $ Doc hActor $ makeActivity luId luActor action
}
retrying
:: RefURI u
-> (ByteString -> S.Signature)
-> Maybe LocalURI
-> BL.ByteString
-> Envelope u
retrying = Envelope
forwarding
:: LocalRefURI
-> (ByteString -> S.Signature)
-> Bool
-> ObjURI u
-> BL.ByteString
-> ByteString
-> Errand u
forwarding lruKey sign holder (ObjURI hFwder luFwder) body sig =
Errand
{ errandKey = RefURI hFwder lruKey
, errandSign = sign
, errandHolder = holder
, errandFwder = luFwder
, errandBody = body
, errandProof = sig
}
deliver
:: (MonadIO m, UriMode u)
=> Manager
-> NonEmpty HeaderName
-> Envelope u
-> Maybe LocalURI
-> ObjURI u
-> m (Either APPostError (Response ()))
deliver manager headers (Envelope ruKey sign mluHolder body) mluFwd uInbox =
httpPostAPBytes
manager
headers
ruKey
sign
mluHolder
body
(maybe SendNoForward SendAllowForward mluFwd)
uInbox
forward
:: (MonadIO m, UriMode u)
=> Manager
-> NonEmpty HeaderName
-> Errand u
-> ObjURI u
-> m (Either APPostError (Response ()))
forward manager headers (Errand ruKey@(RefURI hKey _) sign holder luFwder body sig) uInbox =
httpPostAPBytes
manager
headers
ruKey
sign
(guard holder >> Just luFwder)
body
(ForwardBy (ObjURI hKey luFwder) sig)
uInbox
-- | Result of GETing the keyId URI and processing the JSON document.
data Fetched = Fetched
{ fetchedPublicKey :: PublicVerifKey
-- ^ The Ed25519 or RSA public key corresponding to the URI we requested.
, fetchedKeyExpires :: Maybe UTCTime
-- ^ Optional expiration time declared for the key we received.
, fetchedActorId :: LocalURI
-- ^ The @id URI of the actor for whom the key's signature applies.
, fetchedActorName :: Maybe Text
-- ^ Name of the actor for whom the key's signature applies.
, fetchedActorInbox :: LocalURI
-- ^ The inbox URI of the actor for whom the key's signature applies.
, fetchedActorFollowers :: Maybe LocalURI
-- ^ The follower collection URI of the actor for whom the key's
-- signature applies.
, fetchedKeyShared :: Bool
-- ^ Whether the key we received is shared. A shared key can sign
-- requests for any actor on the same instance, while a personal key is
-- only for one actor. Knowing whether the key is shared will allow us
-- when receiving more requests, whether to accept signatures made on
-- different actors, or allow only a single permanent actor for the key
-- we received.
}
fetchAP' :: (MonadIO m, UriMode u, FromJSON a) => Manager -> Either (ObjURI u) (SubURI u) -> ExceptT APGetError m a
fetchAP' m u = ExceptT $ second responseBody <$> httpGetAP m u
fetchAP :: (MonadIO m, UriMode u, FromJSON a) => Manager -> Either (ObjURI u) (SubURI u) -> ExceptT String m a
fetchAP m u = withExceptT displayException $ fetchAP' m u
fetchAP_T :: (MonadIO m, UriMode u, FromJSON a) => Manager -> Either (ObjURI u) (SubURI u) -> ExceptT Text m a
fetchAP_T m u = withExceptT T.pack $ fetchAP m u
{-
fetchAPH :: (MonadIO m, ActivityPub a) => Manager -> Text -> LocalURI -> ExceptT String m a
fetchAPH m h lu = do
Doc h' v <- fetchAP m $ l2f h lu
if h == h'
then return v
else throwE "Object @id URI's host doesn't match the URI we fetched"
-}
fetchAPID' :: (MonadIO m, UriMode u, ActivityPub a) => Manager -> (a u -> LocalURI) -> Authority u -> LocalURI -> m (Either (Maybe APGetError) (a u))
fetchAPID' m getId h lu = runExceptT $ do
Doc h' v <- withExceptT Just $ fetchAP' m $ Left $ ObjURI h lu
if h == h' && getId v == lu
then return v
else throwE Nothing
fetchTip :: (MonadIO m, UriMode u) => Manager -> Authority u -> LocalURI -> m (Either (Maybe APGetError) (Either (Repo u) (Branch u)))
fetchTip m h lu = runExceptT $ do
tip <- fmap toEither $ withExceptT Just $ fetchAP' m $ Left $ ObjURI h lu
bitraverse
(\ (Doc h' repo) ->
if h == h' && actorId (actorLocal $ repoActor repo) == lu
then return repo
else throwE Nothing
)
(\ (Doc _ branch) -> pure branch)
tip
fetchRecipient :: (MonadIO m, UriMode u) => Manager -> Authority u -> LocalURI -> m (Either (Maybe APGetError) (Recipient u))
fetchRecipient m = fetchAPID' m getId
where
getId (RecipientActor a) = actorId $ actorLocal a
getId (RecipientCollection c) = collectionId c
fetchResource :: (MonadIO m, UriMode u) => Manager -> Authority u -> LocalURI -> m (Either (Maybe APGetError) (Resource u))
fetchResource m = fetchAPID' m getId
where
getId (ResourceActor a) = actorId $ actorLocal a
getId (ResourceChild luId _) = luId
fetchAPID :: (MonadIO m, UriMode u, ActivityPub a) => Manager -> (a u -> LocalURI) -> Authority u -> LocalURI -> m (Either String (a u))
fetchAPID m getId h lu = first showError <$> fetchAPID' m getId h lu
where
showError Nothing = "Object @id doesn't match the URI we fetched"
showError (Just e) = displayException e
data FetchAPError
= FetchAPErrorGet APGetError
-- Object @id doesn't match the URI we fetched
| FetchAPErrorIdMismatch
-- Object @id URI's host doesn't match the URI we fetched
| FetchAPErrorHostMismatch
deriving Show
fetchAPIDOrH'
:: (MonadIO m, UriMode u, ActivityPub a, ActivityPub b)
=> Manager
-> (a u -> LocalRefURI)
-> Authority u
-> LocalRefURI
-> ExceptT FetchAPError m (Either (a u) (b u))
fetchAPIDOrH' m getId h (LocalRefURI lu) = do
e <- withExceptT FetchAPErrorGet $ fetchAP' m $ bimap (ObjURI h) (SubURI h) lu
case e of
Left' (Doc h' x) ->
if h == h' && getId x == LocalRefURI lu
then return $ Left x
else throwE FetchAPErrorIdMismatch
Right' (Doc h' y) ->
if h == h'
then return $ Right y
else throwE FetchAPErrorHostMismatch
fetchAPIDOrH
:: (MonadIO m, UriMode u, ActivityPub a, ActivityPub b)
=> Manager
-> (a u -> LocalRefURI)
-> Authority u
-> LocalRefURI
-> ExceptT String m (Either (a u) (b u))
fetchAPIDOrH m getId h lu = withExceptT show $ fetchAPIDOrH' m getId h lu
-- | Fetches the given actor and checks whether it lists the given key (as a
-- URI, not as an embedded object). If it does, returns 'Right' the fetched
-- actor. Otherwise, or if an error occurs during fetching, returns 'Left' an
-- error message.
keyListedByActor
:: (MonadIO m, UriMode u)
=> Manager
-> Authority u
-> LocalRefURI
-> LocalURI
-> m (Either String (Actor u))
keyListedByActor manager host luKey luActor = runExceptT $ do
actor <- ExceptT $ fetchAPID manager (actorId . actorLocal) host luActor
if keyUriListed luKey actor
then return actor
else throwE "Actor publicKey has no URI matching pkey @id"
where
keyUriListed (LocalRefURI uk) a =
let match (Left uri) = Left uri == uk
match (Right _) = False
in any match $ actorPublicKeys $ actorLocal a
matchKeyObj
:: (Foldable f, Monad m, UriMode u)
=> LocalRefURI
-> f (Either LocalURI (PublicKey u))
-> ExceptT String m (PublicKey u)
matchKeyObj luKey es =
case find' (match luKey) es of
Nothing -> throwE "keyId resolved to actor which doesn't have a key object with that ID"
Just pk -> return pk
where
find' :: Foldable f => (a -> Maybe b) -> f a -> Maybe b
find' p = join . fmap getFirst . foldMap (Just . First . p)
match _ (Left _) = Nothing
match luk (Right pk) =
if publicKeyId pk == luk
then Just pk
else Nothing
verifyAlgo :: Maybe S.Algorithm -> PublicVerifKey -> Either String ()
verifyAlgo Nothing _ = Right ()
verifyAlgo (Just a) k =
case a of
S.AlgorithmEd25519 ->
case k of
PublicVerifKeyEd25519 _ -> Right ()
PublicVerifKeyRSA _ ->
Left "Algo mismatch, algo is Ed25519 but actual key is RSA"
S.AlgorithmRsaSha256 ->
case k of
PublicVerifKeyEd25519 _ ->
Left
"Algo mismatch, algo is RSA-SHA256 but actual key is \
\Ed25519"
PublicVerifKeyRSA _ -> Right ()
S.AlgorithmOther b -> Left $ concat
[ "Unrecognized algo "
, BC.unpack b
, ", actual key is "
, case k of
PublicVerifKeyEd25519 _ -> "Ed25519"
PublicVerifKeyRSA _ -> "RSA"
]
-- | Fetch a key we don't have cached locally.
fetchUnknownKey
:: (MonadIO m, UriMode u)
=> Manager
-- ^ Manager for making HTTP requests
-> Maybe S.Algorithm
-- ^ Signature algorithm possibly specified in the HTTP signature header
-> Authority u
-- ^ Instance host
-> Maybe LocalURI
-- ^ Actor URI possibly provided in the HTTP request's actor header
-> LocalRefURI
-- ^ Key URI provided in HTTP signature header
-> ExceptT String m Fetched
fetchUnknownKey manager malgo host mluActor luKey = do
obj <- fetchAPIDOrH manager publicKeyId host luKey
fetched <-
case obj of
Left pkey -> do
(oi, luActor) <-
case publicKeyOwner pkey of
OwnerInstance ->
case mluActor of
Nothing -> throwE "Key is shared but actor header not specified!"
Just u -> return (True, u)
OwnerActor owner -> do
for_ mluActor $ \ lu ->
if owner == lu
then return ()
else throwE "Key's owner doesn't match actor header"
return (False, owner)
Actor local detail <- ExceptT $ keyListedByActor manager host luKey luActor
return Fetched
{ fetchedPublicKey = publicKeyMaterial pkey
, fetchedKeyExpires = publicKeyExpires pkey
, fetchedActorId = luActor
, fetchedActorName = actorName detail <|> actorUsername detail
, fetchedActorInbox = actorInbox local
, fetchedActorFollowers = actorFollowers local
, fetchedKeyShared = oi
}
Right (Actor local detail) -> do
case luKey of
LocalRefURI (Right lsu) |
actorId local == localSubUriResource lsu -> return ()
_ -> throwE "Actor ID doesn't match the keyid URI we fetched"
for_ mluActor $ \ lu ->
if actorId local == lu
then return ()
else throwE "Key's owner doesn't match actor header"
pk <- matchKeyObj luKey $ actorPublicKeys local
owner <- case publicKeyOwner pk of
OwnerInstance -> throwE "Actor's publicKey is shared, but embedded in actor document! We allow shared keys only if they're in a separate document"
OwnerActor owner ->
if owner == actorId local
then return owner
else throwE "Actor's publicKey's owner doesn't match the actor's ID"
return Fetched
{ fetchedPublicKey = publicKeyMaterial pk
, fetchedKeyExpires = publicKeyExpires pk
, fetchedActorId = owner
, fetchedActorName = actorName detail <|> actorUsername detail
, fetchedActorInbox = actorInbox local
, fetchedActorFollowers = actorFollowers local
, fetchedKeyShared = False
}
ExceptT . pure $ verifyAlgo malgo $ fetchedPublicKey fetched
return fetched
keyDetail pk = (publicKeyMaterial pk, publicKeyExpires pk)
-- | Fetch a personal key we already have cached locally, but we'd like to
-- refresh the local copy by fetching the key again from the server.
fetchKnownPersonalKey
:: (MonadIO m, UriMode u)
=> Manager
-- ^ Manager for making HTTP requests
-> Maybe S.Algorithm
-- ^ Signature algorithm possibly specified in the HTTP signature header
-> Authority u
-- ^ Instance host
-> LocalURI
-- ^ Key owner actor ID URI
-> LocalRefURI
-- ^ Key URI
-> ExceptT String m (PublicVerifKey, Maybe UTCTime)
fetchKnownPersonalKey manager malgo host luOwner luKey@(LocalRefURI ek) = do
obj <- fetchAPIDOrH manager publicKeyId host luKey
(material, mexpires) <-
case obj of
Left pkey -> do
case publicKeyOwner pkey of
OwnerInstance -> throwE "Personal key became shared"
OwnerActor owner ->
when (luOwner /= owner) $ throwE "Key owner changed"
return $ keyDetail pkey
Right (Actor local detail) -> do
unless (Right (actorId local) == second localSubUriResource ek) $
throwE "Actor ID doesn't match the keyid URI we fetched"
unless (actorId local == luOwner) $
throwE "Key owner changed"
pk <- matchKeyObj luKey $ actorPublicKeys local
case publicKeyOwner pk of
OwnerInstance -> throwE "Personal key became shared"
OwnerActor owner ->
when (owner /= luOwner) $
throwE "Actor's publicKey's owner doesn't match the actor's ID"
return $ keyDetail pk
ExceptT . pure $ verifyAlgo malgo material
return (material, mexpires)
-- | Fetch a shared key we already have cached locally, but we'd like to
-- refresh the local copy by fetching the key again from the server.
fetchKnownSharedKey
:: (MonadIO m, UriMode u)
=> Manager
-- ^ Manager for making HTTP requests
-> Maybe S.Algorithm
-- ^ Signature algorithm possibly specified in the HTTP signature header
-> Authority u
-- ^ Instance host
-> LocalURI
-- ^ Actor ID from HTTP actor header
-> LocalRefURI
-- ^ Key URI
-> ExceptT String m (PublicVerifKey, Maybe UTCTime)
fetchKnownSharedKey manager malgo host luActor luKey = do
obj <- fetchAPIDOrH manager publicKeyId host luKey
pkey <-
case asKeyOrActor host obj of
Left pk -> return pk
Right _actor -> throwE "Expected stand-alone key, got embedded key"
case publicKeyOwner pkey of
OwnerInstance -> return ()
OwnerActor _owner -> throwE "Shared key became personal"
let (material, mexpires) = keyDetail pkey
ExceptT . pure $ verifyAlgo malgo material
return (material, mexpires)
where
asKeyOrActor
:: Authority u
-> Either (PublicKey u) (Actor u)
-> Either (PublicKey u) (Actor u)
asKeyOrActor _ = id
data Obj u = Obj
{ objId :: ObjURI u
, objType :: Text
, objContext :: Maybe (ObjURI u)
, objFollowers :: Maybe LocalURI
, objInbox :: Maybe LocalURI
, objTeam :: Maybe LocalURI
}
instance UriMode u => FromJSON (Obj u) where
parseJSON = withObject "Obj" $ \ o -> do
id_@(ObjURI h _) <- o .: "id" <|> o .: "@id"
Obj id_
<$> (o .: "type" <|> o .: "@type")
<*> o .:? "context"
<*> withAuthorityMaybeO h (o .:? "followers")
<*> withAuthorityMaybeO h (o .:? "inbox")
<*> withAuthorityMaybeO h (o .:? "team")
|