FreeNetwork.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // GNU social is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. namespace Component\FreeNetwork;
  20. use App\Core\DB\DB;
  21. use App\Core\Event;
  22. use App\Core\GSFile;
  23. use App\Core\HTTPClient;
  24. use function App\Core\I18n\_m;
  25. use App\Core\Log;
  26. use App\Core\Modules\Component;
  27. use App\Core\Router\RouteLoader;
  28. use App\Core\Router\Router;
  29. use App\Entity\Activity;
  30. use App\Entity\Actor;
  31. use App\Entity\LocalUser;
  32. use App\Entity\Note;
  33. use App\Util\Common;
  34. use App\Util\Exception\ClientException;
  35. use App\Util\Exception\NicknameEmptyException;
  36. use App\Util\Exception\NicknameException;
  37. use App\Util\Exception\NicknameInvalidException;
  38. use App\Util\Exception\NicknameNotAllowedException;
  39. use App\Util\Exception\NicknameTakenException;
  40. use App\Util\Exception\NicknameTooLongException;
  41. use App\Util\Exception\NoSuchActorException;
  42. use App\Util\Exception\ServerException;
  43. use App\Util\Nickname;
  44. use Component\FreeNetwork\Controller\Feeds;
  45. use Component\FreeNetwork\Controller\HostMeta;
  46. use Component\FreeNetwork\Controller\OwnerXrd;
  47. use Component\FreeNetwork\Controller\Webfinger;
  48. use Component\FreeNetwork\Util\Discovery;
  49. use Component\FreeNetwork\Util\WebfingerResource;
  50. use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceActor;
  51. use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceNote;
  52. use Exception;
  53. use Plugin\ActivityPub\Entity\ActivitypubActivity;
  54. use Plugin\ActivityPub\Util\TypeResponse;
  55. use const PREG_SET_ORDER;
  56. use Symfony\Component\HttpFoundation\JsonResponse;
  57. use Symfony\Component\HttpFoundation\Response;
  58. use XML_XRD;
  59. use XML_XRD_Element_Link;
  60. /**
  61. * Implements WebFinger (RFC7033) for GNU social, as well as Link-based Resource Descriptor Discovery based on RFC6415,
  62. * Web Host Metadata ('.well-known/host-meta') resource.
  63. *
  64. * @package GNUsocial
  65. *
  66. * @author Mikael Nordfeldth <mmn@hethane.se>
  67. * @author Diogo Peralta Cordeiro <mail@diogo.site>
  68. */
  69. class FreeNetwork extends Component
  70. {
  71. public const PLUGIN_VERSION = '0.1.0';
  72. public const OAUTH_ACCESS_TOKEN_REL = 'http://apinamespace.org/oauth/access_token';
  73. public const OAUTH_REQUEST_TOKEN_REL = 'http://apinamespace.org/oauth/request_token';
  74. public const OAUTH_AUTHORIZE_REL = 'http://apinamespace.org/oauth/authorize';
  75. public function onAddRoute(RouteLoader $m): bool
  76. {
  77. // Feeds
  78. $m->connect('feed_network', '/feed/network', [Feeds::class, 'network']);
  79. $m->connect('feed_clique', '/feed/clique', [Feeds::class, 'clique']);
  80. $m->connect('feed_federated', '/feed/federated', [Feeds::class, 'federated']);
  81. $m->connect('freenetwork_hostmeta', '.well-known/host-meta', [HostMeta::class, 'handle']);
  82. $m->connect(
  83. 'freenetwork_hostmeta_format',
  84. '.well-known/host-meta.:format',
  85. [HostMeta::class, 'handle'],
  86. ['format' => '(xml|json)'],
  87. );
  88. // the resource GET parameter can be anywhere, so don't mention it here
  89. $m->connect('freenetwork_webfinger', '.well-known/webfinger', [Webfinger::class, 'handle']);
  90. $m->connect(
  91. 'freenetwork_webfinger_format',
  92. '.well-known/webfinger.:format',
  93. [Webfinger::class, 'handle'],
  94. ['format' => '(xml|json)'],
  95. );
  96. $m->connect('freenetwork_ownerxrd', 'main/ownerxrd', [OwnerXrd::class, 'handle']);
  97. return Event::next;
  98. }
  99. public function onCreateDefaultFeeds(int $actor_id, LocalUser $user, int &$ordering)
  100. {
  101. DB::persist(\App\Entity\Feed::create(['actor_id' => $actor_id, 'url' => Router::url($route = 'feed_network'), 'route' => $route, 'title' => _m('Meteorites'), 'ordering' => $ordering++]));
  102. DB::persist(\App\Entity\Feed::create(['actor_id' => $actor_id, 'url' => Router::url($route = 'feed_clique'), 'route' => $route, 'title' => _m('Planetary System'), 'ordering' => $ordering++]));
  103. DB::persist(\App\Entity\Feed::create(['actor_id' => $actor_id, 'url' => Router::url($route = 'feed_federated'), 'route' => $route, 'title' => _m('Galaxy'), 'ordering' => $ordering++]));
  104. return Event::next;
  105. }
  106. public function onStartGetProfileAcctUri(Actor $profile, &$acct): bool
  107. {
  108. $wfr = new WebFingerResourceActor($profile);
  109. try {
  110. $acct = $wfr->reconstructAcct();
  111. } catch (Exception) {
  112. return Event::next;
  113. }
  114. return Event::stop;
  115. }
  116. /**
  117. * Last attempts getting a WebFingerResource object
  118. *
  119. * @param string $resource String that contains the requested URI
  120. * @param null|WebfingerResource $target WebFingerResource extended object goes here
  121. * @param array $args Array which may contains arguments such as 'rel' filtering values
  122. *
  123. * @throws NicknameEmptyException
  124. * @throws NicknameException
  125. * @throws NicknameInvalidException
  126. * @throws NicknameNotAllowedException
  127. * @throws NicknameTakenException
  128. * @throws NicknameTooLongException
  129. * @throws NoSuchActorException
  130. * @throws ServerException
  131. */
  132. public function onEndGetWebFingerResource(string $resource, ?WebfingerResource &$target = null, array $args = []): bool
  133. {
  134. // * Either we didn't find the profile, then we want to make
  135. // the $profile variable null for clarity.
  136. // * Or we did find it but for a possibly malicious remote
  137. // user who might've set their profile URL to a Note URL
  138. // which would've caused a sort of DoS unless we continue
  139. // our search here by discarding the remote profile.
  140. $profile = null;
  141. if (Discovery::isAcct($resource)) {
  142. $parts = explode('@', mb_substr(urldecode($resource), 5)); // 5 is strlen of 'acct:'
  143. if (\count($parts) === 2) {
  144. [$nick, $domain] = $parts;
  145. if ($domain !== $_ENV['SOCIAL_DOMAIN']) {
  146. throw new ServerException(_m('Remote profiles not supported via WebFinger yet.'));
  147. }
  148. $nick = Nickname::normalize(nickname: $nick, check_already_used: false, check_is_allowed: false);
  149. $freenetwork_actor = LocalUser::getByPK(['nickname' => $nick]);
  150. if (!($freenetwork_actor instanceof LocalUser)) {
  151. throw new NoSuchActorException($nick);
  152. }
  153. $profile = $freenetwork_actor->getActor();
  154. }
  155. } else {
  156. try {
  157. if (Common::isValidHttpUrl($resource)) {
  158. // This means $resource is a valid url
  159. $resource_parts = parse_url($resource);
  160. // TODO: Use URLMatcher
  161. if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  162. $str = $resource_parts['path'];
  163. // actor_view_nickname
  164. $renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m';
  165. // actor_view_id
  166. $reuri = '/\/actor\/(\d+)\/?/m';
  167. if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  168. $profile = LocalUser::getByPK(['nickname' => $matches[0][1]])->getActor();
  169. } elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  170. $profile = Actor::getById((int) $matches[0][1]);
  171. }
  172. }
  173. }
  174. } catch (NoSuchActorException $e) {
  175. // not a User, maybe a Note? we'll try that further down...
  176. // try {
  177. // Log::debug(__METHOD__ . ': Finding User_group URI for WebFinger lookup on resource==' . $resource);
  178. // $group = new User_group();
  179. // $group->whereAddIn('uri', array_keys($alt_urls), $group->columnType('uri'));
  180. // $group->limit(1);
  181. // if ($group->find(true)) {
  182. // $profile = $group->getProfile();
  183. // }
  184. // unset($group);
  185. // } catch (Exception $e) {
  186. // Log::error(get_class($e) . ': ' . $e->getMessage());
  187. // throw $e;
  188. // }
  189. }
  190. }
  191. if ($profile instanceof Actor) {
  192. Log::debug(__METHOD__ . ': Found Profile with ID==' . $profile->getID() . ' for resource==' . $resource);
  193. $target = new WebfingerResourceActor($profile);
  194. return Event::stop; // We got our target, stop handler execution
  195. }
  196. $APNote = ActivitypubActivity::getByPK(['object_uri' => $resource]);
  197. if ($APNote instanceof ActivitypubActivity) {
  198. $target = new WebfingerResourceNote(Note::getByPK(['id' => $APNote->getObjectId()]));
  199. return Event::stop; // We got our target, stop handler execution
  200. }
  201. return Event::next;
  202. }
  203. public function onStartHostMetaLinks(array &$links): bool
  204. {
  205. foreach (Discovery::supportedMimeTypes() as $type) {
  206. $links[] = new XML_XRD_Element_Link(
  207. Discovery::LRDD_REL,
  208. Router::url(id: 'freenetwork_webfinger', args: [], type: Router::ABSOLUTE_URL) . '?resource={uri}',
  209. $type,
  210. isTemplate: true,
  211. );
  212. }
  213. // TODO OAuth connections
  214. //$links[] = new XML_XRD_Element_link(self::OAUTH_ACCESS_TOKEN_REL, common_local_url('ApiOAuthAccessToken'));
  215. //$links[] = new XML_XRD_Element_link(self::OAUTH_REQUEST_TOKEN_REL, common_local_url('ApiOAuthRequestToken'));
  216. //$links[] = new XML_XRD_Element_link(self::OAUTH_AUTHORIZE_REL, common_local_url('ApiOAuthAuthorize'));
  217. return Event::next;
  218. }
  219. /**
  220. * Add a link header for LRDD Discovery
  221. */
  222. public function onStartShowHTML($action): bool
  223. {
  224. if ($action instanceof ShowstreamAction) {
  225. $resource = $action->getTarget()->getUri();
  226. $url = common_local_url('webfinger') . '?resource=' . urlencode($resource);
  227. foreach ([Discovery::JRD_MIMETYPE, Discovery::XRD_MIMETYPE] as $type) {
  228. header('Link: <' . $url . '>; rel="' . Discovery::LRDD_REL . '"; type="' . $type . '"', false);
  229. }
  230. }
  231. return Event::next;
  232. }
  233. public function onStartDiscoveryMethodRegistration(Discovery $disco): bool
  234. {
  235. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodWebfinger');
  236. return Event::next;
  237. }
  238. public function onEndDiscoveryMethodRegistration(Discovery $disco): bool
  239. {
  240. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodHostMeta');
  241. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodLinkHeader');
  242. $disco->registerMethod('\Component\FreeNetwork\Util\LrddMethod\LrddMethodLinkHtml');
  243. return Event::next;
  244. }
  245. /**
  246. * @throws ClientException
  247. * @throws ServerException
  248. */
  249. public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?TypeResponse &$response = null): bool
  250. {
  251. if (!\in_array($route, ['freenetwork_hostmeta', 'freenetwork_hostmeta_format', 'freenetwork_webfinger', 'freenetwork_webfinger_format', 'freenetwork_ownerxrd'])) {
  252. return Event::next;
  253. }
  254. $mimeType = array_intersect(array_values(Discovery::supportedMimeTypes()), $accept_header);
  255. /*
  256. * "A WebFinger resource MUST return a JRD as the representation
  257. * for the resource if the client requests no other supported
  258. * format explicitly via the HTTP "Accept" header. [...]
  259. * The WebFinger resource MUST silently ignore any requested
  260. * representations that it does not understand and support."
  261. * -- RFC 7033 (WebFinger)
  262. * http://tools.ietf.org/html/rfc7033
  263. */
  264. $mimeType = \count($mimeType) !== 0 ? array_pop($mimeType) : $vars['default_mimetype'];
  265. $headers = [];
  266. if (Common::config('discovery', 'cors')) {
  267. $headers['Access-Control-Allow-Origin'] = '*';
  268. }
  269. $headers['Content-Type'] = $mimeType;
  270. $response = match ($mimeType) {
  271. Discovery::XRD_MIMETYPE => new Response(content: $vars['xrd']->to('xml'), headers: $headers),
  272. Discovery::JRD_MIMETYPE, Discovery::JRD_MIMETYPE_OLD => new JsonResponse(data: $vars['xrd']->to('json'), headers: $headers, json: true),
  273. };
  274. return Event::stop;
  275. }
  276. /**
  277. * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
  278. *
  279. * @param string $text The text from which to extract webfinger IDs
  280. * @param string $preMention Character(s) that signals a mention ('@', '!'...)
  281. *
  282. * @return array the matching IDs (without $preMention) and each respective position in the given string
  283. */
  284. public static function extractWebfingerIds(string $text, string $preMention = '@'): array
  285. {
  286. $wmatches = [];
  287. $result = preg_match_all(
  288. '/' . Nickname::BEFORE_MENTIONS . preg_quote($preMention, '/') . '(' . Nickname::WEBFINGER_FMT . ')/',
  289. $text,
  290. $wmatches,
  291. \PREG_OFFSET_CAPTURE,
  292. );
  293. if ($result === false) {
  294. Log::error(__METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error==' . preg_last_error() . ').');
  295. return [];
  296. } elseif (($n_matches = \count($wmatches)) != 0) {
  297. Log::debug((sprintf('Found %d matches for WebFinger IDs: %s', $n_matches, print_r($wmatches, true))));
  298. }
  299. return $wmatches[1];
  300. }
  301. /**
  302. * Profile URL matches: @param string $text The text from which to extract URL mentions
  303. *
  304. * @param string $preMention Character(s) that signals a mention ('@', '!'...)
  305. *
  306. * @return array the matching URLs (without @ or acct:) and each respective position in the given string
  307. * @example.com/mublog/user
  308. */
  309. public static function extractUrlMentions(string $text, string $preMention = '@'): array
  310. {
  311. $wmatches = [];
  312. // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
  313. // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
  314. $result = preg_match_all(
  315. '/' . Nickname::BEFORE_MENTIONS . preg_quote($preMention, '/') . '(' . URL_REGEX_DOMAIN_NAME . '(?:\/[' . URL_REGEX_VALID_PATH_CHARS . ']*)*)/',
  316. $text,
  317. $wmatches,
  318. \PREG_OFFSET_CAPTURE,
  319. );
  320. if ($result === false) {
  321. Log::error(__METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error==' . preg_last_error() . ').');
  322. return [];
  323. } elseif (\count($wmatches)) {
  324. Log::debug((sprintf('Found %d matches for profile URL mentions: %s', \count($wmatches), print_r($wmatches, true))));
  325. }
  326. return $wmatches[1];
  327. }
  328. /**
  329. * Find any explicit remote mentions. Accepted forms:
  330. * Webfinger: @user@example.com
  331. * Profile link: @param Actor $sender
  332. *
  333. * @param string $text input markup text
  334. * @param $mentions
  335. *
  336. * @return bool hook return value
  337. * @example.com/mublog/user
  338. */
  339. public function onEndFindMentions(Actor $sender, string $text, array &$mentions): bool
  340. {
  341. $matches = [];
  342. foreach (self::extractWebfingerIds($text, $preMention = '@') as $wmatch) {
  343. [$target, $pos] = $wmatch;
  344. Log::info("Checking webfinger person '{$target}'");
  345. $actor = null;
  346. $resource_parts = explode($preMention, $target);
  347. if ($resource_parts[1] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  348. $actor = LocalUser::getByPK(['nickname' => $resource_parts[0]])->getActor();
  349. } else {
  350. Event::handle('FreeNetworkFindMentions', [$target, &$actor]);
  351. if (\is_null($actor)) {
  352. continue;
  353. }
  354. }
  355. \assert($actor instanceof Actor);
  356. $displayName = !empty($actor->getFullname()) ? $actor->getFullname() : $actor->getNickname() ?? $target; // TODO: we could do getBestName() or getFullname() here
  357. $matches[$pos] = [
  358. 'mentioned' => [$actor],
  359. 'type' => 'mention',
  360. 'text' => $displayName,
  361. 'position' => $pos,
  362. 'length' => mb_strlen($target),
  363. 'url' => $actor->getUri(),
  364. ];
  365. }
  366. foreach (self::extractUrlMentions($text) as $wmatch) {
  367. [$target, $pos] = $wmatch;
  368. $url = "https://{$target}";
  369. if (Common::isValidHttpUrl($url)) {
  370. // This means $resource is a valid url
  371. $resource_parts = parse_url($url);
  372. // TODO: Use URLMatcher
  373. if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  374. $str = $resource_parts['path'];
  375. // actor_view_nickname
  376. $renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m';
  377. // actor_view_id
  378. $reuri = '/\/actor\/(\d+)\/?/m';
  379. if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  380. $actor = LocalUser::getByPK(['nickname' => $matches[0][1]])->getActor();
  381. } elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) {
  382. $actor = Actor::getById((int) $matches[0][1]);
  383. } else {
  384. Log::error('Unexpected behaviour onEndFindMentions at FreeNetwork');
  385. throw new ServerException('Unexpected behaviour onEndFindMentions at FreeNetwork');
  386. }
  387. } else {
  388. Log::info("Checking actor address '{$url}'");
  389. $link = new XML_XRD_Element_Link(
  390. Discovery::LRDD_REL,
  391. 'https://' . parse_url($url, \PHP_URL_HOST) . '/.well-known/webfinger?resource={uri}',
  392. Discovery::JRD_MIMETYPE,
  393. true, // isTemplate
  394. );
  395. $xrd_uri = Discovery::applyTemplate($link->template, $url);
  396. $response = HTTPClient::get($xrd_uri, ['headers' => ['Accept' => $link->type]]);
  397. if ($response->getStatusCode() !== 200) {
  398. continue;
  399. }
  400. $xrd = new XML_XRD();
  401. switch (GSFile::mimetypeBare($response->getHeaders()['content-type'][0])) {
  402. case Discovery::JRD_MIMETYPE_OLD:
  403. case Discovery::JRD_MIMETYPE:
  404. $type = 'json';
  405. break;
  406. case Discovery::XRD_MIMETYPE:
  407. $type = 'xml';
  408. break;
  409. default:
  410. // fall back to letting XML_XRD auto-detect
  411. Log::debug('No recognized content-type header for resource descriptor body on ' . $xrd_uri);
  412. $type = null;
  413. }
  414. $xrd->loadString($response->getContent(), $type);
  415. $actor = null;
  416. Event::handle('FreeNetworkFoundXrd', [$xrd, &$actor]);
  417. if (\is_null($actor)) {
  418. continue;
  419. }
  420. }
  421. $displayName = $actor->getFullname() ?? $actor->getNickname() ?? $target; // TODO: we could do getBestName() or getFullname() here
  422. $matches[$pos] = [
  423. 'mentioned' => [$actor],
  424. 'type' => 'mention',
  425. 'text' => $displayName,
  426. 'position' => $pos,
  427. 'length' => mb_strlen($target),
  428. 'url' => $actor->getUri(),
  429. ];
  430. }
  431. }
  432. foreach ($mentions as $i => $other) {
  433. // If we share a common prefix with a local user, override it!
  434. $pos = $other['position'];
  435. if (isset($matches[$pos])) {
  436. $mentions[$i] = $matches[$pos];
  437. unset($matches[$pos]);
  438. }
  439. }
  440. foreach ($matches as $mention) {
  441. $mentions[] = $mention;
  442. }
  443. return Event::next;
  444. }
  445. public static function notify(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool
  446. {
  447. $protocols = [];
  448. Event::handle('AddFreeNetworkProtocol', [&$protocols]);
  449. $delivered = [];
  450. foreach ($protocols as $protocol) {
  451. $protocol::freeNetworkDistribute($sender, $activity, $targets, $reason, $delivered);
  452. }
  453. $failed_targets = array_udiff($targets, $delivered, fn (Actor $a, Actor $b): int => $a->getId() <=> $b->getId());
  454. // TODO: Implement failed queues
  455. return false;
  456. }
  457. public function onPluginVersion(array &$versions): bool
  458. {
  459. $versions[] = [
  460. 'name' => 'WebFinger',
  461. 'version' => self::PLUGIN_VERSION,
  462. 'author' => 'Mikael Nordfeldth',
  463. 'homepage' => GNUSOCIAL_ENGINE_URL,
  464. // TRANS: Plugin description.
  465. 'rawdescription' => _m('WebFinger and LRDD support'),
  466. ];
  467. return true;
  468. }
  469. }