FederationController.php 13 KB

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