FederationController.php 10 KB

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