1
0

FederationController.php 12 KB

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