FederationController.php 13 KB

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