FederationController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 response(['success' => true, 'follower' => $follower]);
  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. 'protocols' => [
  113. 'activitypub',
  114. ],
  115. 'services' => [
  116. 'inbound' => [],
  117. 'outbound' => [],
  118. ],
  119. 'software' => [
  120. 'name' => 'pixelfed',
  121. 'version' => config('pixelfed.version'),
  122. ],
  123. 'usage' => [
  124. 'localPosts' => \App\Status::whereLocal(true)->whereHas('media')->count(),
  125. 'localComments' => \App\Status::whereLocal(true)->whereNotNull('in_reply_to_id')->count(),
  126. 'users' => [
  127. 'total' => \App\Profile::whereNull('status')->whereNull('domain')->count(),
  128. 'activeHalfyear' => $activeHalfYear,
  129. 'activeMonth' => $activeMonth,
  130. ],
  131. ],
  132. 'version' => '2.0',
  133. ];
  134. });
  135. $res['openRegistrations'] = config('pixelfed.open_registration');
  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. if(!$actor) {
  239. return false;
  240. }
  241. $pkey = openssl_pkey_get_public($actor->public_key);
  242. $inboxPath = "/users/{$profile->username}/inbox";
  243. list($verified, $headers) = HTTPSignature::verify($pkey, $signatureData, $request->headers->all(), $inboxPath, $body);
  244. if($verified == 1) {
  245. return true;
  246. } else {
  247. return false;
  248. }
  249. }
  250. protected function blindKeyRotation(Request $request, Profile $profile)
  251. {
  252. $signature = $request->header('signature');
  253. $date = $request->header('date');
  254. if(!$signature) {
  255. abort(400, 'Missing signature header');
  256. }
  257. if(!$date) {
  258. abort(400, 'Missing date header');
  259. }
  260. if(!now()->parse($date)->gt(now()->subDays(1)) || !now()->parse($date)->lt(now()->addDays(1))) {
  261. abort(400, 'Invalid date');
  262. }
  263. $signatureData = HttpSignature::parseSignatureHeader($signature);
  264. $keyId = Helpers::validateUrl($signatureData['keyId']);
  265. $actor = Profile::whereKeyId($keyId)->whereNotNull('remote_url')->firstOrFail();
  266. $res = Zttp::timeout(5)->withHeaders([
  267. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  268. 'User-Agent' => 'PixelFedBot v0.1 - https://pixelfed.org',
  269. ])->get($actor->remote_url);
  270. $res = json_decode($res->body(), true, 8);
  271. if($res['publicKey']['id'] !== $actor->key_id) {
  272. return false;
  273. }
  274. $actor->public_key = $res['publicKey']['publicKeyPem'];
  275. $actor->save();
  276. return $this->verifySignature($request, $profile);
  277. }
  278. public function userFollowing(Request $request, $username)
  279. {
  280. if (config('pixelfed.activitypub_enabled') == false) {
  281. abort(403);
  282. }
  283. $profile = Profile::whereNull('remote_url')
  284. ->whereUsername($username)
  285. ->whereIsPrivate(false)
  286. ->firstOrFail();
  287. if($profile->status != null) {
  288. return ProfileController::accountCheck($profile);
  289. }
  290. $obj = [
  291. '@context' => 'https://www.w3.org/ns/activitystreams',
  292. 'id' => $request->getUri(),
  293. 'type' => 'OrderedCollectionPage',
  294. 'totalItems' => $profile->following()->count(),
  295. 'orderedItems' => $profile->following->map(function($f) {
  296. return $f->permalink();
  297. })
  298. ];
  299. return response()->json($obj);
  300. }
  301. public function userFollowers(Request $request, $username)
  302. {
  303. if (config('pixelfed.activitypub_enabled') == false) {
  304. abort(403);
  305. }
  306. $profile = Profile::whereNull('remote_url')
  307. ->whereUsername($username)
  308. ->whereIsPrivate(false)
  309. ->firstOrFail();
  310. if($profile->status != null) {
  311. return ProfileController::accountCheck($profile);
  312. }
  313. $obj = [
  314. '@context' => 'https://www.w3.org/ns/activitystreams',
  315. 'id' => $request->getUri(),
  316. 'type' => 'OrderedCollectionPage',
  317. 'totalItems' => $profile->followers()->count(),
  318. 'orderedItems' => $profile->followers->map(function($f) {
  319. return $f->permalink();
  320. })
  321. ];
  322. return response()->json($obj);
  323. }
  324. }