1
0

FederationController.php 13 KB

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