FederationController.php 13 KB

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