FederationController.php 13 KB

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