FederationController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Jobs\InboxPipeline\{
  4. InboxWorker,
  5. InboxValidator
  6. };
  7. use App\Jobs\RemoteFollowPipeline\RemoteFollowPipeline;
  8. use App\{
  9. AccountLog,
  10. Like,
  11. Profile,
  12. Status
  13. };
  14. use App\Transformer\ActivityPub\ProfileOutbox;
  15. use App\Util\Lexer\Nickname;
  16. use App\Util\Webfinger\Webfinger;
  17. use Auth;
  18. use Cache;
  19. use Carbon\Carbon;
  20. use Illuminate\Http\Request;
  21. use League\Fractal;
  22. use App\Util\ActivityPub\{
  23. Helpers,
  24. HttpSignature
  25. };
  26. use \Zttp\Zttp;
  27. class FederationController extends Controller
  28. {
  29. public function authCheck()
  30. {
  31. abort_if(!Auth::check(), 403);
  32. }
  33. public function authorizeFollow(Request $request)
  34. {
  35. $this->authCheck();
  36. $this->validate($request, [
  37. 'acct' => 'required|string|min:3|max:255',
  38. ]);
  39. $acct = $request->input('acct');
  40. $nickname = Nickname::normalizeProfileUrl($acct);
  41. return view('federation.authorizefollow', compact('acct', 'nickname'));
  42. }
  43. public function remoteFollow()
  44. {
  45. $this->authCheck();
  46. return view('federation.remotefollow');
  47. }
  48. public function remoteFollowStore(Request $request)
  49. {
  50. return;
  51. $this->authCheck();
  52. $this->validate($request, [
  53. 'url' => 'required|string',
  54. ]);
  55. abort_if(!config('federation.activitypub.remoteFollow'), 403);
  56. $follower = Auth::user()->profile;
  57. $url = $request->input('url');
  58. $url = Helpers::validateUrl($url);
  59. if(!$url) {
  60. return;
  61. }
  62. RemoteFollowPipeline::dispatch($follower, $url);
  63. return response(['success' => true, 'follower' => $follower]);
  64. }
  65. public function nodeinfoWellKnown()
  66. {
  67. abort_if(!config('federation.nodeinfo.enabled'), 404);
  68. $res = [
  69. 'links' => [
  70. [
  71. 'href' => config('pixelfed.nodeinfo.url'),
  72. 'rel' => 'http://nodeinfo.diaspora.software/ns/schema/2.0',
  73. ],
  74. ],
  75. ];
  76. return response()->json($res);
  77. }
  78. public function nodeinfo()
  79. {
  80. abort_if(!config('federation.nodeinfo.enabled'), 404);
  81. $res = Cache::remember('api:nodeinfo', now()->addMinutes(15), function () {
  82. $activeHalfYear = Cache::remember('api:nodeinfo:ahy', now()->addHours(12), function() {
  83. $count = collect([]);
  84. // $likes = Like::select('profile_id')->where('created_at', '>', now()->subMonths(6)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  85. // $count = $count->merge($likes);
  86. $statuses = Status::select('profile_id')->whereLocal(true)->where('created_at', '>', now()->subMonths(6)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  87. $count = $count->merge($statuses);
  88. $profiles = Profile::select('id')->whereNull('domain')->where('created_at', '>', now()->subMonths(6)->toDateTimeString())->groupBy('id')->pluck('id')->toArray();
  89. $count = $count->merge($profiles);
  90. return $count->unique()->count();
  91. });
  92. $activeMonth = Cache::remember('api:nodeinfo:am', now()->addHours(12), function() {
  93. $count = collect([]);
  94. // $likes = Like::select('profile_id')->where('created_at', '>', now()->subMonths(1)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  95. // $count = $count->merge($likes);
  96. $statuses = Status::select('profile_id')->whereLocal(true)->where('created_at', '>', now()->subMonths(1)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  97. $count = $count->merge($statuses);
  98. $profiles = Profile::select('id')->whereNull('domain')->where('created_at', '>', now()->subMonths(1)->toDateTimeString())->groupBy('id')->pluck('id')->toArray();
  99. $count = $count->merge($profiles);
  100. return $count->unique()->count();
  101. });
  102. return [
  103. 'metadata' => [
  104. 'nodeName' => config('app.name'),
  105. 'software' => [
  106. 'homepage' => 'https://pixelfed.org',
  107. 'repo' => 'https://github.com/pixelfed/pixelfed',
  108. ],
  109. ],
  110. 'protocols' => [
  111. 'activitypub',
  112. ],
  113. 'services' => [
  114. 'inbound' => [],
  115. 'outbound' => [],
  116. ],
  117. 'software' => [
  118. 'name' => 'pixelfed',
  119. 'version' => config('pixelfed.version'),
  120. ],
  121. 'usage' => [
  122. 'localPosts' => \App\Status::whereLocal(true)->whereHas('media')->count(),
  123. 'localComments' => \App\Status::whereLocal(true)->whereNotNull('in_reply_to_id')->count(),
  124. 'users' => [
  125. 'total' => \App\Profile::whereNull('status')->whereNull('domain')->count(),
  126. 'activeHalfyear' => $activeHalfYear,
  127. 'activeMonth' => $activeMonth,
  128. ],
  129. ],
  130. 'version' => '2.0',
  131. ];
  132. });
  133. $res['openRegistrations'] = config('pixelfed.open_registration');
  134. return response()->json($res, 200, [
  135. 'Access-Control-Allow-Origin' => '*'
  136. ]);
  137. }
  138. public function webfinger(Request $request)
  139. {
  140. abort_if(!config('federation.webfinger.enabled'), 404);
  141. $this->validate($request, ['resource'=>'required|string|min:3|max:255']);
  142. $resource = $request->input('resource');
  143. $hash = hash('sha256', $resource);
  144. $parsed = Nickname::normalizeProfileUrl($resource);
  145. $username = $parsed['username'];
  146. $profile = Profile::whereUsername($username)->firstOrFail();
  147. if($profile->status != null) {
  148. return ProfileController::accountCheck($profile);
  149. }
  150. $webfinger = (new Webfinger($profile))->generate();
  151. return response()->json($webfinger, 200, [], JSON_PRETTY_PRINT);
  152. }
  153. public function hostMeta(Request $request)
  154. {
  155. abort_if(!config('federation.webfinger.enabled'), 404);
  156. $path = route('well-known.webfinger');
  157. $xml = '<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><Link rel="lrdd" type="application/xrd+xml" template="'.$path.'?resource={uri}"/></XRD>';
  158. return response($xml)->header('Content-Type', 'application/xrd+xml');
  159. }
  160. public function userOutbox(Request $request, $username)
  161. {
  162. abort_if(!config('federation.activitypub.enabled'), 404);
  163. abort_if(!config('federation.activitypub.outbox'), 404);
  164. $profile = Profile::whereNull('remote_url')->whereUsername($username)->firstOrFail();
  165. if($profile->status != null) {
  166. return ProfileController::accountCheck($profile);
  167. }
  168. if($profile->is_private) {
  169. return response()->json(['error'=>'403', 'msg' => 'private profile'], 403);
  170. }
  171. $timeline = $profile->statuses()->whereVisibility('public')->orderBy('created_at', 'desc')->paginate(10);
  172. $fractal = new Fractal\Manager();
  173. $resource = new Fractal\Resource\Item($profile, new ProfileOutbox());
  174. $res = $fractal->createData($resource)->toArray();
  175. return response(json_encode($res['data']))->header('Content-Type', 'application/activity+json');
  176. }
  177. public function userInbox(Request $request, $username)
  178. {
  179. abort_if(!config('federation.activitypub.enabled'), 404);
  180. abort_if(!config('federation.activitypub.inbox'), 404);
  181. // $headers = $request->headers->all();
  182. // $payload = $request->getContent();
  183. // InboxValidator::dispatch($username, $headers, $payload);
  184. $profile = Profile::whereNull('domain')->whereUsername($username)->firstOrFail();
  185. if($profile->status != null) {
  186. return ProfileController::accountCheck($profile);
  187. }
  188. $body = $request->getContent();
  189. $bodyDecoded = json_decode($body, true, 8);
  190. if($this->verifySignature($request, $profile) == true) {
  191. InboxWorker::dispatch($request->headers->all(), $profile, $bodyDecoded);
  192. } else if($this->blindKeyRotation($request, $profile) == true) {
  193. InboxWorker::dispatch($request->headers->all(), $profile, $bodyDecoded);
  194. } else {
  195. abort(400, 'Bad Signature');
  196. }
  197. return;
  198. }
  199. protected function verifySignature(Request $request, Profile $profile)
  200. {
  201. $body = $request->getContent();
  202. $bodyDecoded = json_decode($body, true, 8);
  203. $signature = $request->header('signature');
  204. $date = $request->header('date');
  205. if(!$signature) {
  206. abort(400, 'Missing signature header');
  207. }
  208. if(!$date) {
  209. abort(400, 'Missing date header');
  210. }
  211. if(!now()->parse($date)->gt(now()->subDays(1)) || !now()->parse($date)->lt(now()->addDays(1))) {
  212. abort(400, 'Invalid date');
  213. }
  214. $signatureData = HttpSignature::parseSignatureHeader($signature);
  215. $keyId = Helpers::validateUrl($signatureData['keyId']);
  216. $id = Helpers::validateUrl($bodyDecoded['id']);
  217. $keyDomain = parse_url($keyId, PHP_URL_HOST);
  218. $idDomain = parse_url($id, PHP_URL_HOST);
  219. if(isset($bodyDecoded['object'])
  220. && is_array($bodyDecoded['object'])
  221. && isset($bodyDecoded['object']['attributedTo'])
  222. ) {
  223. if(parse_url($bodyDecoded['object']['attributedTo'], PHP_URL_HOST) !== $keyDomain) {
  224. abort(400, 'Invalid request');
  225. }
  226. }
  227. if(!$keyDomain || !$idDomain || $keyDomain !== $idDomain) {
  228. abort(400, 'Invalid request');
  229. }
  230. $actor = Profile::whereKeyId($keyId)->first();
  231. if(!$actor) {
  232. $actor = Helpers::profileFirstOrNew($bodyDecoded['actor']);
  233. }
  234. if(!$actor) {
  235. return false;
  236. }
  237. $pkey = openssl_pkey_get_public($actor->public_key);
  238. $inboxPath = "/users/{$profile->username}/inbox";
  239. list($verified, $headers) = HTTPSignature::verify($pkey, $signatureData, $request->headers->all(), $inboxPath, $body);
  240. if($verified == 1) {
  241. return true;
  242. } else {
  243. return false;
  244. }
  245. }
  246. protected function blindKeyRotation(Request $request, Profile $profile)
  247. {
  248. $signature = $request->header('signature');
  249. $date = $request->header('date');
  250. if(!$signature) {
  251. abort(400, 'Missing signature header');
  252. }
  253. if(!$date) {
  254. abort(400, 'Missing date header');
  255. }
  256. if(!now()->parse($date)->gt(now()->subDays(1)) || !now()->parse($date)->lt(now()->addDays(1))) {
  257. abort(400, 'Invalid date');
  258. }
  259. $signatureData = HttpSignature::parseSignatureHeader($signature);
  260. $keyId = Helpers::validateUrl($signatureData['keyId']);
  261. $actor = Profile::whereKeyId($keyId)->whereNotNull('remote_url')->firstOrFail();
  262. $res = Zttp::timeout(5)->withHeaders([
  263. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  264. 'User-Agent' => 'PixelfedBot v0.1 - https://pixelfed.org',
  265. ])->get($actor->remote_url);
  266. $res = json_decode($res->body(), true, 8);
  267. if($res['publicKey']['id'] !== $actor->key_id) {
  268. return false;
  269. }
  270. $actor->public_key = $res['publicKey']['publicKeyPem'];
  271. $actor->save();
  272. return $this->verifySignature($request, $profile);
  273. }
  274. public function userFollowing(Request $request, $username)
  275. {
  276. abort_if(!config('federation.activitypub.enabled'), 404);
  277. $profile = Profile::whereNull('remote_url')
  278. ->whereUsername($username)
  279. ->whereIsPrivate(false)
  280. ->firstOrFail();
  281. return [];
  282. if($profile->status != null) {
  283. return [];
  284. }
  285. $obj = [
  286. '@context' => 'https://www.w3.org/ns/activitystreams',
  287. 'id' => $request->getUri(),
  288. 'type' => 'OrderedCollectionPage',
  289. 'totalItems' => $profile->following()->count(),
  290. 'orderedItems' => $profile->following->map(function($f) {
  291. return $f->permalink();
  292. })
  293. ];
  294. return response()->json($obj);
  295. }
  296. public function userFollowers(Request $request, $username)
  297. {
  298. abort_if(!config('federation.activitypub.enabled'), 404);
  299. $profile = Profile::whereNull('remote_url')
  300. ->whereUsername($username)
  301. ->whereIsPrivate(false)
  302. ->firstOrFail();
  303. return [];
  304. if($profile->status != null) {
  305. return [];
  306. }
  307. $obj = [
  308. '@context' => 'https://www.w3.org/ns/activitystreams',
  309. 'id' => $request->getUri(),
  310. 'type' => 'OrderedCollectionPage',
  311. 'totalItems' => $profile->followers()->count(),
  312. 'orderedItems' => $profile->followers->map(function($f) {
  313. return $f->permalink();
  314. })
  315. ];
  316. return response()->json($obj);
  317. }
  318. }