FederationController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. $date = $request->header('date');
  176. if(!$signature) {
  177. abort(400, 'Missing signature header');
  178. }
  179. if(!$date) {
  180. abort(400, 'Missing date header');
  181. }
  182. if(!now()->parse($date)->gt(now()->subDays(1)) || !now()->parse($date)->lt(now()->addDays(1))) {
  183. abort(400, 'Invalid date');
  184. }
  185. $signatureData = HttpSignature::parseSignatureHeader($signature);
  186. $keyId = Helpers::validateUrl($signatureData['keyId']);
  187. $id = Helpers::validateUrl($bodyDecoded['id']);
  188. $keyDomain = parse_url($keyId, PHP_URL_HOST);
  189. $idDomain = parse_url($id, PHP_URL_HOST);
  190. if(isset($bodyDecoded['object'])
  191. && is_array($bodyDecoded['object'])
  192. && isset($bodyDecoded['object']['attributedTo'])
  193. ) {
  194. if(parse_url($bodyDecoded['object']['attributedTo'], PHP_URL_HOST) !== $keyDomain) {
  195. abort(400, 'Invalid request');
  196. }
  197. }
  198. if(!$keyDomain || !$idDomain || $keyDomain !== $idDomain) {
  199. abort(400, 'Invalid request');
  200. }
  201. $actor = Profile::whereKeyId($keyId)->first();
  202. if(!$actor) {
  203. $actor = Helpers::profileFirstOrNew($bodyDecoded['actor']);
  204. }
  205. $pkey = openssl_pkey_get_public($actor->public_key);
  206. $inboxPath = "/users/{$profile->username}/inbox";
  207. list($verified, $headers) = HTTPSignature::verify($pkey, $signatureData, $request->headers->all(), $inboxPath, $body);
  208. if($verified == 1) {
  209. return true;
  210. } else {
  211. return false;
  212. }
  213. }
  214. protected function blindKeyRotation(Request $request, Profile $profile)
  215. {
  216. $signature = $request->header('signature');
  217. if(!$signature) {
  218. abort(400, 'Missing signature header');
  219. }
  220. $signatureData = HttpSignature::parseSignatureHeader($signature);
  221. $keyId = Helpers::validateUrl($signatureData['keyId']);
  222. $actor = Profile::whereKeyId($keyId)->whereNotNull('remote_url')->firstOrFail();
  223. $res = Zttp::timeout(5)->withHeaders([
  224. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  225. 'User-Agent' => 'PixelFedBot v0.1 - https://pixelfed.org',
  226. ])->get($actor->remote_url);
  227. $res = json_decode($res->body(), true, 8);
  228. if($res['publicKey']['id'] !== $actor->key_id) {
  229. return false;
  230. }
  231. $actor->public_key = $res['publicKey']['publicKeyPem'];
  232. $actor->save();
  233. return $this->verifySignature($request, $profile);
  234. }
  235. public function userFollowing(Request $request, $username)
  236. {
  237. if (config('pixelfed.activitypub_enabled') == false) {
  238. abort(403);
  239. }
  240. $profile = Profile::whereNull('remote_url')
  241. ->whereUsername($username)
  242. ->whereIsPrivate(false)
  243. ->firstOrFail();
  244. if($profile->status != null) {
  245. return ProfileController::accountCheck($profile);
  246. }
  247. $obj = [
  248. '@context' => 'https://www.w3.org/ns/activitystreams',
  249. 'id' => $request->getUri(),
  250. 'type' => 'OrderedCollectionPage',
  251. 'totalItems' => $profile->following()->count(),
  252. 'orderedItems' => $profile->following->map(function($f) {
  253. return $f->permalink();
  254. })
  255. ];
  256. return response()->json($obj);
  257. }
  258. public function userFollowers(Request $request, $username)
  259. {
  260. if (config('pixelfed.activitypub_enabled') == false) {
  261. abort(403);
  262. }
  263. $profile = Profile::whereNull('remote_url')
  264. ->whereUsername($username)
  265. ->whereIsPrivate(false)
  266. ->firstOrFail();
  267. if($profile->status != null) {
  268. return ProfileController::accountCheck($profile);
  269. }
  270. $obj = [
  271. '@context' => 'https://www.w3.org/ns/activitystreams',
  272. 'id' => $request->getUri(),
  273. 'type' => 'OrderedCollectionPage',
  274. 'totalItems' => $profile->followers()->count(),
  275. 'orderedItems' => $profile->followers->map(function($f) {
  276. return $f->permalink();
  277. })
  278. ];
  279. return response()->json($obj);
  280. }
  281. }