FederationController.php 11 KB

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