FederationController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Jobs\InboxPipeline\InboxWorker;
  4. use App\Jobs\RemoteFollowPipeline\RemoteFollowPipeline;
  5. use App\Profile;
  6. use App\Transformer\ActivityPub\ProfileOutbox;
  7. use App\Util\Lexer\Nickname;
  8. use App\Util\Webfinger\Webfinger;
  9. use Auth;
  10. use Cache;
  11. use Carbon\Carbon;
  12. use Illuminate\Http\Request;
  13. use League\Fractal;
  14. use App\Util\ActivityPub\Helpers;
  15. use App\Util\ActivityPub\HttpSignature;
  16. class FederationController extends Controller
  17. {
  18. public function authCheck()
  19. {
  20. if (!Auth::check()) {
  21. return abort(403);
  22. }
  23. }
  24. public function authorizeFollow(Request $request)
  25. {
  26. $this->authCheck();
  27. $this->validate($request, [
  28. 'acct' => 'required|string|min:3|max:255',
  29. ]);
  30. $acct = $request->input('acct');
  31. $nickname = Nickname::normalizeProfileUrl($acct);
  32. return view('federation.authorizefollow', compact('acct', 'nickname'));
  33. }
  34. public function remoteFollow()
  35. {
  36. $this->authCheck();
  37. return view('federation.remotefollow');
  38. }
  39. public function remoteFollowStore(Request $request)
  40. {
  41. $this->authCheck();
  42. $this->validate($request, [
  43. 'url' => 'required|string',
  44. ]);
  45. if (config('pixelfed.remote_follow_enabled') !== true) {
  46. abort(403);
  47. }
  48. $follower = Auth::user()->profile;
  49. $url = $request->input('url');
  50. RemoteFollowPipeline::dispatch($follower, $url);
  51. return redirect()->back();
  52. }
  53. public function nodeinfoWellKnown()
  54. {
  55. $res = [
  56. 'links' => [
  57. [
  58. 'href' => config('pixelfed.nodeinfo.url'),
  59. 'rel' => 'http://nodeinfo.diaspora.software/ns/schema/2.0',
  60. ],
  61. ],
  62. ];
  63. return response()->json($res);
  64. }
  65. public function nodeinfo()
  66. {
  67. $res = Cache::remember('api:nodeinfo', 60, function () {
  68. return [
  69. 'metadata' => [
  70. 'nodeName' => config('app.name'),
  71. 'software' => [
  72. 'homepage' => 'https://pixelfed.org',
  73. 'github' => 'https://github.com/pixelfed',
  74. 'follow' => 'https://mastodon.social/@pixelfed',
  75. ],
  76. ],
  77. 'openRegistrations' => config('pixelfed.open_registration'),
  78. 'protocols' => [
  79. 'activitypub',
  80. ],
  81. 'services' => [
  82. 'inbound' => [],
  83. 'outbound' => [],
  84. ],
  85. 'software' => [
  86. 'name' => 'pixelfed',
  87. 'version' => config('pixelfed.version'),
  88. ],
  89. 'usage' => [
  90. 'localPosts' => \App\Status::whereLocal(true)->whereHas('media')->count(),
  91. 'localComments' => \App\Status::whereLocal(true)->whereNotNull('in_reply_to_id')->count(),
  92. 'users' => [
  93. 'total' => \App\User::count(),
  94. 'activeHalfyear' => \App\AccountLog::select('user_id')->whereAction('auth.login')->where('updated_at', '>',Carbon::now()->subMonths(6)->toDateTimeString())->groupBy('user_id')->get()->count(),
  95. 'activeMonth' => \App\AccountLog::select('user_id')->whereAction('auth.login')->where('updated_at', '>',Carbon::now()->subMonths(1)->toDateTimeString())->groupBy('user_id')->get()->count(),
  96. ],
  97. ],
  98. 'version' => '2.0',
  99. ];
  100. });
  101. return response()->json($res, 200, [
  102. 'Access-Control-Allow-Origin' => '*'
  103. ]);
  104. }
  105. public function webfinger(Request $request)
  106. {
  107. $this->validate($request, ['resource'=>'required|string|min:3|max:255']);
  108. $resource = $request->input('resource');
  109. $hash = hash('sha256', $resource);
  110. $parsed = Nickname::normalizeProfileUrl($resource);
  111. $username = $parsed['username'];
  112. $profile = Profile::whereUsername($username)->firstOrFail();
  113. if($profile->status != null) {
  114. return ProfileController::accountCheck($profile);
  115. }
  116. $webfinger = (new Webfinger($profile))->generate();
  117. return response()->json($webfinger, 200, [], JSON_PRETTY_PRINT);
  118. }
  119. public function hostMeta(Request $request)
  120. {
  121. $path = route('well-known.webfinger');
  122. $xml = <<<XML
  123. <?xml version="1.0" encoding="UTF-8"?>
  124. <XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
  125. <Link rel="lrdd" type="application/xrd+xml" template="{$path}?resource={uri}"/>
  126. </XRD>
  127. XML;
  128. return response($xml)->header('Content-Type', 'application/xrd+xml');
  129. }
  130. public function userOutbox(Request $request, $username)
  131. {
  132. if (config('pixelfed.activitypub_enabled') == false) {
  133. abort(403);
  134. }
  135. $profile = Profile::whereNull('remote_url')->whereUsername($username)->firstOrFail();
  136. if($profile->status != null) {
  137. return ProfileController::accountCheck($profile);
  138. }
  139. if($profile->is_private) {
  140. return response()->json(['error'=>'403', 'msg' => 'private profile'], 403);
  141. }
  142. $timeline = $profile->statuses()->whereVisibility('public')->orderBy('created_at', 'desc')->paginate(10);
  143. $fractal = new Fractal\Manager();
  144. $resource = new Fractal\Resource\Item($profile, new ProfileOutbox());
  145. $res = $fractal->createData($resource)->toArray();
  146. return response(json_encode($res['data']))->header('Content-Type', 'application/activity+json');
  147. }
  148. public function userInbox(Request $request, $username)
  149. {
  150. if (config('pixelfed.activitypub_enabled') == false) {
  151. abort(403);
  152. }
  153. $profile = Profile::whereNull('domain')->whereUsername($username)->firstOrFail();
  154. if($profile->status != null) {
  155. return ProfileController::accountCheck($profile);
  156. }
  157. $body = $request->getContent();
  158. $bodyDecoded = json_decode($body, true, 8);
  159. if($this->verifySignature($request, $profile) == true) {
  160. InboxWorker::dispatch($request->headers->all(), $profile, $bodyDecoded);
  161. } else if($this->blindKeyRotation($request, $profile) == true) {
  162. InboxWorker::dispatch($request->headers->all(), $profile, $bodyDecoded);
  163. } else {
  164. abort(400, 'Bad Signature');
  165. }
  166. return;
  167. }
  168. protected function verifySignature(Request $request, Profile $profile)
  169. {
  170. $body = $request->getContent();
  171. $bodyDecoded = json_decode($body, true, 8);
  172. $signature = $request->header('signature');
  173. if(!$signature) {
  174. abort(400, 'Missing signature header');
  175. }
  176. $signatureData = HttpSignature::parseSignatureHeader($signature);
  177. $keyId = Helpers::validateUrl($signatureData['keyId']);
  178. $id = Helpers::validateUrl($bodyDecoded['id']);
  179. $keyDomain = parse_url($keyId, PHP_URL_HOST);
  180. $idDomain = parse_url($id, PHP_URL_HOST);
  181. if(isset($bodyDecoded['object'])
  182. && is_array($bodyDecoded['object'])
  183. && isset($bodyDecoded['object']['attributedTo'])
  184. ) {
  185. if(parse_url($bodyDecoded['object']['attributedTo'], PHP_URL_HOST) !== $keyDomain) {
  186. abort(400, 'Invalid request');
  187. }
  188. }
  189. if(!$keyDomain || !$idDomain || $keyDomain !== $idDomain) {
  190. abort(400, 'Invalid request');
  191. }
  192. $actor = Profile::whereKeyId($keyId)->first();
  193. if(!$actor) {
  194. $actor = Helpers::profileFirstOrNew($bodyDecoded['actor']);
  195. }
  196. $pkey = openssl_pkey_get_public($actor->public_key);
  197. $inboxPath = "/users/{$profile->username}/inbox";
  198. list($verified, $headers) = HTTPSignature::verify($pkey, $signatureData, $request->headers->all(), $inboxPath, $body);
  199. if($verified == 1) {
  200. return true;
  201. } else {
  202. return false;
  203. }
  204. }
  205. protected function blindKeyRotation(Request $request, Profile $profile)
  206. {
  207. $signature = $request->header('signature');
  208. if(!$signature) {
  209. abort(400, 'Missing signature header');
  210. }
  211. $signatureData = HttpSignature::parseSignatureHeader($signature);
  212. $keyId = Helpers::validateUrl($signatureData['keyId']);
  213. $actor = Profile::whereKeyId($keyId)->first();
  214. $res = Zttp::timeout(5)->withHeaders([
  215. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  216. 'User-Agent' => 'PixelFedBot v0.1 - https://pixelfed.org',
  217. ])->get($actor->remote_url);
  218. $res = json_decode($res->body(), true, 8);
  219. if($res['publicKey']['id'] !== $actor->key_id) {
  220. return false;
  221. }
  222. $actor->public_key = $res['publicKey']['publicKeyPem'];
  223. $actor->save();
  224. return $this->verifySignature($request, $profile);
  225. }
  226. public function userFollowing(Request $request, $username)
  227. {
  228. if (config('pixelfed.activitypub_enabled') == false) {
  229. abort(403);
  230. }
  231. $profile = Profile::whereNull('remote_url')
  232. ->whereUsername($username)
  233. ->whereIsPrivate(false)
  234. ->firstOrFail();
  235. if($profile->status != null) {
  236. return ProfileController::accountCheck($profile);
  237. }
  238. $obj = [
  239. '@context' => 'https://www.w3.org/ns/activitystreams',
  240. 'id' => $request->getUri(),
  241. 'type' => 'OrderedCollectionPage',
  242. 'totalItems' => $profile->following()->count(),
  243. 'orderedItems' => $profile->following->map(function($f) {
  244. return $f->permalink();
  245. })
  246. ];
  247. return response()->json($obj);
  248. }
  249. public function userFollowers(Request $request, $username)
  250. {
  251. if (config('pixelfed.activitypub_enabled') == false) {
  252. abort(403);
  253. }
  254. $profile = Profile::whereNull('remote_url')
  255. ->whereUsername($username)
  256. ->whereIsPrivate(false)
  257. ->firstOrFail();
  258. if($profile->status != null) {
  259. return ProfileController::accountCheck($profile);
  260. }
  261. $obj = [
  262. '@context' => 'https://www.w3.org/ns/activitystreams',
  263. 'id' => $request->getUri(),
  264. 'type' => 'OrderedCollectionPage',
  265. 'totalItems' => $profile->followers()->count(),
  266. 'orderedItems' => $profile->followers->map(function($f) {
  267. return $f->permalink();
  268. })
  269. ];
  270. return response()->json($obj);
  271. }
  272. }