FederationController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. if (!Auth::check()) {
  27. return abort(403);
  28. }
  29. }
  30. public function authorizeFollow(Request $request)
  31. {
  32. $this->authCheck();
  33. $this->validate($request, [
  34. 'acct' => 'required|string|min:3|max:255',
  35. ]);
  36. $acct = $request->input('acct');
  37. $nickname = Nickname::normalizeProfileUrl($acct);
  38. return view('federation.authorizefollow', compact('acct', 'nickname'));
  39. }
  40. public function remoteFollow()
  41. {
  42. $this->authCheck();
  43. return view('federation.remotefollow');
  44. }
  45. public function remoteFollowStore(Request $request)
  46. {
  47. $this->authCheck();
  48. $this->validate($request, [
  49. 'url' => 'required|string',
  50. ]);
  51. if (config('pixelfed.remote_follow_enabled') !== true) {
  52. abort(403);
  53. }
  54. $follower = Auth::user()->profile;
  55. $url = $request->input('url');
  56. $url = Helpers::validateUrl($url);
  57. if(!$url) {
  58. return;
  59. }
  60. RemoteFollowPipeline::dispatch($follower, $url);
  61. return response(['success' => true, 'follower' => $follower]);
  62. }
  63. public function nodeinfoWellKnown()
  64. {
  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. $res = Cache::remember('api:nodeinfo', now()->addMinutes(15), function () {
  78. $activeHalfYear = Cache::remember('api:nodeinfo:ahy', now()->addHours(12), function() {
  79. $count = collect([]);
  80. // $likes = Like::select('profile_id')->where('created_at', '>', now()->subMonths(6)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  81. // $count = $count->merge($likes);
  82. $statuses = Status::select('profile_id')->whereLocal(true)->where('created_at', '>', now()->subMonths(6)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  83. $count = $count->merge($statuses);
  84. $profiles = Profile::select('id')->whereNull('domain')->where('created_at', '>', now()->subMonths(6)->toDateTimeString())->groupBy('id')->pluck('id')->toArray();
  85. $count = $count->merge($profiles);
  86. return $count->unique()->count();
  87. });
  88. $activeMonth = Cache::remember('api:nodeinfo:am', now()->addHours(12), function() {
  89. $count = collect([]);
  90. // $likes = Like::select('profile_id')->where('created_at', '>', now()->subMonths(1)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  91. // $count = $count->merge($likes);
  92. $statuses = Status::select('profile_id')->whereLocal(true)->where('created_at', '>', now()->subMonths(1)->toDateTimeString())->groupBy('profile_id')->pluck('profile_id')->toArray();
  93. $count = $count->merge($statuses);
  94. $profiles = Profile::select('id')->whereNull('domain')->where('created_at', '>', now()->subMonths(1)->toDateTimeString())->groupBy('id')->pluck('id')->toArray();
  95. $count = $count->merge($profiles);
  96. return $count->unique()->count();
  97. });
  98. return [
  99. 'metadata' => [
  100. 'nodeName' => config('app.name'),
  101. 'software' => [
  102. 'homepage' => 'https://pixelfed.org',
  103. 'repo' => 'https://github.com/pixelfed/pixelfed',
  104. ],
  105. ],
  106. 'protocols' => [
  107. 'activitypub',
  108. ],
  109. 'services' => [
  110. 'inbound' => [],
  111. 'outbound' => [],
  112. ],
  113. 'software' => [
  114. 'name' => 'pixelfed',
  115. 'version' => config('pixelfed.version'),
  116. ],
  117. 'usage' => [
  118. 'localPosts' => \App\Status::whereLocal(true)->whereHas('media')->count(),
  119. 'localComments' => \App\Status::whereLocal(true)->whereNotNull('in_reply_to_id')->count(),
  120. 'users' => [
  121. 'total' => \App\Profile::whereNull('status')->whereNull('domain')->count(),
  122. 'activeHalfyear' => $activeHalfYear,
  123. 'activeMonth' => $activeMonth,
  124. ],
  125. ],
  126. 'version' => '2.0',
  127. ];
  128. });
  129. $res['openRegistrations'] = config('pixelfed.open_registration');
  130. return response()->json($res, 200, [
  131. 'Access-Control-Allow-Origin' => '*'
  132. ]);
  133. }
  134. public function webfinger(Request $request)
  135. {
  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. $path = route('well-known.webfinger');
  151. $xml = <<<XML
  152. <?xml version="1.0" encoding="UTF-8"?>
  153. <XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
  154. <Link rel="lrdd" type="application/xrd+xml" template="{$path}?resource={uri}"/>
  155. </XRD>
  156. XML;
  157. return response($xml)->header('Content-Type', 'application/xrd+xml');
  158. }
  159. public function userOutbox(Request $request, $username)
  160. {
  161. if (config('pixelfed.activitypub_enabled') == false) {
  162. abort(403);
  163. }
  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. if (config('pixelfed.activitypub_enabled') == false) {
  180. abort(403);
  181. }
  182. $profile = Profile::whereNull('domain')->whereUsername($username)->firstOrFail();
  183. if($profile->status != null) {
  184. return ProfileController::accountCheck($profile);
  185. }
  186. $body = $request->getContent();
  187. $bodyDecoded = json_decode($body, true, 8);
  188. if($this->verifySignature($request, $profile) == true) {
  189. InboxWorker::dispatch($request->headers->all(), $profile, $bodyDecoded);
  190. } else if($this->blindKeyRotation($request, $profile) == true) {
  191. InboxWorker::dispatch($request->headers->all(), $profile, $bodyDecoded);
  192. } else {
  193. abort(400, 'Bad Signature');
  194. }
  195. return;
  196. }
  197. protected function verifySignature(Request $request, Profile $profile)
  198. {
  199. $body = $request->getContent();
  200. $bodyDecoded = json_decode($body, true, 8);
  201. $signature = $request->header('signature');
  202. $date = $request->header('date');
  203. if(!$signature) {
  204. abort(400, 'Missing signature header');
  205. }
  206. if(!$date) {
  207. abort(400, 'Missing date header');
  208. }
  209. if(!now()->parse($date)->gt(now()->subDays(1)) || !now()->parse($date)->lt(now()->addDays(1))) {
  210. abort(400, 'Invalid date');
  211. }
  212. $signatureData = HttpSignature::parseSignatureHeader($signature);
  213. $keyId = Helpers::validateUrl($signatureData['keyId']);
  214. $id = Helpers::validateUrl($bodyDecoded['id']);
  215. $keyDomain = parse_url($keyId, PHP_URL_HOST);
  216. $idDomain = parse_url($id, PHP_URL_HOST);
  217. if(isset($bodyDecoded['object'])
  218. && is_array($bodyDecoded['object'])
  219. && isset($bodyDecoded['object']['attributedTo'])
  220. ) {
  221. if(parse_url($bodyDecoded['object']['attributedTo'], PHP_URL_HOST) !== $keyDomain) {
  222. abort(400, 'Invalid request');
  223. }
  224. }
  225. if(!$keyDomain || !$idDomain || $keyDomain !== $idDomain) {
  226. abort(400, 'Invalid request');
  227. }
  228. $actor = Profile::whereKeyId($keyId)->first();
  229. if(!$actor) {
  230. $actor = Helpers::profileFirstOrNew($bodyDecoded['actor']);
  231. }
  232. if(!$actor) {
  233. return false;
  234. }
  235. $pkey = openssl_pkey_get_public($actor->public_key);
  236. $inboxPath = "/users/{$profile->username}/inbox";
  237. list($verified, $headers) = HTTPSignature::verify($pkey, $signatureData, $request->headers->all(), $inboxPath, $body);
  238. if($verified == 1) {
  239. return true;
  240. } else {
  241. return false;
  242. }
  243. }
  244. protected function blindKeyRotation(Request $request, Profile $profile)
  245. {
  246. $signature = $request->header('signature');
  247. $date = $request->header('date');
  248. if(!$signature) {
  249. abort(400, 'Missing signature header');
  250. }
  251. if(!$date) {
  252. abort(400, 'Missing date header');
  253. }
  254. if(!now()->parse($date)->gt(now()->subDays(1)) || !now()->parse($date)->lt(now()->addDays(1))) {
  255. abort(400, 'Invalid date');
  256. }
  257. $signatureData = HttpSignature::parseSignatureHeader($signature);
  258. $keyId = Helpers::validateUrl($signatureData['keyId']);
  259. $actor = Profile::whereKeyId($keyId)->whereNotNull('remote_url')->firstOrFail();
  260. $res = Zttp::timeout(5)->withHeaders([
  261. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  262. 'User-Agent' => 'PixelFedBot v0.1 - https://pixelfed.org',
  263. ])->get($actor->remote_url);
  264. $res = json_decode($res->body(), true, 8);
  265. if($res['publicKey']['id'] !== $actor->key_id) {
  266. return false;
  267. }
  268. $actor->public_key = $res['publicKey']['publicKeyPem'];
  269. $actor->save();
  270. return $this->verifySignature($request, $profile);
  271. }
  272. public function userFollowing(Request $request, $username)
  273. {
  274. if (config('pixelfed.activitypub_enabled') == false) {
  275. abort(403);
  276. }
  277. $profile = Profile::whereNull('remote_url')
  278. ->whereUsername($username)
  279. ->whereIsPrivate(false)
  280. ->firstOrFail();
  281. if($profile->status != null) {
  282. return ProfileController::accountCheck($profile);
  283. }
  284. $obj = [
  285. '@context' => 'https://www.w3.org/ns/activitystreams',
  286. 'id' => $request->getUri(),
  287. 'type' => 'OrderedCollectionPage',
  288. 'totalItems' => $profile->following()->count(),
  289. 'orderedItems' => $profile->following->map(function($f) {
  290. return $f->permalink();
  291. })
  292. ];
  293. return response()->json($obj);
  294. }
  295. public function userFollowers(Request $request, $username)
  296. {
  297. if (config('pixelfed.activitypub_enabled') == false) {
  298. abort(403);
  299. }
  300. $profile = Profile::whereNull('remote_url')
  301. ->whereUsername($username)
  302. ->whereIsPrivate(false)
  303. ->firstOrFail();
  304. if($profile->status != null) {
  305. return ProfileController::accountCheck($profile);
  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. }