FederationController.php 13 KB

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